<template>
  <MOSTY.PageTree :pageTitle="'保安人员信息列表'" :searchType="'01'" @getDeptId="getdeptId">
    <template #serach>
      <el-divider />
      <MOSTY.Search :searchArr="searchArr" @submit="onSearch">
        <el-button type="primary" @click="addInfo">
          <el-icon>
            <Plus />
          </el-icon>新增
        </el-button>
      </MOSTY.Search>
    </template>
    <template #table>
      <el-divider />
      <div :style="{ height: totalHeight }">
        <MOSTY.Table :table-columns="tableColumn" :tableData="tableData" :tableloading="tableoading"
          :tableHeight="'100%'" :isSelect="false" style="width: 100%;" :isSort="false">
          <template #gender="{ row }">
            <dict-tag v-if="row.gender" :options="D_BZ_XB" :value="row.gender" :tag="false" />
            <span v-else>无</span>
          </template>
          <template #peopleeducation="{ row }">
            <dict-tag v-if="row.peopleeducation" :options="D_BZ_WHCD" :value="row.peopleeducation" :tag="false" />
            <span v-else>无</span>
          </template>
          <!-- 操作 -->
          <template #actions="{ row }">
            <span class="operedit" @click="editInfo(row)"><el-icon>
                <EditPen />
              </el-icon>修改</span>
            <el-popconfirm confirm-button-text="是" cancel-button-text="否" icon-color="red" title="确定要删除?"
              @confirm="handledelete(row)">
              <template #reference>
                <span class="operdel" size="small"><el-icon>
                    <Delete />
                  </el-icon>删除</span>
              </template>
            </el-popconfirm>
          </template>
        </MOSTY.Table>
      </div>
      <div class="fenye">
        <el-pagination class="pagination" @size-change="handleSizeChange" @current-change="handleCurrentChange"
          :current-page="listQuery.pageCurrent" :page-sizes="[2, 5, 10, 20]" :page-size="listQuery.pageSize"
          layout="total, prev, pager, next, sizes, jumper" :total="total"></el-pagination>
      </div>
    </template>
  </MOSTY.PageTree>
  <div>
    <el-dialog v-model="dialogVisible" :title="data.title" width="70%" center :before-close="CloseEvent">
      <div v-if="dialogVisible">
        <el-form class="mosty-from-wrap" ref="ruleFormRef" label-width="130px" :model="fromObj" :inline="true"
          :rules="rules" :disabled="!data.savebtn">
          <el-form-item label="人员姓名：" prop="peoplenasme">
            <!-- <el-input v-model="fromObj.peoplenasme" clearable style="width: 250px" /> -->
            <el-input v-model="fromObj.peoplenasme" readonly clearable style="width: 250px;">
              <template #append>
                <el-button class='cursor' @click="ChooesDdld('01')">选择</el-button>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item label="身份证：" prop="identitycard">
            <MOSTY.IdentityCard width="250px" v-model="fromObj.identitycard" clearable @onInput="identityCardChange">
            </MOSTY.IdentityCard>
          </el-form-item>
          <el-form-item label="联系方式：" prop="peoplephone">
            <MOSTY.Phone width="250px" show-word-limit v-model="fromObj.peoplephone" maxlength="11" clearable
              @onInput="phoneChange">
            </MOSTY.Phone>
          </el-form-item>
          <el-form-item label="出生日期：" prop="birthdata">
            <el-date-picker v-model="fromObj.birthdata" type="data" format="YYYY-MM-DD" value-format="YYYY-MM-DD"
              placeholder="请选择出生日期" :default-value="getDefaultDates" :disabled-date="disabledDate" style="width: 250px">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="性别：" prop="gender">
            <el-select v-model="fromObj.gender" style="width: 250px" 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="peopleeducation">
            <el-select v-model="fromObj.peopleeducation" style="width: 250px" clearable>
              <el-option v-for="item in D_BZ_WHCD" :key="item" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="岗位：" prop="post">
            <el-input v-model="fromObj.post" clearable style="width: 250px" />
          </el-form-item>
          <el-form-item v-if="fromObj.xgfname" label="相关方：" prop="xgfname">
            <el-input v-model="fromObj.xgfname" clearable style="width: 250px" disabled />
            <!-- <el-select v-model="fromObj.xgfid" style="width: 250px" clearable>
              <el-option v-for="item in xgflist" :key="item" :label="item.label" :value="item.value"
                @click="changexgf(item)" />
            </el-select> -->
          </el-form-item>
          <el-form-item v-else label="部门：">
            <el-input v-model="fromObj.deptname" clearable style="width: 250px" disabled />
          </el-form-item>
          <el-form-item label="用工方式：" prop="mode">
            <MOSTY.DictRidioAndSelect selectType="select" :dictData="D_BZ_YGFS" v-model="fromObj.mode"
              :disabledItem="isInvestmentCompany || fromObj.xgfname ? ['3'] : ['1', '2']" />
            <!-- <el-select v-model="fromObj.mode" style="width: 250px" clearable>
              <el-option v-for="item in D_BZ_YGFS" :key="item" :label="item.label" :value="item.value" />
            </el-select> -->
          </el-form-item>
          <el-form-item label="工作地点：" prop="worksite">
            <el-input v-model="fromObj.worksite" clearable style="width: 665px" />
          </el-form-item>
          <el-form-item label="备注：">
            <el-input v-model="fromObj.bz" clearable style="width: 665px" />
          </el-form-item>
          <el-form-item label="上传的图片：">
            <MOSTY.Upload v-model="fromObj.file" :limit="5" :delrow="delrow" :isEdit="fileEdit" :ShowfileList="true"
              @filehandleChange="changeFile" :isImg="true" :disabled="!data.savebtn" />
          </el-form-item>
        </el-form>
        <!-- 选择人员 -->
        <MOSTY.xgfandzzjgry v-model="chooseUserVisible" :deptId="deptId" :Single="singleShow" :data="memberList"
          :stlyrylx='stlyrylx' :relatedid="null" @choosedUsers="getSonValue" @changerylx='changerylx' />
      </div>
      <template #footer>
        <span class="dialog-footer">

          <el-button v-if="data.savebtn" @click="saveinfo(ruleFormRef)"><el-icon>
              <DocumentChecked />
            </el-icon>保存</el-button>
          <el-button @click="CloseEvent"><el-icon>
              <DocumentDelete />
            </el-icon>关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
