<template>
  <el-dialog :title="dialogTitle" v-model='dialogVisible' @close="close" v-bind="dialogBig">
    <div >
      <el-form :model="formContent" ref='dialogFormRef' :rules='rules' :disabled="tableIsDisable" label-width="auto" class="form-three">
            <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-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-form>
    </div>

    <ParameterTable :parameterStr="formContent.parameter" @change-parameter="changeParameter" ref="parameterTable"  :is-disable="tableIsDisable"/>
    <template #footer>
      <div>
        <el-button :disabled="tableIsDisable" @click='close()'>取 消</el-button>
        <el-button :disabled="tableIsDisable" 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()
const tableIsDisable = ref(true)

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

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

let dialogTitle = computed(() => {
  switch (titleType.value) {
    case 'add':
      tableIsDisable.value = false
      return '新增检测源';
    case 'edit':
      tableIsDisable.value = false
      return '编辑检测源';
    case 'view':
      tableIsDisable.value = true
      return '查看检测源';
    default:
      return ''; // 默认情况，可选
  }
});

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: any) => {
  formContent.value.parameter = JSON.stringify(parameterArr)
}

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