<template>
  <div>
    <el-dialog :title="props.title" width="830px" v-model="props.addUserShow" :before-close="black">
      <div class="fromBox">
        <el-form class="mosty-from-wrap" ref="ruleFormRef" label-width="148px" :model="formData" :inline="true"
          :rules="rules" :disabled="!props.saveBtnShow">
          <el-form-item label="填写类型:" prop="userType">
            <MOSTY.DictRidioAndSelect :dictData="[{ value: '01', label: '选择' }, { value: '02', label: '填写' }]"
              @onChange="changeUserType" v-model="formData.userType" selectType="radio" :disabled="formData.id"
              style="width: 337px" />
          </el-form-item>
          <el-form-item label="人员姓名:" prop="username" v-if="formData.userType == '01'">
            <el-input v-model="formData.username" readonly clearable style="width: 600px">
              <template #append> <el-button class="cursor" @click="ChooesDdld('01')"
                  :disabled="formData.id">选择</el-button></template>
            </el-input>
          </el-form-item>
          <el-form-item label="人员姓名:" prop="username" v-if="formData.userType == '02'">
            <el-input v-model="formData.username" clearable style="width: 600px" />
          </el-form-item>
          <el-form-item label="身份证号:" prop="idCard">
            <MOSTY.IdentityCard width="600px" v-model="formData.idCard" clearable :disabled='formData.id' />
          </el-form-item>
          <el-form-item label="人员类别：" prop="peopletype">
            <el-select v-model="formData.peopletype" placeholder="请选择人员类别" style="width: 600px"
              :disabled="formData.userType == '02'">
              <el-option v-for="item in props.zdlist.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="hazardsiteid">
            <el-select v-model="formData.hazardsiteid" clearable style="width: 600px" placeholder="请选择职业危害场所"
              @change="getChangeValue">
              <el-option v-for="item in csmclist" :key="item.id" :label="item.partname" :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item label="接触危害因素：">
            <el-select v-model="formData.hazardousfactors" disabled placeholder="请输入危害类型" multiple style="width: 600px">
              <el-option v-for="item in props.zdlist.D_TB_ZYJK_WHYS" :key="item.value" :label="item.label"
                :value="item.value"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>

        <el-button type="primary" v-if="props.saveBtnShow" v-loading="loadingshow" @click="submit(ruleFormRef)">
          <el-icon>
            <DocumentChecked />
          </el-icon>保存
        </el-button>
        <el-button @click="black">
          <el-icon>
            <DocumentDelete />
          </el-icon>关闭
        </el-button>
      </template>
    </el-dialog>
    <!-- 选择带队领导 -->
    <ChooseUser v-model="chooseUserVisible" :deptId="props.deptid" :Single="singleShow" :data="memberList"
      :leaderid="leaderid" @choosedUsers="getSonValue" :isNewChooseDept="true" :searchType="'04'"></ChooseUser>
  </div>
</template>