// 引入
import { reactive, onMounted, ref, getCurrentInstance } from "vue";
import { getItem } from "@/utils/storage";
import { ElMessage } from "element-plus";
import { getApi, postApi } from "@/api/tobAcco_api.js";
import * as MOSTY from "@/components/MyComponents/index";
import * as rule from "@/utils/rules.js";
const { proxy } = getCurrentInstance();
// 数据
const fileEdit = ref(true);
const { D_BZ_XB } = proxy.$dict("D_BZ_XB");
const { D_BZ_WHCD } = proxy.$dict("D_BZ_WHCD");
const { D_BZ_YGFS } = proxy.$dict("D_BZ_YGFS");
const tableColumn = reactive([
  {
    title: "单位",
    prop: "orgname",
  },
  {
    title: "部门",
    prop: "deptname",
  },
  {
    title: "人员姓名",
    prop: "peoplenasme",
  },
  {
    title: "身份证号",
    prop: "identitycard",
  },
  {
    title: "性别",
    prop: "gender",
    slot: true
  },
  {
    title: "工作地点",
    prop: "worksite",
  },
  {
    title: "操作",
    prop: "actions",
    slot: true
  }
])
const searchArr = reactive([
  {
    showType: "input",
    prop: "anyname",
    width: '300px',
    placeholder: '请输入人员名称或工作地点进行查询'
  },

])
const dialogVisible = ref(false);
//查询条件
const data = reactive({
  deptname: "",
  title: "",
  savebtn: true,
  seeimg: true,
  img: []
});
const xgflist = ref([])
const fromObj = ref({});
const tableData = ref([]);
const delrow = ref({}); //删除文件列表
// 分页
const listQuery = reactive({
  pageCurrent: 1,
  pageSize: 20,
  orgid: ""
});
const total = ref(0);
const CloseEvent = () => {
  if (data.savebtn) {
    proxy.$modal.confirm('离开会丢失页面中修改的内容，确认离开吗？')
      .then(() => {
        // 关闭上一次的表单校验
        ruleFormRef.value.clearValidate();
        dialogVisible.value = false;
      })
      .catch(() => {
        // catch error
      })
  } else {
    // 关闭上一次的表单校验
    ruleFormRef.value.clearValidate();
    dialogVisible.value = false;
  }

};
//规则校验
const rules = reactive({
  peoplenasme: [
    { required: true, message: "人员姓名不能为空", trigger: "blur" }
  ],
  ...rule.identityCardRule({ require: true, validator: true }, "identitycard"),
  ...rule.phoneRule({
    require: true,
    validator: true
  }, 'peoplephone'),
  birthdata: [{ required: true, message: "出生日期不能为空", trigger: "blur" }],
  gender: [{ required: true, message: "性别不能为空", trigger: "blur" }],
  peopleeducation: [{ required: true, message: "学历不能为空", trigger: "blur" }],
  worksite: [{ required: true, message: "工作地点不能为空", trigger: "blur" }],
  post: [{ required: true, message: "岗位不能为空", trigger: "blur" }],
  mode: [{ required: true, message: "用工方式不能为空", trigger: "blur" }]
});
const totalHeight = ref()
onMounted(() => {
  totalHeight.value = `calc(100vh - 335px)`
});
// 查询
const onSearch = (obj) => {
  listQuery.anyname = obj.anyname
  listQuery.pageCurrent = 1;
  getListData();
}
//获取部门数据
const getdeptId = (val) => {
  listQuery.orgid = val.id;
  listQuery.pageCurrent = 1;
  getListData();
};
// 获取表格数据
const tableloading = ref(false);
function getListData() {
  tableloading.value = true;
  data.deptname = getItem("deptId").ssbmid;
  postApi(listQuery, `/mosty-jcgl/peoplemessage/queryPeoplemessage`).then(
    (res) => {
      if (res.records) {
        tableloading.value = false;
        tableData.value = res.records;
        total.value = res.total;
      } else {
        tableData.value = [];
        tableloading.value = false;
      }
    }
  ).finally(() => {
    tableloading.value = false;
  });
}
const getmain = (id) => {
  if (id) {
    getApi({}, "/mosty-jcgl/peoplemessage/getPeoplemessageById/" + id).then(
      (res) => {
        if (res) {
          fromObj.value = res;
        }
      }
    );
  }
};
//新增
function addInfo() {
  fromObj.value = {};
  fromObj.value.file = null;
  dialogVisible.value = true;
  data.savebtn = true;
  data.seeimg = false;
  data.title = "保安人员信息新增";
}
//详情
function handleSee(row) {
  dialogVisible.value = true;
  data.title = "保安人员信息详情";
  fromObj.value.file = null;
  data.savebtn = false;
  data.seeimg = true;
  getmain(row.id);
}
//修改
function editInfo(row) {
  dialogVisible.value = true;
  data.savebtn = true;
  data.seeimg = false;
  fromObj.value.file = null;
  data.title = "保安人员信息修改";
  getmain(row.id);
}
//删除
function handledelete(row) {
  postApi(
    {},
    "/mosty-jcgl/peoplemessage/deletePeoplemessageOne/" + row.id
  ).then((res) => {
    ElMessage.success("删除成功");
    getListData();
  });
}
// 新的文件上传返回
const changeFile = (row) => {
};
const ruleFormRef = ref();
function changexgf(val) {
  fromObj.value.xgfname = val.label
}
//保存
const saveinfo = async (ruleFormRef) => {
  if (!ruleFormRef) return;
  await ruleFormRef.validate((valid) => {
    if (valid) {
      fromObj.value.file = fromObj.value.file
        ? fromObj.value.file.toString()
        : "";
      if (fromObj.value.id) {
        postApi(
          fromObj.value,
          "/mosty-jcgl/peoplemessage/updatePeoplemessageOne"
        )
          .then((res) => {
            ElMessage.success("修改成功");
            dialogVisible.value = false;
            getListData();
          })
      } else {
        postApi(
          fromObj.value,
          "/mosty-jcgl/peoplemessage/addPeoplemessageOne"
        )
          .then((res) => {
            ElMessage.success("新增成功");
            dialogVisible.value = false;
            getListData();
          })
      }
    } else {
      ElMessage.error("请输入必填项");
    }
  });
};
//分页
const handleSizeChange = (currentSize) => {
  listQuery.pageSize = currentSize;
  getListData();
};
const handleCurrentChange = (currentPage) => {
  listQuery.pageCurrent = currentPage;
  getListData();
};
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 isInvestmentCompany = ref(false)
const getSonValue = (value) => {
  // 驾驶员姓名
  if (zzlx.value == "01") {
    fromObj.value.xgfname = value[0].relatedname || ''
    fromObj.value.xgfid = value[0].relatedid || ''
    fromObj.value.driveruserid = value[0].id;
    if (fromObj.value.xgfid && value[0].idcard) {
      isInvestmentCompany.value = true
      fromObj.value.birthdata = getBirth(value[0].idcard);
      fromObj.value.mode = ''
      fromObj.value.identitycard = value[0].idcard;
      fromObj.value.gender = value[0].sex ? value[0].sex : getSex(value[0].idcard);
    } else {
      isInvestmentCompany.value = false
      getdreardata(fromObj.value.driveruserid);
    }
    fromObj.value.peoplephone = value[0].mobile;
    fromObj.value.peoplenasme = value[0].userName;
    fromObj.value.orgid = value[0].orgid;
    fromObj.value.orgname = value[0].orgname;
    fromObj.value.deptid = value[0].deptId || value[0].deptid;
    fromObj.value.deptname = value[0].deptName || value[0].deptname;
    getsgz(fromObj.value.driveruserid)
  }

};
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';
}
//根据用户id查询证号
function getsgz(userid) {
  getApi({ userid }, '/mosty-jcgl/driverposts/queryDriByUserid').then(res => {
    if (res) {
      if (res.zjz) {
        fromObj.value.cdfiid = res.zjz
      } else if (res.sgz) {
        fromObj.value.cdfiid = res.sgz
      }

    }

  })
}

