<template>
  <div class="admin-authorize-editInfo">
    <el-dialog :title="formData.titleText" v-model="formData.isShowDialog" draggable width="769px">
      <el-form :model="formData.editData"
               :rules="rules"
               ref="formRef"
               v-loading="formData.loading"
               size="default"
               label-width="80px">
        <el-row :gutter="35">
          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
            <el-form-item label="软件类型" prop="softwareType">
              <el-select  v-model="formData.editData.softwareType" placeholder="请选择软件类型" >
                <el-option v-for="(value, key) in softwareType" :key="key" :label="value[1].name"  :value="Number(value[1].value)" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
            <el-form-item label="设备类型" prop="equipmentType">
              <el-select  v-model="formData.editData.equipmentType" placeholder="请选择设备类型" >
                <el-option v-for="(value, key) in equipmentType" :key="key" :label="value[1].name"  :value="Number(value[1].value)" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
            <el-form-item label="软件包名" prop="softwareName">
              <el-input v-model="formData.editData.softwareName" placeholder="请输入软件包名" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
            <el-form-item label="版本" prop="version">
              <el-input v-model="formData.editData.version" placeholder="请输入版本" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
            <el-form-item label="说明" prop="explain">
              <el-input v-model="formData.editData.explain" placeholder="请输入说明" rows="6" clearable type="textarea"></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="formData.editData.remark" placeholder="请输入备注" rows="6" clearable type="textarea"></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
            <el-form-item label="数字签名" prop="digitalSignature">
              <el-input v-model="formData.editData.digitalSignature" placeholder="数字签名，TQC+、ECVR、OPW必填" clearable></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <MyUploadFile  v-model="formData.fileValue" ref="uploadFileRef" :file="{fileUrl:formData.editData.downloadUrl,fileName:formData.editData.fileName}"  @onUpload="onUpload"/>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="onCancel" icon="ele-CircleClose" size="default">取 消</el-button>
          <el-button type="primary" :icon="formData.editIcon" @click="onSubmit" size="default">{{formData.buttonText}}</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import {defineAsyncComponent, reactive, ref, watch} from "vue";
import {FormRules} from "element-plus";
import eventBus from "/@/utils/mitt";
import {softwarePackageManagement_TableData} from "/@/api/admin/deviceAuthorization/softwarePackageManagementDto";
import {useGlobalCacheStore} from "/@/stores/globalCacheStore";
import {SoftwarePackageManagementApi} from "/@/api/admin/deviceAuthorization/softwarePackageManagementApi";
//import { de } from "element-plus/es/locale";

const MyUploadFile = defineAsyncComponent(() => import('/@/components/my-upload-file/index.vue'))

/**获取全局缓存*/
const globalCacheStore = useGlobalCacheStore()
/**设备类型缓存*/
const equipmentType = ref(globalCacheStore.getGlobalStore().get('equipmentType'))
/**软件类型缓存*/
const softwareType = ref(globalCacheStore.getGlobalStore().get('softwareType'))

enum Form {
  ADD,
  UPDATE
}


/**数据对象 */
const formData = reactive({
  loading: false,
  formType: Form,
  titleText:'',
  editIcon:'',
  buttonText:'',
  isShowDialog: false,
  editData:{} as softwarePackageManagement_TableData,
  fileValue: null,
})
/**有效版本号选择校验*/
const validateVersion = (rule: any, value: any, callback: any) => {
  const versionPattern: RegExp = /^\d+\.\d+\.\d+$/; // 正则表达式，以数字开头和结尾，并且包含数字和点号（.）
  if (!versionPattern.test(value)) {
    callback(new Error('输入的版本号格式错误'))
  } else {
    callback()
  }
}


/**表单校验*/
const rules = reactive<FormRules>({
  softwareType: [
    { required: true, message: '请选择软件类型', trigger: 'blur' },
  ],
  equipmentType: [
    { required: true, message: '请选择设备类型', trigger: 'blur' },
  ],
  softwareName: [
    { required: true, message: '请输入软件包名', trigger: 'blur' },
  ],
  version: [
    { required: true, message: '请输入版本号', trigger: 'blur' },
    { validator: validateVersion, trigger: 'blur' }
  ],
})

/**
 * 表单对象
 */
const formRef = ref()

const openDialog = (val) => {
  if(val){
    formData.editData = JSON.parse(JSON.stringify(val))
    formData.titleText = '更新软件包'
    formData.buttonText = '更新'
    //更新操作
    formData.formType = Form.UPDATE
    formData.editIcon = 'ele-Refresh'
  }else {
    formData.editData = {} as softwarePackageManagement_TableData
    formData.titleText = '添加软件包'
    formData.buttonText = '添加'
    //添加操作
    formData.formType = Form.ADD
    formData.editIcon = 'ele-CirclePlus'
  }
  formData.isShowDialog = true
  formData.isShowDialog = true
}

const onCancel = () => {
  formData.editData = {} as softwarePackageManagement_TableData
  formData.isShowDialog = false
}

/***监听弹窗关   闭表单验证*/
watch(() => formData.isShowDialog,(newVal) => {
  if(newVal) formRef.value?.resetFields()
})

const onUpload = (val) => {
  formData.editData.downloadUrl = val.fileUrl
  formData.editData.fileName = val.fileName
  //MyUploadFile.value?.onSure();
}

const uploadFileRef = ref(null);

const onSubmit =  () => {
debugger
  formRef.value.validate(async (valid: boolean) =>{
    if(!valid) return

    formData.loading = true
    let res = {} as any
    console.log(formData.editData)
    if(formData.formType === Form.UPDATE){
      res = await new SoftwarePackageManagementApi().addData(formData.editData as softwarePackageManagement_TableData)
    }else if(formData.formType === Form.ADD){
      res = await new SoftwarePackageManagementApi().addData(formData.editData as softwarePackageManagement_TableData)
    }else {
      formData.loading = false
      return
    }

    if(res?.success){
      eventBus.emit('refreshView')
      formData.isShowDialog = false
      formData.editData = {} as softwarePackageManagement_TableData
    }

    formData.loading = false
  })
}

defineExpose({
  openDialog,
})
</script>
<style scoped lang="scss">

</style>
