<template>
  <!-- 评聘安全工程师 -->
  <div>
    <el-dialog v-model="dialogVisible" :title="formData && formData.id ? personTitleData[0] : personTitleData[1]"
      :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="orgName" style="width: 100%;display: flex;">
            <el-input v-model="formData.orgName" type="textarea" clearable readonly autosize
              style="width: 520px;margin-right: 10px;" placeholder="聘用单位">
            </el-input>
            <el-button @click.stop.prevent="ChooesDdld">选择</el-button>
          </el-form-item>
          <el-form-item :label="personTimeData[0]" prop="startDate" style="width: calc(48% - 20px);">
            <el-date-picker v-model="formData.startDate" type="date" value-format="YYYY-MM-DD"
              :placeholder="personTimeData[0]" />
          </el-form-item>
          <el-form-item :label="personTimeData[1]" prop="endDate" style="width: calc(48% - 20px);">
            <el-date-picker v-model="formData.endDate" type="date" value-format="YYYY-MM-DD"
              :placeholder="personTimeData[1]" />
          </el-form-item>
          <el-form-item label="备注:" prop="logoname">
            <el-input v-model="formData.bz" type="textarea" placeholder="请输入备注" clearable
              style="width: 600px"></el-input>
          </el-form-item>
          <el-form-item class="file-item" :label="personTimeData[2]" prop="assessEmployFile">
            <MOSTY.Upload width="100%" height="270px" :widthNumber="340" :limit="2" :nopicer="true" :isImg="false"
              :ShowfileList="true" v-model="formData.assessEmployFile" :showinput="false"
              :gsgfList="['pdf', 'ofd', 'doc', 'docx', 'wps']" @filehandleChange="changeFile">
            </MOSTY.Upload>
          </el-form-item>
          <el-form-item class="file-item" label="年度履职报告" prop="deputyActivityFile">
            <MOSTY.Upload :width="'100%'" height="270px" :widthNumber="340" :limit="2" :nopicer="true" :isImg="false"
              :ShowfileList="true" v-model="formData.deputyActivityFile" :showinput="false"
              :gsgfList="['pdf', 'ofd', 'doc', 'docx', 'wps']" @filehandleChange="changeFile">
            </MOSTY.Upload>
          </el-form-item>
          <el-form-item class="file-item" label="年度考核结果" prop="examineResultFile">
            <MOSTY.Upload :width="'100%'" height="270px" :widthNumber="340" :limit="2" :nopicer="true" :isImg="false"
              :ShowfileList="true" v-model="formData.examineResultFile" :showinput="false"
              :gsgfList="['pdf', 'ofd', 'doc', 'docx', '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', 'wps']" @filehandleChange="changeFile">
            </MOSTY.Upload>
          </el-form-item>
        </el-form>

        <!-- 选择部门 -->
        <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 ChooseDept from "@/components/MyComponents/ChooseDept/Departnobj.vue";
import * as MOSTY from "@/components/MyComponents/index";
import { getApi, postApi, deleteApi } from "@/api/tobAcco_api.js";
import { ElMessage } from "element-plus"
// const props = defineProps({});
const { proxy } = getCurrentInstance();
const emits = defineEmits(['ok', 'close'])
const personTitleData = ref(['修改评聘安全人员', '新增评聘安全人员'])
const personTimeData = ref(['评聘开始时间:', '评聘结束时间:', '评聘文件'])
/**  */
/** 表单组件 */
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

  startDate: '', //	评聘开始时间
  endDate: '', //	评聘结束时间时间

  orgName: '', //	聘用单位
  orgId: '', //	聘用单位id
  /**评聘文件 */
  assessEmployFile: [],	//评聘文件
  deputyActivityFile: [],	//年度履职报告
  examineResultFile: [],	//年度考核结果
  otherFile: [],	// 其他资料
  bz: "",// 备注
})
const rules = reactive({
  userName: [{ required: true, message: "请填写人员", trigger: "change" }],
  orgName: [{ required: true, message: "请选择单位", trigger: "change" }],
  assessEmployFile: [{ required: true, message: "请选择评聘文件", trigger: "change" }],
  // userName: [{required:true,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 = formData.value.orgId ? formData.value.orgId.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.assessEmployFile = formData.value.assessEmployFile ? formData.value.assessEmployFile.toString() : ''
      params.deputyActivityFile = formData.value.deputyActivityFile ? formData.value.deputyActivityFile.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/assessEmployStaff/editAssessEmployStaff")
          .then((res) => {
            ElMessage.success("修改成功");
            emits('ok', 'edit')
          }).finally(() => {
            addLoading.value = false
          })
      } else {
        postApi(params, "/mosty-jcgl/assessEmployStaff/saveAssessEmployStaff")
          .then((res) => {
            ElMessage.success("新增成功")
            emits('ok', 'add')
          }).finally(() => {
            addLoading.value = false
          })
      }
    } else {
      ElMessage.error("请输入必填项!");
      addLoading.value = false
    }
  });
};
/** 字符串转数组 */
const str2Arr = (val) => typeof val === 'string' ? val.split(',') : [];
//查询部门详细资料
function setFormData(id, mtcsoltype) {
  getApi({ id }, '/mosty-jcgl/assessEmployStaff/selectOne').then((res) => {
    if (!res) return
    formData.value = res
    // formData.value.assessEmployFile = str2Arr(formData.value.assessEmployFile);
    // formData.value.deputyActivityFile = str2Arr(formData.value.deputyActivityFile);
    // formData.value.examineResultFile = str2Arr(formData.value.examineResultFile);
    // formData.value.otherFile = str2Arr(formData.value.otherFile);
  })
}
const init = (obj) => {
  // 编辑
  if (obj && obj.id) {
    isEdit.value = true
    setFormData(obj.id)
  } else {
    // isShowUpdate.value = true
  }
}
defineExpose({ init });
</script>

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