<template>
  <el-dialog width="500px" append-to-body :title="isEdit ? '修改数据字典' : '新增数据字典'" v-model="visible" @close="handleClose">
    <el-form :model="formData" ref="formRef" label-width="120px" :rules="formRules">
      <el-form-item label="字典归属" prop="dictLevel">
        <el-select
              v-model="formData.dictLevel"
              placeholder="请选择字典归属"
              maxlength="30"
              @change="changeCodeType"
            >
              <el-option
                v-for="dict in std_code_status"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              ></el-option>
            </el-select>
        </el-form-item>
        <el-form-item label="来源系统" prop="sysId" v-show="showSys">
        <el-select
              v-model="formData.sysId"
              placeholder="请选择来源系统"
              maxlength="30"
              @change="dataChange"
            >
              <el-option
                v-for="dict in dbResourceOldList"
                :key="dict.id"
                :label="dict.name"
                :value="dict.id"
              ></el-option>
            </el-select>  
        </el-form-item>
        <el-form-item label="数据字典类型" prop="dictType">
        <el-select v-model="formData.dictType" placeholder="请选择数据字典类型">
          <el-option label="基础数据" value="0" />
          <el-option label="指标数据" value="1" />
        </el-select>    
        </el-form-item>
      <el-form-item label="数据字典编号" prop="dictNum">
        <el-input v-model="formData.dictNum" :disabled=isEdit placeholder="请输入数据字典编号" clearable />
      </el-form-item>
      <el-form-item label="字典英文名" prop="dictCode">
        <el-input v-model="formData.dictCode" placeholder="请输入字典英文名" clearable />
      </el-form-item>
      <el-form-item label="字典中文名" prop="dictName">
        <el-input v-model="formData.dictName" placeholder="请输入字典中文名" clearable />
      </el-form-item>
      <el-form-item label="字典业务定义" prop="dictMenu">
        <el-input v-model="formData.dictMenu" placeholder="请输入字典中文名" clearable />
      </el-form-item>
      <el-form-item label="数据类型" prop="dataType">
        <el-input v-model="formData.dataType" placeholder="请输入字典中文名" clearable />
      </el-form-item>
      <el-form-item label="数据标准" prop="stdCode">
        <el-input v-model="formData.stdCode" placeholder="请输入字典中文名" clearable />
      </el-form-item>
      <el-form-item label="业务认责部门" prop="bussDeptId">
                     <el-tree-select
                        v-model="formData.bussDeptId"
                        :data="deptOptions"
                        :props="{ value: 'id', label: 'label', children: 'children' }"
                        value-key="id"
                        placeholder="请选择业务认责部门"
                        check-strictly />
     </el-form-item>
     <el-form-item label="业务认责人员" prop="bussUser">
        <el-select v-model="formData.bussUser" placeholder="请选择业务认责人员">
          <el-option
                v-for="dict in userList"
                :key="dict.id"
                :label="dict.userName"
                :value="dict.userName"
              ></el-option>
        </el-select>    
        </el-form-item>
     <el-form-item label="技术认责部门" prop="techDeptId">
                     <el-tree-select
                        v-model="formData.techDeptId"
                        :data="deptOptions"
                        :props="{ value: 'id', label: 'label', children: 'children' }"
                        value-key="id"
                        placeholder="请选择技术认责部门"
                        check-strictly />
     </el-form-item>
     <el-form-item label="技术认责人员" prop="techUser">
        <el-select v-model="formData.techUser" placeholder="技术认责人员">
          <el-option
                v-for="dict in userList"
                :key="dict.id"
                :label="dict.userName"
                :value="dict.userName"
              ></el-option>
        </el-select>    
        </el-form-item>

         <!-- 底部按钮区域 -->
         <el-row justify="center" style="margin-top: 20px;">
        <el-col :span="4" style="padding-right: 10px;">
          <el-button @click="handleClose" style="width: 100%" plain>取消</el-button>
        </el-col>
        <el-col :span="4" style="padding-left: 10px;">
          <el-button type="primary" @click="handleSubmit" style="width: 100%">保存</el-button>
        </el-col>
      </el-row>
  

    </el-form>
  </el-dialog>
</template>

<script setup>
import { ref, watch } from 'vue';
import { updateStdDict, addStdDict } from '@/api/datastd/std'; // 确保接口存在
import {  listUser,  deptTreeSelect } from "@/api/system/user";
const { proxy } = getCurrentInstance();
const { std_code_status,std_code_appr } = proxy.useDict("std_code_status","std_code_appr");

const props = defineProps({
  data: {
    type: Object,
    required: false,
  },
  isEdit: {
    type: Boolean,
  },
  dbResourceOldList: {
    type: Object,
  },
  visible: {
    type: Boolean,
  },
});
// 定义表单校验规则
const formRules = ref({
  dictLevel: [{ required: true, message: '请选择字典归属', trigger: 'blur' }],
  dictType: [{ required: true, message: '请选择数据字典类型', trigger: 'blur' }],
  dictNum: [{ required: true, message: '请输入数据字典编号', trigger: 'blur' }]
});
const showSys = ref(false);
const emit = defineEmits(['update:visible', 'refresh']);
const userList = ref([]);
const formData = ref({ ...props.data });
const visible = ref(props.visible);  // 使用 prop 传入的 visible
function dataChange(data) {
  // 从 dbResourceOldList 中查找对应的 name
  const selectedItem = props.dbResourceOldList.find(item => item.id === data);
  if (selectedItem) {
    // 如果找到对应的项，将 name 赋值给 formData.value.dbRName
    formData.value.sysName = selectedItem.name;
  } else {
    // 如果未找到，清空 formData.value.dbRName
    formData.value.sysName = '';
  }
}
// 监听 props.visible 的变化，确保同步到 local visible
watch(() => props.visible, (newVal) => {
  visible.value = newVal;
  formData.value = { ...props.data }
});

function getList() {
  listUser({pageSize:1000,pageNum:1}).then(res => {
    userList.value = res.rows;
  });
};
const handleClose = () => {
  emit('update:visible', false);  // 关闭弹框
};
const deptOptions = ref(undefined);

function getDeptTree() {
  deptTreeSelect().then(response => {
    deptOptions.value = response.data;
  });
};
function changeCodeType(data) {
  if (data != "company") {
    showSys.value = true;
    formData.value.sysName = "";
    formData.value.sysId = undefined;
  } else {
    showSys.value = false;
    formData.value.sysName = "公司级";
    formData.value.sysId = 10000;
  }
}
getDeptTree();
getList();
const handleSubmit = () => {
  const formRef = proxy.$refs.formRef;
  formRef.validate((valid) => {
    if (valid) {
      const apiCall = props.isEdit ? updateStdDict(formData.value) : addStdDict(formData.value);
      apiCall
        .then(() => {
          emit('refresh');
          handleClose();
        })
        .catch((error) => {
          console.error(error);
        });
    } else {
      console.log('表单验证失败');
      return false;
    }
  });
};
</script>
