<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="oilStation">
              <el-input v-model="formData.editData.oilStation" 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="projectName">
              <el-input v-model="formData.editData.projectName" 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="设备SN" prop="sn">
              <el-input v-model="formData.editData.sn" placeholder="请输入设备SN号" 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="key">
              <el-input v-model="formData.editData.key" 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="expiedTime">
              <el-date-picker
                v-model="formData.editData.expiedTime"
                type="datetime"
                value-format="YYYY-MM-DD HH:mm:ss"
                placeholder="选择有效时间"
              />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
            <el-form-item label="状态" prop="state">
              <el-select v-model="formData.editData.state" class="m-2" placeholder="选择状态" >
                <el-option
                  v-for="item in formData.options"
                  :key="item.value"
                  :label="item.label"
                  :value="item.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="remark">
              <el-input v-model="formData.editData.remark" placeholder="请输入备注" rows="6" clearable type="textarea"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </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 {reactive, ref, watch} from "vue";
import {oilSdkTableModel} from "/@/api/admin/deviceAuthorization/oilSdkAuthorDto";
import {OilSdkAuthorAPI} from "/@/api/admin/deviceAuthorization/oilSdkAuthor";
import eventBus from "/@/utils/mitt";
import {FormRules} from "element-plus";

enum Form {
  ADD,
  UPDATE
}

/**数据对象 */
const formData = reactive({
  loading: false,
  formType: Form,
  titleText:'',
  editIcon:'',
  buttonText:'',
  isShowDialog: false,
  editData:{} as oilSdkTableModel,
  // /**动态表头 */
  // dynamicColumns: [
  //   { prop: 'oilStation', label: '油站名称' },
  //   { prop: 'projectName', label: '项目名称' },
  //   { prop: 'sn', label: '设备SN号' },
  //   { prop: 'key', label: '授权码' },
  //   { prop: 'expiedTime', label: '过期时间' },
  //   { prop: 'formData', label: '状态' },
  //   { prop: 'remark', label: '备注' },
  // ],
  options:[
    {label:'正常',value:'正常'},
    {label:'未授权',value:'未授权'},
  ]
})

/**有效时间选择校验*/
const validateDate = (rule: any, value: any, callback: any) => {
  if(new Date(value).getTime() > Date.now()){
    callback()
  }else{
    callback(new Error('选择的时间已失效'))
  }
}

/**表单校验*/
const rules = reactive<FormRules>({
  oilStation: [
    { required: true, message: '请输入油站名称', trigger: 'blur' },
  ],
  projectName: [
    { required: true, message: '请输入项目名称', trigger: 'blur' },
  ],
  sn: [
    { required: true, message: '请输入设备SN号', trigger: 'blur' },
  ],
  key: [
    { required: true, message: '请输入设备授权码', trigger: 'blur' },
  ],
  expiedTime: [
    { type: 'date', required: true, message: '请选择有效期', trigger: 'blur' },
    { validator: validateDate, trigger: 'blur' }
  ],
  state: [
    { required: true, message: '请选择状态', 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 oilSdkTableModel
    formData.titleText = '添加授权'
    formData.buttonText = '添加'
    //添加操作
    formData.formType = Form.ADD
    formData.editIcon = 'ele-CirclePlus'
  }
  formData.isShowDialog = true
  formData.isShowDialog = true
}

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

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

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

    formData.loading = true
    // eslint-disable-next-line @typescript-eslint/no-unused-vars,no-unused-vars
    const { projectName, state, ...newData} = formData.editData
    let res = {} as any
    if(formData.formType === Form.UPDATE){
      res = await new OilSdkAuthorAPI().updateForm({project: formData.editData.projectName, state: formData.editData.state === '正常' ? 1 : 0 ?? 0,  ...newData},{ showSuccessMessage: true }).catch(() => {
        formData.loading = false
      })
    }else if(formData.formType === Form.ADD){
      res = await new OilSdkAuthorAPI().addForm({project: formData.editData.projectName, state: formData.editData.state === '正常' ? 1 : 0 ?? 0,  ...newData},{ showSuccessMessage: true }).catch(() => {
        formData.loading = false
      })
    }else {
      formData.loading = false
      return
    }

    if(res?.success){
      console.log('2')
      eventBus.emit('refreshView')
      formData.isShowDialog = false
      formData.editData = {} as oilSdkTableModel
    }

    formData.loading = false
  })
}

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

</style>
