<template>
  <div class="bigBoxs">
    <MOSTY.FromPage :title="props.formData.title" @closeDialog="handleClose">
      <template #content>
        <MOSTY.Assort :title="'基础信息'" />
        <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" :="true" label-width="135px" :inline="true"
          :disabled="!props.formData.savebtn">
          <el-form-item label="人员姓名：" prop="peoplename">
            <el-input v-model="ruleForm.peoplename" readonly clearable style="width: 337px;">
              <template #append>
                <el-button class='cursor' @click="ChooesDdld('01')">选择</el-button>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item label="身份证：" prop="idcard">
            <MOSTY.IdentityCard width="337px" v-model="ruleForm.idcard" clearable placeholder="请输入身份证号"
              @onInput="identityCardChange1">
            </MOSTY.IdentityCard>
          </el-form-item>
          <el-form-item label="联系方式：" prop="contact">
            <MOSTY.Phone width="337px" show-word-limit v-model="ruleForm.contact" maxlength="11" clearable
              @onInput="phoneChange">
            </MOSTY.Phone>
          </el-form-item>
          <el-form-item label="出生日期：" prop="birthdate">
            <el-date-picker v-model="ruleForm.birthdate" disabled type="data" format="YYYY-MM-DD"
              value-format="YYYY-MM-DD" placeholder="请选择出生日期" :disabled-date="disablednowDate1" style="width: 337px">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="性别：" prop="sex">
            <el-select v-model="ruleForm.sex" style="width: 337px" clearable>
              <el-option v-for="item in D_BZ_XB" :key="item" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="学历：" prop="culture">
            <MOSTY.DictRidioAndSelect :dictData="D_BZ_AQRYWHCD" v-model="ruleForm.culture" selectType="select"
              placeholder="请选择学历" style="width: 337px" />
          </el-form-item>
          <el-form-item v-if="ruleForm.xgfname" label="相关方：">
            <el-input v-model="ruleForm.xgfname" clearable style="width: 337px" disabled />
          </el-form-item>
          <el-form-item v-else label="部门：">
            <el-input v-model="ruleForm.deptname" clearable style="width: 337px" disabled />
          </el-form-item>
          <el-form-item label="岗位：" prop="post">
            <el-input v-model="ruleForm.post" clearable style="width: 337px" />
          </el-form-item>
          <el-form-item label="健康证号：" prop="jkzh">
            <el-input v-model="ruleForm.jkzh" clearable style="width: 337px" />
          </el-form-item>
          <el-form-item label="健康证发证机关：" prop="healthcertificate">
            <el-input v-model="ruleForm.healthcertificate" clearable style="width: 337px" />
          </el-form-item>
          <el-form-item label="发证日期：" prop="issuingtime">
            <el-date-picker style="width: 337px" v-model="ruleForm.issuingtime" type="date" value-format="YYYY-MM-DD"
              placeholder="请选择发证日期" :disabled-date="disablednowDate1" @change="ruleForm.effectivetime = ''" />
          </el-form-item>
          <el-form-item label="有效期：" prop="effectivetime">
            <el-date-picker style="width: 337px" v-model="ruleForm.effectivetime" type="date" value-format="YYYY-MM-DD"
              placeholder="请选择有效期" :disabled-date="disablednowDate" />
          </el-form-item>
          <el-form-item label="工作地点：" prop="workplace">
            <el-input v-model="ruleForm.workplace" clearable style="width: 337px;" />
          </el-form-item>
          <el-form-item label="备注：" style="width:100%;">
            <el-input type="textarea" v-model="ruleForm.bz" clearable style="width:100%;" />
          </el-form-item>
          <!-- <el-row style="width: 100%;">

          </el-row> -->

          <el-form-item label="证书上传：" prop="file" style="width: 100%;">
            <MOSTY.Upload v-model="ruleForm.file" :limit="5" :delrow="delrow" :ShowfileList="true"
            :gsgfList="['pdf', 'ofd', 'doc', 'docx', 'xls', 'xlsx','wps']"  @filehandleChange="changeFile" :isImg="true" :disabled='props.formData.seeimg' />
          </el-form-item>
        </el-form>
        <!-- 选择人员 -->
        <MOSTY.xgfandzzjgry v-model="chooseUserVisible" :deptId="deptId" :Single="singleShow" :stlyrylx='stlyrylx'
          :relatedid="null" @choosedUsers="getSonValue" :xgflx="'04,10'" @changerylx='changerylx' />
        <div v-if='props.formData.id'>
          <MOSTY.Assort :title="'健康证修改记录表'" />
          <section style='height: 40vh;'>
            <MOSTY.Table :table-columns="tableColumn" :tableData="tableData2" :tableloading="tableloading2"
              :isSelect="false" :isSort="false" @SortChange="SortChange" style="width: 100%;">
              <template #sex="{ row }">
                <dict-tag v-if="row.sex" :options="D_BZ_XB" :value="row.sex" :tag="false" />
                <span v-else>无</span>
              </template>
              <template #sfgq="{ row }">
                <dict-tag v-if="row.sfgq" :options="D_BZ_SF" :value="row.sfgq" :tag="false" />
                <span v-else>无</span>
              </template>
              <!-- 操作 -->
              <template #actions="{ row }">
                <span class="operesee" @click="handletabSee(row)" size="small"><el-icon>
                    <View />
                  </el-icon>详情</span>
              </template>
            </MOSTY.Table>
          </section>
          <div class="fenye">
            <Pages :pageConfiger="pageConfiger" @changeSize="handleSizeChange" @changeNo="handleCurrentChange"></Pages>
          </div>
        </div>
      </template>
      <template #footer>

        <el-button type="primary" v-if="props.formData.savebtn" :loading="loading" @click="handleSave(ruleFormRef)">
          <span><el-icon>
              <DocumentChecked />
            </el-icon>保存</span>
        </el-button>
        <el-button @click="handleClose" type="primary">
          <span><el-icon>
              <DocumentDelete />
            </el-icon>关闭</span>
        </el-button>
      </template>
      <template #dwbox>
        <!-- 详情 -->
        <el-dialog v-model="dialogVisible" :show-close="false" :title="'健康证记录详情'" :close-on-click-modal="false"
          width="1300px">
          <div class='diafrom'>
            <el-form class="mosty-from-wrap" ref="ruleFormRef" label-width="150px" :disabled="true" :model="fromObj"
              :inline="true" :rules="rules">
              <el-form-item label="人员姓名：" prop="peoplename">
                <el-input v-model="fromObj.peoplename" clearable style="width: 337px" />
              </el-form-item>
              <el-form-item label="身份证：" prop="idcard">
                <MOSTY.IdentityCard width="337px" v-model="fromObj.idcard" clearable placeholder="请输入身份证号"
                  @onInput="identityCardChange1">
                </MOSTY.IdentityCard>
              </el-form-item>
              <el-form-item label="联系方式：" prop="contact">
                <MOSTY.Phone width="337px" show-word-limit v-model="fromObj.contact" maxlength="11" clearable
                  @onInput="phoneChange">
                </MOSTY.Phone>
              </el-form-item>
              <el-form-item label="出生日期：" prop="birthdate">
                <el-date-picker v-model="fromObj.birthdate" type="data" format="YYYY-MM-DD" value-format="YYYY-MM-DD"
                  placeholder="请选择出生日期" :disabled-date="disablednowDate1" style="width: 337px">
                </el-date-picker>
              </el-form-item>
              <el-form-item label="性别：" prop="sex">
                <el-select v-model="fromObj.sex" style="width: 337px" clearable>
                  <el-option v-for="item in D_BZ_XB" :key="item" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
              <el-form-item label="学历：" prop="culture">
                <MOSTY.DictRidioAndSelect :dictData="D_BZ_AQRYWHCD" v-model="fromObj.culture" selectType="select"
                  placeholder="请选择学历" style="width: 337px" />
              </el-form-item>
              <el-form-item label="岗位：" prop="post">
                <el-input v-model="fromObj.post" clearable style="width: 337px" />
              </el-form-item>
              <el-form-item v-if="ruleForm.xgfname" label="相关方：">
                <el-input v-model="ruleForm.xgfname" clearable style="width: 337px" disabled />
              </el-form-item>
              <el-form-item v-else label="部门：">
                <el-input v-model="ruleForm.deptname" clearable style="width: 337px" disabled />
              </el-form-item>
              <el-form-item label="健康证号：" prop="jkzh">
                <el-input v-model="fromObj.jkzh" clearable style="width: 337px" />
              </el-form-item>
              <el-form-item label="健康证发证机关：" prop="healthcertificate">
                <el-input v-model="fromObj.healthcertificate" clearable style="width: 337px" />
              </el-form-item>
              <el-form-item label="发证日期：" prop="issuingtime">
                <el-date-picker style="width: 337px" v-model="fromObj.issuingtime" type="date" value-format="YYYY-MM-DD"
                  placeholder="请选择发证日期" @change="fromObj.effectivetime = ''" />
              </el-form-item>
              <el-form-item label="有效期：" prop="effectivetime">
                <el-date-picker style="width: 337px" v-model="fromObj.effectivetime" type="date"
                  value-format="YYYY-MM-DD" placeholder="请选择有效期" :disabled-date="disabledayxq" />
              </el-form-item>
              <el-form-item label="工作地点：" prop="workplace">
                <el-input v-model="fromObj.workplace" clearable style="width: 1055px" />
              </el-form-item>
              <el-form-item label="备注：">
                <el-input type="textarea" v-model="fromObj.bz" clearable style="width: 1055px" />
              </el-form-item>
              <el-form-item label="证书上传：" prop="file">
                <MOSTY.Upload v-model="fromObj.file" :limit="5" :delrow="delrow" :ShowfileList="true"
                :gsgfList="['pdf', 'ofd', 'doc', 'docx', 'xls', 'xlsx','wps']"  @filehandleChange="changeFile" :isImg="true" :disabled='true' />
              </el-form-item>
            </el-form>
          </div>
          <template #footer>
            <span class="dialog-footer">
              <el-button @click="cancle()"><el-icon>
                  <DocumentDelete />
                </el-icon>关闭</el-button>
            </span>
          </template>
        </el-dialog>
      </template>
    </MOSTY.FromPage>
  </div>
