<template>
  <!-- 评聘安全工程师 -->
  <div>
    <el-dialog v-model="dialogVisible" :title="formData && formData.id ? '修改人才' : '新增人才'" :before-close="close"
      width="800px" append-to-body>
      <div class="form-container">
        <el-form class="mosty-from-wrap" ref="formRef" label-width="130px" :model="formData" :inline="true"
          :rules="rules" style="flex-wrap: wrap;">
          <el-form-item label="人员:" prop="userName" style="width: calc(48% - 20px);">
            <el-input v-model="formData.userName" clearable placeholder="请选择人员" readonly
              @click.stop.prevent="chooseUserVisible = true">
            </el-input>
          </el-form-item>
          <el-form-item label="工作经验:" prop="workExperience" style="width: calc(48% - 20px);">
            <!-- <el-date-picker v-model="formData.workExperience" type="date" value-format="YYYY-MM-DD"
              placeholder="工作经验" /> -->
            <el-input v-model="formData.workExperience" clearable type="number" style="width: 100%">
              <template #append>年</template>
            </el-input>
          </el-form-item>
          <el-form-item label="层级类型:" prop="levelType" style="width: calc(48% - 20px);">
            <MOSTY.Select v-model="formData.levelType" :options="props.dic.D_BZ_CJLX" style="width: 337px;"
              placeholder="请选择层级类型">
              <!-- <option v-for="item in props.dic.D_BZ_CJLX" :key="item.value" :label="item.label"
                :value="item.value" /> -->
            </MOSTY.Select>
          </el-form-item>
          <el-form-item label="专业领域:" prop="professionalField" style="width: calc(48% - 20px);">
            <el-select v-model="formData.professionalField" style="width: 337px;" placeholder="请选择专业领域" multiple
              collapse-tags>
              <el-option v-for="item in props.dic.D_BZ_AQRYSCLY" :key="item.value" :label="item.label"
                :value="item.value" />
            </el-select>
          </el-form-item>

          <el-form-item label="备注:" prop="bz">
            <el-input v-model="formData.bz" type="textarea" :rows="2" placeholder="请输入备注" clearable
              style="width: 600px">
            </el-input>
          </el-form-item>

          <el-form-item class="file-item" label="发文资料" prop="informationFile">
            <MOSTY.Upload width="100%" height="270px" :widthNumber="340" :limit="2" :nopicer="true" :isImg="false"
              :ShowfileList="true" v-model="formData.informationFile" :showinput="false"
              :gsgfList="['pdf', 'ofd', 'doc', 'docx', 'png', 'wps']" @filehandleChange="changeFile">
            </MOSTY.Upload>
          </el-form-item>

          <el-form-item class="file-item" label="其他资料" prop="otherFile">
            <MOSTY.Upload :width="'100%'" height="270px" :widthNumber="340" :limit="2" :nopicer="true" :isImg="false"
              :ShowfileList="true" v-model="formData.otherFile" :showinput="false"
              :gsgfList="['pdf', 'ofd', 'doc', 'docx', 'png', 'wps']" @filehandleChange="changeFile">
            </MOSTY.Upload>
          </el-form-item>
        </el-form>

        <!-- 选择部门 -->
        <!-- <Choosebm :showDdld="showDept" :deptId="deptId" @closezzjg="closezzjg" @listdata="getDeptVal"
				:zzlx="zzlx" /> -->
        <!-- <ChooseDept :data="deptArr" :showDdld="showDept" searchType="03" @closezzjg="closezzjg" :Isstrictly='true'
          @listdata="getDeptVal" :zzlx="zzlx" /> -->
        <ChooseUser v-model="chooseUserVisible" :data="memberList" :deptId="deptId" :leaderid="leaderid"
          @choosedUsers="getSonValue"></ChooseUser>
      </div>
      <template #footer>
        <span class="dialog-footer">

          <el-button @click="savefrom(formRef)" :loading="addLoading">
            <el-icon>
              <DocumentChecked />
            </el-icon>
            <span>保存</span>
          </el-button>
          <el-button @click="close">
            <el-icon>
              <DocumentDelete />
            </el-icon>
            <span>关闭</span>
          </el-button>
        </span>
      </template>

    </el-dialog>
  </div>
</template>