function getdreardata(id) {
  if (stlyrylx.value == '01') {
    getApi({}, `/mosty-base/sysUser/getUserInfo/${id}`).then((res) => {
      fromObj.value.gender = res.sex ? res.sex : getSex(res?.idEntityCard);
      if (!['1', '2'].includes(fromObj.value.sex)) fromObj.value.sex = ''
      fromObj.value.birthdata = res.birthday ? res.birthday : getBirth(res?.idEntityCard);
      fromObj.value.identitycard = res.idEntityCard;
      fromObj.value.drivenumber = res.idEntityCard;
      fromObj.value.mode = '3'
    });
  } else {
    getApi({ id }, `/mosty-jcgl/relatedUser/getInfo`).then((res) => {
      fromObj.value.gender = res.sex ? res.sex : getSex(res?.idEntityCard);
      if (!['1', '2'].includes(fromObj.value.sex)) fromObj.value.sex = ''
      fromObj.value.birthdata = res.birthday ? res.birthday : getBirth(res?.idEntityCard);
      fromObj.value.identitycard = res.idEntityCard;
      fromObj.value.drivenumber = res.idEntityCard;
      fromObj.value.mode = '1'
    });
  }

}
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}`;
}
</script>

<style lang="scss" scoped>
.el-form {
  width: 100%;
  display: flex;
  flex-wrap: wrap;
}
</style>