<template>
    <el-dialog v-model='dialogVisible' :title='dialogTitle' v-bind='dialogMiddle' @close="close">
        <el-form :model='formContent' ref='dialogFormRef' :rules='rules' class='form-two'>
          <el-divider >基础数据</el-divider>
          <el-form-item label='数据模型' :label-width='140' prop='dataType'>
            <el-select v-model="formContent.dataType"  clearable placeholder="请选择数据模型">
            <el-option
              v-for="item in dictStore.getDictData('Cs_Data_Type')"
              :key="item.id"
              :label="item.name"
              :value="item.code"
            />
          </el-select>
          </el-form-item>
          <el-form-item label='指标名称' :label-width='140' prop='name'>
            <el-input v-model='formContent.name' placeholder='请输入' autocomplete='off' />
          </el-form-item>
          <el-form-item label='别名' :label-width='140' prop='otherName'>
            <el-input v-model='formContent.otherName' placeholder='请输入' autocomplete='off' />
          </el-form-item>
          <el-form-item label='显示名称' :label-width='140' prop='showName'>
            <el-input v-model='formContent.showName' placeholder='请输入' autocomplete='off' />
          </el-form-item>
          <el-form-item label='相别' :label-width='140' prop='phase'>
            <el-select v-model="formContent.phase"  clearable placeholder="请选择相别">
            <el-option
              v-for="item in dictStore.getDictData('phase')"
              :key="item.id"
              :label="item.name"
              :value="item.code"
            />
          </el-select>
          </el-form-item>
          <el-form-item label='单位' :label-width='140' prop='unit'>
            <el-input v-model='formContent.unit' placeholder='请输入单位' autocomplete='off' />
          </el-form-item>
          <el-form-item label='指标数据类型' :label-width='140' prop='type'>
            <el-input v-model='formContent.type' placeholder='请输入指标数据类型' autocomplete='off' />
          </el-form-item>
          <el-form-item label='次数' :label-width='140'>
            <el-row :gutter="20">
              <el-col :span="11">
                <el-input v-model="formContent.harmStart" placeholder="请输入起始次数" autocomplete="off" />
              </el-col>
              <el-col :span="2" class="text-center" style="line-height: 32px;">-</el-col>
              <el-col :span="11">
                <el-input v-model="formContent.harmEnd" placeholder="请输入结束次数" autocomplete="off" />
              </el-col>
            </el-row>
          </el-form-item>
          <el-form-item label='数据统计类型' :label-width='140' prop='statMethod'>
            <el-select v-model="selectedStatMethods" multiple   placeholder="请选择数据统计类型">
              <el-option
              v-for="item in dictStore.getDictData('Stat_Method')"
              :key="item.value"
              :label="item.name"
              :value="item.code"
            />
          </el-select>
          </el-form-item>
          <el-form-item label='系统类别' :label-width='140' prop='systemType'>
            <el-input v-model='formContent.systemType' placeholder='请输入' autocomplete='off' />
          </el-form-item>
          <el-form-item label='报表数据来源' :label-width='140' prop='resourcesId'>
            <el-select v-model="formContent.resourcesId"  clearable placeholder="请选择报表数据来源">
            <el-option
              v-for="item in dictStore.getDictData('Data_Day')"
              :key="item.id"
              :label="item.name"
              :value="item.code"
            />
          </el-select>
          </el-form-item>
          <el-form-item label='数据表表名' :label-width='140' prop='classId'>
            <el-select v-model="formContent.classId"  clearable placeholder="请选择数据表表名">
            <el-option
              v-for="item in dictStore.getDictData('Data')"
              :key="item.id"
              :label="item.name"
              :value="item.code"
            />
          </el-select>
          </el-form-item>
          <el-form-item label='限值字段名称' :label-width='140' prop='limitName'>
            <el-input v-model='formContent.limitName' placeholder='请输入限值字段名称' autocomplete='off' />
          </el-form-item>
          <el-form-item label='限值表名' :label-width='140' prop='limitTable'>
            <el-input v-model='formContent.limitTable' placeholder='请输入限值表名' autocomplete='off' />
          </el-form-item>
          <el-form-item label='超标判断方式' :label-width='140' prop='formula'>
            <el-select v-model="formContent.formula"  clearable placeholder="请选择超标判断方式">
            <el-option
              v-for="item in dictStore.getDictData('Limit_Value_Judgment')"
              :key="item.id"
              :label="item.name"
              :value="item.code"
            />
          </el-select>
          </el-form-item>
          <el-form-item label='排序' :label-width='140'>
            <el-input-number v-model='formContent.sort' :min='1' :max='999' />
          </el-form-item>
          <el-divider >拓展数据</el-divider>
          <el-form-item label='参数缺省值' :label-width='140' prop='defaultValue'>
            <el-input v-model='formContent.defaultValue' placeholder='请输入参数缺省值' autocomplete='off' />
          </el-form-item>
          <el-form-item label='事件类别' :label-width='140' prop='eventType'>
            <el-input v-model='formContent.eventType' placeholder='请输入事件类别' autocomplete='off' />
          </el-form-item>
          <el-form-item label='设置最大值' :label-width='140' prop='maxNum'>
            <el-input-number v-model='formContent.maxNum'  controls-position="right" style="width: 300px;"/>
          </el-form-item>
          <el-form-item label='设置最小值' :label-width='140' prop='minNum'>
            <el-input-number v-model='formContent.minNum'  controls-position="right" style="width: 300px;"/>
          </el-form-item>
          <el-form-item label='枚举序列' :label-width='140' prop='setValue'>
            <el-input v-model='formContent.setValue' placeholder='请输入枚举序列' autocomplete='off' />
          </el-form-item>
          <el-form-item label='字符串长度上限' :label-width='140' prop='strlen'>
            <el-input-number v-model='formContent.strlen'  controls-position="right" style="width: 300px;"/>
          </el-form-item>
          <el-form-item label='上送规则' :label-width='140' prop='tranRule'>
            <el-input v-model='formContent.tranRule' placeholder='请输入上送规则' autocomplete='off' />
          </el-form-item>
          <el-form-item label='当前值' :label-width='140' prop='curSts'>
            <el-input v-model='formContent.curSts' placeholder='请输入当前值' autocomplete='off' />
          </el-form-item>
          <el-form-item label='二次值转一次值公式' :label-width='140' prop='primaryFormula'>
            <el-input v-model='formContent.primaryFormula' placeholder='请输入公式' autocomplete='off' />
          </el-form-item>
          <el-form-item label="是否可远程控制" :label-width="140">
            <el-radio-group v-model="formContent.ctlSts" >
              <el-radio label="是" :value="1"></el-radio>
              <el-radio label="否" :value="0"></el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="是否存储" :label-width="140">
            <el-radio-group v-model="formContent.storeFlag" >
              <el-radio label="是" :value="1"></el-radio>
              <el-radio label="否" :value="0"></el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="数据是否上送" :label-width="140">
            <el-radio-group v-model="formContent.tranFlag" >
              <el-radio label="是" :value="1"></el-radio>
              <el-radio label="否" :value="0"></el-radio>
            </el-radio-group>
          </el-form-item>
         
        </el-form>
     
      <template #footer>
        <div class='dialog-footer'>
          <el-button @click='close()'>取消</el-button>
          <el-button type='primary' @click='save()'>
            保存
          </el-button>
        </div>
      </template>
    </el-dialog>
  </template>
  <script setup lang='ts'>
  import { dialogMiddle } from '@/utils/elementBind'
  import { type Dict } from '@/api/system/dictionary/interface'
  import { ElMessage, type FormItemRule } from 'element-plus'
  import { addDictPq, updateDictPq } from '@/api/system/dictionary/dictPq'
  import { computed, type Ref, ref } from 'vue';
  import { useDictStore } from '@/stores/modules/dict'
  const dictStore = useDictStore()
  const selectedStatMethods = ref<string[]>([])
  // 定义弹出组件元信息
  const dialogFormRef = ref()
  function useMetaInfo() {
    const dialogVisible = ref(false)
    const titleType = ref('add')
    const formContent = ref<Dict.ResDictPq>({
      id: '',
      name: '',
      phase: '',
      sort: 100,
      dataType: '',
      state: 1,
      classId: '',
    })
    return { dialogVisible, titleType, formContent }
  }
  
  const { dialogVisible, titleType, formContent } = useMetaInfo()
  // 清空formContent
  const resetFormContent = () => {
    formContent.value = {
      id: '',
      name: '',
      phase: '',
      sort: 100,
      dataType: '',
      state: 1,
      classId: '',
    }
  }
  
  let dialogTitle = computed(() => {
    return titleType.value === 'add' ? '新增字典' : '编辑字典'
  })
  
  // 定义表单校验规则
  const rules: Ref<Record<string, Array<FormItemRule>>> = ref({
    dataType: [{ required: true, message: '数据模型必选！', trigger: 'change' }],
    name: [{ required: true, message: '指标名称必填！', trigger: 'blur' }],
    phase: [{ required: true, message: '相别必选！', trigger: 'change' }],
    classId: [{ required: true, message: '数据库表名必选！', trigger: 'change' }],
  })
  
  // 关闭弹窗
  const close = () => {
    dialogVisible.value = false
    // 清空dialogForm中的值
    resetFormContent()
    // 重置表单
    dialogFormRef.value?.resetFields()
    selectedStatMethods.value = []
  }
  
  // 保存数据
  const save = () => {
    try {
        dialogFormRef.value?.validate(async (valid: boolean) => {
        if (valid) {
          formContent.value.statMethod = selectedStatMethods.value.join(',')
          if (formContent.value.id) {
            await updateDictPq(formContent.value);
          } else {
            await addDictPq(formContent.value);
          }
          ElMessage.success({ message: `${dialogTitle.value}成功！` })
          close()
          // 刷新表格
          await props.refreshTable!()
        }
      })
    } catch (err) {
      console.error('验证过程中出现错误', err)
    }
  }
  
  // 打开弹窗，可能是新增，也可能是编辑
  const open = (sign: string, data: Dict.ResDictPq) => {
    titleType.value = sign
    dialogVisible.value = true
    selectedStatMethods.value = data.statMethod ? data.statMethod.split(',') : []
    if (data.id) {
      formContent.value = { ...data }
    } else {
      resetFormContent()
    }
  }
  
  // 对外映射
  defineExpose({ open })
  const props = defineProps<{
    refreshTable: (() => Promise<void>) | undefined;
  }>()
  

  
  </script>