<script setup>
import { reactive, ref, onMounted, getCurrentInstance } from "vue"
import { ElMessage } from "element-plus"
import ChooseUser from "@/components/MyComponents/ChooseUser/Leader.vue"
import { getApi, postApi } from "@/api/tobAcco_api.js"
import * as MOSTY from "@/components/MyComponents/index"
import { getItem } from "@/utils/storage"
const { proxy } = getCurrentInstance();
const props = defineProps({
  title: String,
  addUserShow: {
    type: Boolean,
    default: false
  },
  saveBtnShow: {
    type: String,
    default: false
  },
  hazardsiteid: String,
  deptid: String,
  rowId: String,
  zdlist: {
    type: Object,
    default: () => { }
  },
  obj: {
    type: Object,
    default: () => { }
  },
  listQuery: Object
})
const loadingshow = ref(false)
const chooseUserVisible = ref(false) //选择领导弹窗
const singleShow = ref(true) //单选多选
const memberList = ref([]) //成员选择的id回显
const leaderid = ref("")
const zzlx = ref(null)
const emit = defineEmits("changePage")
const ruleFormRef = ref()
const formData = ref({})
const saveBtn = ref(true)
const csmclist = ref([])
let idCardValidity = (rule, code, callback) => {
  var city = {
    11: "北京",
    12: "天津",
    13: "河北",
    14: "山西",
    15: "内蒙古",
    21: "辽宁",
    22: "吉林",
    23: "黑龙江 ",
    31: "上海",
    32: "江苏",
    33: "浙江",
    34: "安徽",
    35: "福建",
    36: "江西",
    37: "山东",
    41: "河南",
    42: "湖北 ",
    43: "湖南",
    44: "广东",
    45: "广西",
    46: "海南",
    50: "重庆",
    51: "四川",
    52: "贵州",
    53: "云南",
    54: "西藏 ",
    61: "陕西",
    62: "甘肃",
    63: "青海",
    64: "宁夏",
    65: "新疆",
    71: "台湾",
    81: "香港",
    82: "澳门",
    91: "国外 "
  }
  var tip = ""
  var pass = true

  if (!code || !/^\d{6}(18|19|20)?\d{2}(0[1-9]|1[012])(0[1-9]|[12]\d|3[01])\d{3}(\d|X)$/i.test(code)) {
    tip = "身份证号格式错误"
    pass = false
  } else if (!city[code.substr(0, 2)]) {
    tip = "地址编码错误"
    pass = false
  } else {
    // 18位身份证需要验证最后一位校验位
    if (code.length === 18) {
      code = code.split("")
      // ∑(ai×Wi)(mod 11)
      // 加权因子
      var factor = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2]
      // 校验位
      var parity = [1, 0, "X", 9, 8, 7, 6, 5, 4, 3, 2]
      var sum = 0
      var ai = 0
      var wi = 0
      for (var i = 0; i < 17; i++) {
        ai = code[i]
        wi = factor[i]
        sum += ai * wi
      }
      var last = parity[sum % 11]
      if (parity[sum % 11] != code[17]) {
        tip = "校验位错误"
        pass = false
      }
    }
  }
  if (!pass) {
    callback(new Error(tip))
  } else {
    callback()
  }
  // if (!pass) alert(tip)
  // return pass
}
const rules = reactive({
  userType: [{ required: true, message: "请选择填写类型", trigger: "change" }],
  username: [{ required: true, message: "姓名不能为空", trigger: "blur" }],
  idCard: [
    { required: true, message: "请输入证件号", trigger: "blur" },
    {
      pattern: /(^\d{8}(0\d|10|11|12)([0-2]\d|30|31)\d{3}$)|(^\d{6}(18|19|20)\d{2}(0\d|10|11|12)([0-2]\d|30|31)\d{3}(\d|X|x)$)/,
      message: "请输入正确的证件号",
      trigger: "blur"
    },
    { validator: idCardValidity, trigger: "blur" }
  ],
  peopletype: [{ required: true, message: "人员类别不能为空", trigger: "blur" }],
  hazardsiteid: [{ required: true, message: "场所名称不能为空", trigger: "blur" }]
})

onMounted(() => {
  saveBtn.value = props.saveBtnShow
  formData.value = {}
  formData.value.hazardsiteid = props.hazardsiteid
  getcsData()
  if (props.rowId) {
    gtdataxq(props.rowId)
  }
})
// 选择类型切换
const changeUserType = () => {
  formData.value.username = null
  formData.value.userid = null
  formData.value.peopletype = null
  formData.value.idCard = null
  if (formData.value.userType == '02') {
    formData.value.peopletype = '3'
  }
}
function getcsData() {
  postApi({
    orgcode: getItem("deptId").ssdwid,
    pageCurrent: 1,
    pageSize: 5e4
  }, "/mosty-jcgl/occupationalHazard/selectPage"
  ).then(res => {
    if (res.records) {
      csmclist.value = res.records
      csmclist.value.forEach(item => {
        if (item.id == formData.value.hazardsiteid) {
          formData.value.hazardousfactors = item.hazardousfactors ? item.hazardousfactors.split(',') : []
        }
      })

    }
  })
}
const getChangeValue = e => {
  if (csmclist.value.find(item => item.id == e)) formData.value.hazardousfactors = csmclist.value.find(item => item.id == e).hazardousfactors.split(",")
}

//获取详情
function gtdataxq(id) {
  getApi({ id }, `/mosty-jcgl/occHazardOpr/queryById`).then(res => {
    formData.value = res
    if (formData.value.hazardsiteid) {
      csmclist.value.forEach(item => {
        if (item.id == formData.value.hazardsiteid) {
          formData.value.hazardousfactors = item.hazardousfactors ? item.hazardousfactors.split(',') : []
        }
      })
    }
    formData.value.userType = res?.userid ? '01' : '02' // 有就是选择的，没有就是填写的
  })
}

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

// 保存
const submit = async formEl => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      loadingshow.value = true
      if (!formData.value.id) {
        postApi(formData.value, "/mosty-jcgl/occHazardOpr/add")
          .then(res => {
            ElMessage.success("新增成功")
            emit("changePage", false)
            loadingshow.value = false
          })
          .finally(() => {
            loadingshow.value = false
          })
      } else {
        postApi(formData.value, "/mosty-jcgl/occHazardOpr/update")
          .then(res => {
            ElMessage.success("修改成功")
            emit("changePage", false)
            loadingshow.value = false
          })
          .finally(() => {
            loadingshow.value = false
          })
      }
    }
  })
}

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

}
</script>

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

.fromBox {
  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;
  justify-content: start;
  flex-wrap: wrap;
}

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

.addbtn {
  margin-bottom: 10px;
}

.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>