<script setup>
import { ref, defineProps, defineEmits, defineExpose, onMounted, getCurrentInstance, reactive } from "vue";
import ChooseUser from "@/components/MyComponents/ChooseUser/Leader.vue";
import Choosebm from "@/components/MyComponents/ChooseDept/index.vue";
import ChooseDept from "@/components/MyComponents/ChooseDept/Departnobj.vue";
import * as MOSTY from "@/components/MyComponents/index";
import * as rule from "@/utils/rules.js"
import { getApi, postApi, deleteApi } from "@/api/tobAcco_api.js";
import { ElMessage } from "element-plus"
const props = defineProps({
  dic: {
    type: Object,
    default: {
      D_BZ_CJLX: [],
      D_BZ_AQRYSCLY: [],
    }
  }
});
const { proxy } = getCurrentInstance();
const emits = defineEmits(['ok', 'close'])
/**  */
/** 表单组件 */
const formRef = ref();
const dialogVisible = ref(true);
// /** 选择人员弹框 */
const chooseUserVisible = ref(false)
const zzlx = ref(null);
// /** 选中的部门 */
// const deptArr = ref([])
/** 选中的人员 */
const memberList = ref([])
/** 展示选择部门 */
const showDept = ref(false);
// /** 展示上传组件（为了回显，所以需要这样设置为true） */
// const isShowUpdate = ref(true);
/** 是否是【编辑】 */
const isEdit = ref(false);
/** 是否加载中。。。 */
const addLoading = ref(false);
/** 1 */
const leaderid = ref();
/** 表单数据 */
const formData = ref({
  // id: '', //	id
  userName: '', //	聘用人员
  userId: '', //	聘用人员id

  levelType: '', //	层级类型 || D_BZ_CJLX
  workExperience: '', //	工作经验 (年)

  // orgName: '', //	聘用单位
  // orgId: '', //	聘用单位id
  professionalField: '', //	专业领域 (安全人员新增  -擅长领域) ||D_BZ_AQRYSCLY
  informationFile: [],	//发文资料
  // deputyActivityFile: [],	//年度履职报告
  // examineResultFile: [],	//年度考核结果
  bz: "",// 备注
  otherFile: [],	// 其他资料
})
const rules = reactive({
  userName: [{ required: true, message: "请填写人员", trigger: "change" }],
  levelType: [{ required: true, message: "请选择层级类型", trigger: "change" }],
  ...rule.numberzzsRule({ validator: true, require: false, num: 99 }, 'workExperience')
  // professionalField: [{ required: true, message: "请选择专业领域", trigger: "change" }],
  // informationFile: [{ required: true, message: "请选择发文资料", trigger: "change" }],
})
const deptId = ref()
// 生效时间只能选当天及之前的
const disabledDate = (time) => {
  return time.getTime() > Date.now();
};
const closezzjg = (val) => {
  showDept.value = false;
};
const close = () => {
  if(!formRef.value) return
  proxy.$modal.confirm('离开会丢失页面中修改的内容，确认离开吗？')
    .then(() => {
      emits("close")
    })
    .catch(() => {
      // catch error
    })

}
/** 部门确认 */
const getDeptVal = (value) => {
  formData.value.orgName = value.map(item => item.orgName).toString()

  formData.value.orgId = value.map(item => item.id).toString()
}
function ChooesDdld(val) {
  //   zzlx.value = val;
  deptArr.value = typeof formData.value.deptid === 'string' ? formData.value.deptid.split(',') : []
  // val·
  showDept.value = true;

}
// 新的文件上传返回
const changeFile = (data) => {
  // fjtableData.value = data;

};
/** 选择人确认 */
const getSonValue = (val) => {

  formData.value.userName = val[0].userName
  formData.value.userId = val[0].id
}
// 保存
const savefrom = async (ruleFormRef) => {
  addLoading.value = true
  if (!ruleFormRef) return;
  await ruleFormRef.validate((valid) => {
    if (valid) {
      let params = { ...formData.value }

      params.informationFile = formData.value.informationFile ? formData.value.informationFile.toString() : ''
      params.professionalField = formData.value.professionalField ? formData.value.professionalField.toString() : ''
      // params.examineResultFile = formData.value.examineResultFile ? formData.value.examineResultFile.toString() : ''
      params.otherFile = formData.value.otherFile ? formData.value.otherFile.toString() : ''
      if (params.id) {
        postApi(params, "/mosty-jcgl/talentPool/editTalentPool")
          .then((res) => {
            ElMessage.success("修改成功");
            emits('ok', 'edit')
          }).finally(() => {
            addLoading.value = false
          })
      } else {
        postApi(params, "/mosty-jcgl/talentPool/saveTalentPool")
          .then((res) => {
            ElMessage.success("新增成功")
            emits('ok', 'add')
          }).finally(() => {
            addLoading.value = false
          })


      }
    } else {
      ElMessage.error("请输入必填项!");
      addLoading.value = false
    }
  });
};
/** 字符串转数组 */
const str2Arr = (val) => { return val && typeof val === 'string' ? val.split(',') : undefined }
//查询部门详细资料
function setFormData(obj) {
  // getApi({ id }, '/mosty-jcgl/assessEmployStaff/selectOne').then((res) => {
  //   if (!res) return
  //   formData.value = res

  // })
  formData.value = { ...obj }
  formData.value.professionalField = str2Arr(obj.professionalField)
  // formData.value.otherFile = str2Arr(obj.otherFile)
}
const init = (obj) => {
  // 编辑
  if (obj && obj.id) {
    isEdit.value = true
    setFormData(obj)
  } else {
    // isShowUpdate.value = true
    formData.value.levelType = obj.levelType;
  }
}
defineExpose({ init });
</script>

<style lang="scss" scoped>
.form-container {
  .file-item {
    width: calc(98% - 30px);
  }
}
</style>