</template>

<script setup>
// 引入
import { ref, onMounted, defineProps, defineEmits, reactive, getCurrentInstance } from "vue";
import { getApi, postApi } from "@/api/tobAcco_api.js";
import { disablednowDate1 } from "@/utils/tools.js";
import { ElMessage } from "element-plus";
import * as MOSTY from "@/components/MyComponents/index";
import * as rule from "@/utils/rules.js";
import { IdCard } from "@/utils/dict.js";
const { proxy } = getCurrentInstance();
const { D_BZ_XB, D_BZ_SF, D_BZ_AQRYWHCD } = proxy.$dict("D_BZ_XB", 'D_BZ_SF', "D_BZ_AQRYWHCD");
const loading = ref(false); //新增保存按钮截流
const tableloading2 = ref(false);
const xgflist = ref([])
const tableData2 = ref([])
const ruleFormRef = ref(null)
const dialogVisible = ref(false);
const listQuery = ref({
  pageCurrent: 1,
  pageSize: 10
});
//表单数据
const rules = reactive({
  peoplename: [
    { required: true, message: "人员姓名不能为空", trigger: "blur" }
  ],
  ...rule.phoneRule({ require: true, validator: true }, 'contact'),
  ...rule.identityCardRule({ require: true, validator: true }, "idcard"),
  birthdate: [{ trigger: "blur", required: true, message: "出生日期不能为空" }],
  sex: [{ trigger: "blur", required: true, message: "请选择性别" }],
  culture: [{ trigger: "blur", required: true, message: "学历不能为空" }],
  post: [{ trigger: "blur", required: true, message: "岗位不能为空" }],
  jkzh: [{ trigger: "blur", required: true, message: "健康证号不能为空" }],
  healthcertificate: [{ trigger: "blur", required: true, message: "健康证发证机关不能为空" }],
  issuingtime: [{ trigger: "blur", required: true, message: "发证日期不能为空" }],
  effectivetime: [{ trigger: "blur", required: true, message: "有效期不能为空" }],
  workplace: [{ trigger: "blur", required: true, message: "工作地点不能为空" }],
  file: [{ trigger: "blur", required: true, message: "证书不能为空" }]
});
const fromObj = ref({})
const ruleForm = ref({})
const emits = defineEmits(["changeAddVi", "changeclose"]);
const props = defineProps({
  formData: {
    type: Object,
    required: {}
  },
  canteenInfoId: String
});
const tableColumn = ref([
  {
    title: "人员姓名",
    prop: "peoplename",
  },
  {
    title: "身份证号",
    prop: "idcard"
  },
  {
    title: "性别",
    prop: "sex",
    slot: true,
  },
  {
    title: "出生日期",
    prop: "birthdate"
  },
  {
    title: "健康证号",
    prop: "jkzh",
  },
  {
    title: "发证日期",
    prop: "issuingtime"
  },
  {
    title: "有效期",
    prop: "effectivetime"
  },
  {
    title: "是否到期",
    prop: "sfgq",
    slot: true,
  },
  {
    title: "工作地点",
    prop: "workplace"
  },
  {
    title: "操作",
    prop: "actions",
    slot: true
  }
])
const pageConfiger = reactive({
  pageSize: 10,
  pageCurrent: 1,
  total: 0
})
// 初始化
onMounted(() => {
  getxgflist()
  if (props.formData.id) {
    listQuery.value.zbid = props.formData.id
    getmain(props.formData.id);
    getjlData()
  }
});
function getxgflist() {
  getApi({ type: '2' }, '/mosty-jcgl/relatedpartyinfo/getListByOrgcode').then(res => {
    if (res.length > 0) {
      xgflist.value = res.map(item => {
        return { label: item.relatedname, value: item.id }
      })
    }

  })
}
function identityCardChange1(val) {
  if (val.length == 18) {
    ruleForm.value.birthdate = IdCard(ruleForm.value.idcard, 1)
    ruleForm.value.sex = getSex(ruleForm.value.idcard);
  }

}
//有效期
function disablednowDate(time) {
  return time.getTime() + 24 * 60 * 60 * 1000 < new Date(ruleForm.value.issuingtime).getTime()
}
function disabledayxq(time) {
  return time.getTime() + 24 * 60 * 60 * 1000 < new Date(fromObj.value.issuingtime).getTime()
}

