<template>
  <div class="bigBox">
    <MOSTY.FromPage :title="pageTitle" @closeDialog="black">
      <template #content>
        <MOSTY.Assort :title="'基本信息'" />
        <div class="fromBox">
          <el-form class="mosty-from-wrap" ref="ruleFormRef" label-width="148px" :model="formData" :inline="true"
            :rules="rules" :disabled="!saveBtn">
            <el-form-item label="姓名:" prop="fullname">
              <el-input v-model="formData.fullname" readonly clearable style="width: 335px">
                <template #append>
                  <el-button class='cursor' @click="ChooesDdld('01')">选择</el-button></template>
              </el-input>
            </el-form-item>
            <el-form-item label="人员类别：" prop="peopletype">
              <el-select v-model="formData.peopletype" placeholder="请选择人员类别" style="width: 335px">
                <el-option v-for="item in D_BZ_RYLB_NEW" :key="item.value" :label="item.label"
                  :value="item.value"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="性别：" prop="gender">
              <el-select v-model="formData.gender" placeholder="请选择性别" style="width: 335px">
                <el-option v-for="item in props.obj.zdlist.D_BZ_XB" :key="item.value" :label="item.label"
                  :value="item.value"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="年龄：" prop="age">
              <el-input controls-position="right" v-model.number="formData.age" type="number" placeholder="请输入年龄"
                style="width: 335px"></el-input>
            </el-form-item>
            <el-form-item label="场所名称:" prop="sitename">
              <el-select v-model="formData.sitename" filterable @change="cahngecsmc" clearable placeholder="请选择场所名称："
                style="width: 335px">
                <el-option v-for="item in csmclist" :key="item" :label="item.sitename" :value="item.id" />
              </el-select>
            </el-form-item>
            <el-form-item label="危害因素：" prop="hazardousfactors">
              <el-select v-model="formData.hazardousfactors" placeholder="请选择危害因素" multiple style="width: 335px">
                <el-option v-for="item in props.obj.zdlist.D_TB_ZYJK_WHYS" :key="item.value" :label="item.label"
                  :value="item.value"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="体检周期：" prop="examinationcycle">
              <el-select v-model="formData.examinationcycle" placeholder="请选择体检周期" style="width: 335px">
                <el-option v-for="item in props.obj.zdlist.D_TB_JCZQ" :key="item.value" :label="item.label"
                  :value="item.value"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="岗位：">
              <el-input v-model="formData.post" placeholder="请输入岗位" style="width: 335px"></el-input>
            </el-form-item>
            <el-form-item label="档案编号：">
              <el-input v-model="formData.filenumber" placeholder="请输入岗位" type="Number" style="width: 335px"></el-input>
            </el-form-item>
            <el-form-item label="年份：" prop="yealy">
              <el-date-picker v-model="formData.yealy" type="year" format="YYYY" value-format="YYYY" placeholder="请选择年份"
                style="width: 335px" />
            </el-form-item>
            <el-form-item label="特殊作业类型：" prop="specialHomeworkCategories">
              <el-select v-model="formData.specialHomeworkCategories" placeholder="请选择特殊作业类型" style="width: 335px">
                <el-option v-for="item in D_BZ_TSZYLX" :key="item.value" :label="item.label"
                  :value="item.value"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="接触危害因素：" prop="exposureHazardousFactors">
              <el-select v-model="formData.exposureHazardousFactors" placeholder="请选择接触危害因素" style="width: 335px">
                <el-option v-for="item in D_BZ_JCZYWHYS" :key="item.value" :label="item.label"
                  :value="item.value"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="健康体检类型：" prop="healthExaminationType">
              <el-select v-model="formData.healthExaminationType" placeholder="请选择健康体检类型" style="width: 335px">
                <el-option v-for="item in D_BZ_ZYJKTJLB" :key="item.value" :label="item.label"
                  :value="item.value"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="是否有职业病：" prop="ill">
              <el-select v-model="formData.ill" placeholder="请选择是否有职业病" style="width: 335px">
                <el-option v-for="item in D_BZ_SF" :key="item.value" :label="item.label"
                  :value="item.value"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="备注：" style='width:100%;'>
              <el-input v-model="formData.bz" type="textarea" autosize show-word-limit maxlength="200"
                style="width: 100%" />
            </el-form-item>
            <el-form-item label="患病体检报告：" prop="illFile" style='width:100%;'>
              <MOSTY.Upload :isAutoWidth="true" :limit="5" :nopicer="true" :isImg="false" :ShowfileList="true"
                :gsgfList="['pdf', 'ofd', 'doc', 'docx', 'xls', 'xlsx', 'wps']" v-model="formData.illFile"
                :showinput="true" :delrow="delrow"></MOSTY.Upload>
            </el-form-item>
            <el-form-item label="健康体检报告附件：" prop="file" style='width:100%;'>
              <MOSTY.Upload :isAutoWidth="true" :limit="5" :nopicer="true" :isImg="false" :ShowfileList="true"
                :gsgfList="['pdf', 'ofd', 'doc', 'docx', 'xls', 'xlsx', 'wps']" v-model="formData.file"
                :showinput="true" :delrow="delrow"></MOSTY.Upload>
            </el-form-item>
          </el-form>

        </div>
        <div v-if="props.obj.rowid">
          <MOSTY.Assort :title="'体检记录表'" />
          <el-table ref="multipleTableRef" stripe :data="tjjlList" style="width: 100%"
            @selection-change="handleSelectionChange" border>
            <el-table-column label="年份" prop="yealy">
            </el-table-column>
            <el-table-column label="人员姓名" prop="username">
            </el-table-column>
            <el-table-column label="修改时间" prop="xgsj">
            </el-table-column>
            <el-table-column label="操作" width="250">
              <template #default="scope">
                <span class="operate" style="color: yellowgreen" @click="onloadflie(scope.row)">详情</span>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </template>
      <template #footer>
        <el-button type="primary" v-if="saveBtn" v-loading='loadingshow' @click="submit(ruleFormRef)"> <el-icon>
            <DocumentChecked />
          </el-icon>
          <span>保存</span></el-button>
        <el-button @click="black"> <el-icon>
            <DocumentDelete />
          </el-icon>
          <span>关闭</span></el-button>
      </template>
    </MOSTY.FromPage>
    <!-- 体检记录详情 -->
    <Tjjlxq v-model="showtjjlxq" :title="'体检记录详情'" :rowId="rowId" :zdlist="{
      D_BZ_RYLB_NEW, D_BZ_TSZYLX, D_BZ_JCZYWHYS, D_BZ_ZYJKTJLB, D_BZ_SF
    }" />
    <!-- 选择带队领导 -->
    <ChooseUser v-model="chooseUserVisible" :Single="singleShow" :data="memberList" :leaderid="leaderid"
      @choosedUsers="getSonValue"></ChooseUser>
  </div>
