<template>
  <el-dialog :title="dialogTitle" v-model='dialogVisible' @close="close" v-bind="dialogBig" >
    <div >
      <el-form :model="formContent" ref='dialogFormRef' :rules='rules' >
        <el-row :gutter="24">
          <el-col :span="8">
            <el-form-item label="检测源名称" prop="name" >
              <el-input v-model='formContent.name' placeholder="源类型+源型号+数字"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="源型号" prop="devType" >
              <el-select v-model='formContent.devType' placeholder="请选择源型号">
                <el-option
                    v-for="item in dictStore.getDictData(dictTypeCode)"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="源类型" prop="type">
              <el-select v-model='formContent.type' placeholder="请选择源类型">
                <el-option
                    v-for="item in dictStore.getDictData('Pq_Source_Type')"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>

    <ParameterTable :parameterStr="formContent.parameter" @change-parameter="changeParameter" ref="parameterTable"/>
    <template #footer>
      <div>
        <el-button @click='close()'>取 消</el-button>
        <el-button type="primary" @click='save()'>保存</el-button>
      </div>
    </template>
  </el-dialog>


</template>

<script lang="ts" setup name="ErrorSystemDialog">
import {ElMessage, type FormItemRule} from 'element-plus'
import {computed, defineProps, Ref, ref} from 'vue';
import {dialogBig} from '@/utils/elementBind'
import {addTestSource, getTestSourceById, updateTestSource} from '@/api/device/testSource/index'
import {useDictStore} from '@/stores/modules/dict'
import {type TestSource} from '@/api/device/interface/testSource';
// 定义弹出组件元信息
const dialogFormRef = ref()
const dictStore = useDictStore()
const mode = ref()
const modeId = ref()
const parameterTable = ref()


function useMetaInfo() {
  const dialogVisible = ref(false)
  const titleType = ref('add')
  const formContent = ref<TestSource.ResTestSource>({
    id: '',
    name: '',
    pattern: modeId.value,
    parameter: '',
    type: '',
    devType: '',
    state: 1,
  })
  return {dialogVisible, titleType, formContent}
}

const {dialogVisible, titleType, formContent} = useMetaInfo()
// 清空formContent
const resetFormContent = () => {
  formContent.value = {
    id: '',
    name: '',
    pattern: modeId.value,
    parameter: '',
    type: '',
    devType: '',
    state: 1,
  }
}

let dialogTitle = computed(() => {
  return titleType.value === 'add' ? '新增检测源' : '编辑检测源'
})

let dictTypeCode = computed(() => {
  return 'S_Dev_Type_' + dictStore.getDictData('Pattern').find(item => item.id === modeId.value)?.code
})
// 定义规则
const rules: Ref<Record<string, Array<FormItemRule>>> = ref({
  name: [{required: true, message: '检测源名称必填！', trigger: 'blur'}],
  devType: [{required: true, message: '请选择一项设备类型', trigger: 'change'},],
  type: [{required: true, message: '请选择一项检测源类型', trigger: 'change '},]
});


// 关闭弹窗
const close = () => {
  dialogVisible.value = false
  // 清空dialogForm中的值
  resetFormContent()
  // 重置表单
  dialogFormRef.value?.resetFields()
  parameterTable.value?.clearData()
}

// 保存数据
const save = () => {
  try {
    dialogFormRef.value?.validate(async (valid: boolean) => {
      if (valid) {
        if (formContent.value.id) {
          await updateTestSource(formContent.value);
          ElMessage.success({message: `${dialogTitle.value}成功！`})
        } else {
          await addTestSource(formContent.value);
          ElMessage.success({message: `${dialogTitle.value}成功！`})
        }
        close()
        // 刷新表格
        await props.refreshTable!()
      }
    })
  } catch (err) {
    console.error('验证过程中出现错误', err)
  }
}

// 打开弹窗，可能是新增，也可能是编辑
const open = async (sign: string, data: TestSource.ResTestSource, currentMode: string) => {
  titleType.value = sign
  dialogVisible.value = true
  mode.value = currentMode
  modeId.value = dictStore.getDictData('Pattern').find(item => item.name === currentMode)?.id;
  if (data.id) {
    const result = await getTestSourceById(data);
    if (result && result.data) {
      formContent.value = result.data as TestSource.ResTestSource;
    }
  } else {
    resetFormContent()
  }
  // 重置表单
  dialogFormRef.value?.resetFields()
}

const changeParameter = (parameterArr) => {
  formContent.value.parameter = JSON.stringify(parameterArr)
}

// 对外映射
defineExpose({open})
const props = defineProps<{
  refreshTable: (() => Promise<void>) | undefined;
}>()
</script>
<style>
</style>
  