//详情
const getmain = (id) => {
  if (id) {
    getApi({ id }, "/mosty-jcgl/peopleParameter/queryPeopleParameterById").then(
      (res) => {
        if (res) {
          ruleForm.value = res;

        }
      }
    );
  }
};

//获取记录表
function getjlData() {
  postApi(listQuery.value, `/mosty-jcgl/peopleParameter/queryJlb`).then(
    (res) => {
      if (res.records) {
        tableloading2.value = false;
        tableData2.value = res.records;
        tableData2.value.forEach(item => {
          if (new Date(item.effectivetime).getTime() < Date.now()) {
            item.sfgq = '1'
          } else {
            item.sfgq = '2'
          }
        })
        pageConfiger.total = res.total;
      } else {
        tableData2.value = [];
        tableloading2.value = false;
      }
    }
  );
}
//记录表详情
function handletabSee(val) {
  getApi({ id: val.id }, '/mosty-jcgl/peopleParameter/queryJlbById').then(res => {
    fromObj.value = res
    dialogVisible.value = true
  })

}
const deptId = ref('');
const stlyrylx = ref('01')
const zzlx = ref();
const leaderid = ref("");
const singleShow = ref(true); //单选多选
const chooseUserVisible = ref(false); //选择人员弹窗
// 人员姓名选择
const ChooesDdld = (val) => {
  zzlx.value = val;
  //选择检查成员
  if (val == "01") {
    leaderid.value = "";
    singleShow.value = true;
    chooseUserVisible.value = true;
  }
}
//获取人员类型
function changerylx(val) {
  stlyrylx.value = val
}
const getSonValue = (value) => {
  if (zzlx.value == "01") {
    ruleForm.value.xgfname = value[0].relatedname || ''
    ruleForm.value.xgfid = value[0].relatedid || ''
    if (ruleForm.value.xgfid && value[0].idcard) {
      ruleForm.value.peoplename = value[0].userName;
      ruleForm.value.idcard = value[0].idcard;
      ruleForm.value.contact = value[0].mobile;
      ruleForm.value.birthdate = getBirth(value[0].idcard);
      ruleForm.value.idcard = value[0].idcard;
      ruleForm.value.sex = value[0].sex ? value[0].sex : getSex(value[0].idcard);
    } else {
      ruleForm.value.peoplename = value[0].userName;
      ruleForm.value.idcard = value[0].idEntityCard;
      ruleForm.value.contact = value[0].mobile;
      ruleForm.value.birthdate = getBirth(value[0].idEntityCard);
      ruleForm.value.sex = value[0].sex ? value[0].sex : getSex(value[0].idEntityCard);
      ruleForm.value.deptname = value[0].deptName;
      ruleForm.value.deptId = value[0].deptId;
    }
  }
};
const getSex = (sfz) => {
  if (sfz.length !== 18) return ''
  const genderCode = parseInt(sfz.charAt(16), 10);
  // return genderCode % 2 === 1 ? '男' : '女';
  return genderCode % 2 === 1 ? '1' : '2';
}
const getBirth = (sfz) => {
  if (sfz?.length !== 18) return ''
  const birthYear = sfz.substring(6, 10);
  const birthMonth = sfz.substring(10, 12);
  const birthDay = sfz.substring(12, 14);
  return `${birthYear}-${birthMonth}-${birthDay}`;
}
//关闭记录详情
function cancle() {
  dialogVisible.value = false
}