</template>

<script setup>
import {
  reactive,
  ref,
  getCurrentInstance,
  onMounted
} from "vue";
import * as MOSTY from "@/components/MyComponents/index";
import * as rule from "@/utils/rules.js";
import { ElMessage } from "element-plus";
import ChooseUser from "@/components/MyComponents/ChooseUser/Leader.vue";
import Tjjlxq from './tjjlxq.vue'
import { getApi, deleteApi, putApi, postApi } from "@/api/tobAcco_api.js";
import { isString } from '@/utils/tools.js';
const { proxy } = getCurrentInstance();
const { D_BZ_RYLB_NEW, D_BZ_TSZYLX, D_BZ_JCZYWHYS,
  D_BZ_ZYJKTJLB, D_BZ_SF } = proxy.$dict(
    "D_BZ_RYLB_NEW", "D_BZ_TSZYLX", "D_BZ_JCZYWHYS",
    "D_BZ_ZYJKTJLB", "D_BZ_SF",
  );
const props = defineProps({
  obj: {
    type: Object,
    default: () => { }
  }
});
const loadingshow = ref(false)
const chooseUserVisible = ref(false); //选择领导弹窗
const singleShow = ref(true); //单选多选
const memberList = ref([]); //成员选择的id回显
const leaderid = ref("");
const rowId = ref(null)
const tjjlList = ref([])
const showtjjlxq = ref(false);
const zzlx = ref(null);
const activeNames = ref(["1"]);
const emit = defineEmits("changePage");
const ruleFormRef = ref();
let pageTitle = ref("");
const csmclist = ref([]);
const formData = ref({})
const saveBtn = ref(true);
const rules = reactive({
  fullname: [{ required: true, message: "姓名不能为空", trigger: "change" }],
  gender: [{ required: true, message: "请选择性别", trigger: "change" }],
  sitename: [{ required: true, message: "所在场所不能为空", trigger: "change" }],
  ...rule.intRule({ validator: true, require: true }, "age"),
  hazardousfactors: [{ required: true, message: "危害因素不能为空", trigger: "blur" }],
  examinationcycle: [{ required: true, message: "体检周期不能为空", trigger: "change" }],
  yealy: [{ required: true, message: "年份不能为空", trigger: "change" }],
  specialHomeworkCategories: [{ required: true, message: "特殊作业类型不能为空", trigger: "change" }],
  exposureHazardousFactors: [{ required: true, message: "接触危害因素不能为空", trigger: "change" }],
  healthExaminationType: [{ required: true, message: "健康体检类型不能为空", trigger: "change" }],
  ill: [{ required: true, message: "是否有职业病不能为空", trigger: "change" }],
  peopletype: [{ required: true, message: "人员类型不能为空", trigger: "change" }],
  illFile: [{ required: true, message: "患病体检报告不能为空", trigger: "change" }],
  file: [{ required: true, message: "健康体检报告附件不能为空", trigger: "change" }],
});