//清空数据
function reset() {
  ruleForm.value = {};
}

//保存
const handleSave = async (ruleFormRef) => {
  if (!ruleFormRef) return;
  await ruleFormRef.validate((valid) => {
    if (valid) {
      loading.value = true
      ruleForm.value.file = ruleForm.value.file
        ? ruleForm.value.file.toString()
        : "";
      // 餐厅id
      ruleForm.value.canteenInfoId = props.canteenInfoId;
      if (ruleForm.value) {
        if (ruleForm.value.id) {
          postApi(
            ruleForm.value,
            "/mosty-jcgl/peopleParameter/updatePeopleParameterOne"
          )
            .then((res) => {
              ElMessage.success("修改成功");

              reset();
              emits("changeAddVi", false);
            }).finally(() => {
              loading.value = false
            })
        } else {
          postApi(
            ruleForm.value,
            "/mosty-jcgl/peopleParameter/addPeopleParameterOne"
          )
            .then((res) => {
              ElMessage.success("新增成功");

              reset();
              emits("changeAddVi", false);
            }).finally(() => {
              loading.value = false
            })
        }

      }
    } else {
      ElMessage.error("请输入必填项");
    }
  });
};
// 关闭
const handleClose = () => {
  if (props.formData.savebtn) {
    proxy.$modal.confirm('离开会丢失页面中修改的内容，确认离开吗？')
      .then(() => {
        // 关闭上一次的表单校验
        ruleFormRef.value.clearValidate();
        reset();
        emits("changeAddVi", false);
      })
      .catch(() => {
        // catch error
      })
  } else {
    // 关闭上一次的表单校验
    ruleFormRef.value.clearValidate();
    reset();
    emits("changeAddVi", false);
  }

};

//页码发生变化
const handleCurrentChange = (val) => {
  listQuery.value.pageCurrent = val;
  pageConfiger.pageCurrent = val;
  getPxjhlist();
};
//查询条数发生变化
const handleSizeChange = (val) => {
  listQuery.value.pageSize = val;
  pageConfiger.pageSize = val;
  getPxjhlist();
};
</script>

<style lang="scss" scoped>
.diafrom {
  width: 1238px;

  .el-form {
    width: 100%;
  }
}

.sele-title {
  display: flex;
  justify-content: space-between;
  font-size: 16px;
  padding: 10px 20px;
}

.sele-titles {
  display: flex;
  justify-content: space-between;
  font-size: 16px;
  padding: 10px 20px 0px 50px;

}

.beiz {
  width: 100%;
  padding: 10px;
  background: #0b6047;
}

.addbtn {
  margin: 10px;
  display: flex;
  justify-content: end;
}

::v-deep .el-form-item__content {
  flex-wrap: nowrap !important;
}

.el-form {
  margin: 20px 30px;
  flex-wrap: wrap;
  justify-content: space-between;

}

.el-form-item {
  text-align: center;
}


::v-deep .el-dialog__body {
  overflow: auto !important;
  max-height: 70vh !important;
}
</style>