onMounted(() => {
  pageTitle.value = props.obj.title;
  saveBtn.value = props.obj.saveBtn;
  formData.value = {}
  formData.value.illFile = null
  formData.value.file = null
  if (props.obj.rowid) {
    gtdataxq(props.obj.rowid)
    getjktjlist(props.obj.rowid)
  } else {
    getZywhcs();
  }

})
//获取职业危害场所
function getZywhcs() {
  getApi({}, "/mosty-jcgl/occupationalHazard/queryOccupationalHazardByBmId/").then((res) => {
    res.hazardousfactors = res.hazardousfactors ? res.hazardousfactors.split(',') : null
    csmclist.value = res;
    if (formData.value.hazardsiteid) {
      csmclist.value.forEach(item => {
        if (item.id == formData.value.hazardsiteid) {
          formData.value.sitename = item.sitename
        }
      })
    }
  });
}
//获取详情
function gtdataxq(id) {
  getApi({ id }, `/mosty-jcgl/occHazardOpr/queryOccHazardOprById`).then(
    (res) => {
      res.hazardousfactors = res.hazardousfactors ? res.hazardousfactors.split(',') : []
      formData.value = res;
      getZywhcs()
    }
  );
}
//获取职业健康体检
function getjktjlist(id) {
  getApi({ id }, '/mosty-jcgl/occHazardOpr/queryOccHazardOprChild').then(res => {
    if (res) {
      tjjlList.value = res
    }
  })
}

//获取场所选择
const cahngecsmc = (val) => {
  csmclist.value.forEach((item) => {
    if (item.id == val) {
      formData.value.hazardsiteid = item.id;
      formData.value.sitename = item.sitename;
      formData.value.hazardousfactors = item.hazardousfactors ? item.hazardousfactors.split(',') : [];
    }
  });
};

//点击带队领导选择按钮
function ChooesDdld(val) {
  zzlx.value = val;
  leaderid.value = "";
  singleShow.value = true;
  chooseUserVisible.value = true;
}
//获取人员姓名
const getSonValue = (value) => {
  formData.value.fullname = value[0].userName;
  formData.value.username = value[0].userName;
  formData.value.userid = value[0].id;
};

//查看体检记录详情
function onloadflie(row) {
  rowId.value = row.id
  showtjjlxq.value = true

}
// 保存
const submit = async (formEl) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      loadingshow.value = true
      formData.value.illFile = formData.value.illFile ? formData.value.illFile.toString() : null;
      formData.value.file = formData.value.file ? formData.value.file.toString() : null;
      formData.value.useType = formData.value.peopletype
      formData.value.hazardousfactors = formData.value.hazardousfactors ? formData.value.hazardousfactors.toString() : null;
      if (!formData.value.id) {
        postApi(formData.value, "/mosty-jcgl/occHazardOpr/addOccHazardOprOne").then((res) => {
          ElMessage.success("新增成功");
          emit("changePage", "Main");
        }).finally(() => {
          loadingshow.value = false
          formData.value.hazardousfactors = formData.value.hazardousfactors && isString(formData.value.hazardousfactors) ? formData.value.hazardousfactors.split(',') : formData.value.hazardousfactors;
        })
      } else {
        postApi(formData.value, "/mosty-jcgl/occHazardOpr/updateOccHazardOprOne").then((res) => {
          ElMessage.success("修改成功");
          emit("changePage", "Main");
          loadingshow.value = false
        }).finally(() => {
          loadingshow.value = false
          formData.value.hazardousfactors = formData.value.hazardousfactors && isString(formData.value.hazardousfactors) ? formData.value.hazardousfactors.split(',') : formData.value.hazardousfactors;
        })
      }
    }
  });
};

const black = () => {
  if(!ruleFormRef.value) return;
  if (saveBtn.value) {
    proxy.$modal.confirm('离开会丢失页面中修改的内容，确认离开吗？')
      .then(() => {
        // 关闭上一次的表单校验
        ruleFormRef.value.clearValidate();
        emit("changePage", "Main");
      })
      .catch(() => {
        // catch error
      })
  } else {
    // 关闭上一次的表单校验
    ruleFormRef.value.clearValidate();
    emit("changePage", "Main");
  }

};
</script>

<style lang="scss" scoped>
::-webkit-scrollbar {
  width: 0 !important;
  height: 0;
}

.box_cont {
  height: 80vh;
  overflow-y: scroll;
}

.fromBox {
  width: 100%;
  margin: 20px auto;
  padding: 15px 15px 0 15px;
  border-radius: 1px;
}

.ld_box {
  display: flex;
  margin-right: 20px;
}

.el-form {
  width: 100%;
  align-items: center;
  display: flex;
  flex-wrap: wrap;
  flex-wrap: wrap;
}

.el-form-item {
  display: flex;
  margin-right: 20px;
}

.addbtn {
  margin-bottom: 10px;
}

.bigBox {
  display: block !important;
  padding: 0 14px;
  box-sizing: border-box;
}

.tabbox {
  max-height: 300px;
  overflow-y: scroll;

  .input {
    width: 100%;
    height: 100%;
  }
}

::v-deep .el-table .cell {
  padding: 0 0 !important;
}

::v-deep .el-table--border .el-table__cell .cell {
  padding-left: 0px !important;

  >input {
    width: 100%;
    height: 33px;
  }
}

::v-deep .el-upload-list {
  width: 50%;
}
</style>
