<template>
  <div class="app-container pro-project-info-subdepts-users-index">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">

      <el-form-item label="所属单位" prop="subDeptId">
        <el-select v-model="queryParams.subDeptId" placeholder="请选择所属单位" @change="doSubDeptChange('query')" clearable>
          <el-option v-for="(it) in data.subdepts" :key="it.id" :label="it.subDeptName" :value="it.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="班组" prop="subDeptName">
        <el-select v-model="queryParams.subDeptGroup" placeholder="请选择班组" @change="doDeptGroupChange" clearable>
          <el-option v-for="(it, idx) in data.queryDeptGroups" :key="idx" :label="it.groupName" :value="it.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="姓名" prop="userName">
        <el-input v-model="queryParams.userName" placeholder="请输入姓名" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="联系电话" prop="userId">
        <el-input v-model="queryParams.userPhone" placeholder="请输入联系电话" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="工种类型" prop="craftType">
        <el-select v-model="queryParams.craftType" placeholder="请选择工种类型" clearable>
          <el-option v-for="dict in pro_craft_type" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="工种岗位" prop="craftPost">
        <el-select v-model="queryParams.craftPost" placeholder="请选择工种岗位" clearable>
          <el-option
            v-for="dict in (queryParams.craftType ? pro_craft_post.filter(d => d.remark == queryParams.craftType) : [])"
            :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd"
          v-hasPermi="['manage:proProjectInfoSubdeptsUsers:add']">新增人员</el-button>
      </el-col>
      <el-col :span="1.5" v-if="false">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
          v-hasPermi="['manage:proProjectInfoSubdeptsUsers:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5" v-if="false">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['manage:proProjectInfoSubdeptsUsers:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport"
          v-hasPermi="['manage:proProjectInfoSubdeptsUsers:export']">导出花名册</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Download" @click="handleBatchEnterState(1)"
          v-hasPermi="['manage:proProjectInfoSubdeptsUsers:export']">批量离场</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Download" @click="handleBatchEnterState(0)"
          v-hasPermi="['manage:proProjectInfoSubdeptsUsers:export']">批量入场</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="proProjectInfoSubdeptsUsersList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="头像" align="center">
        <template #default="scope">
          <el-image :src="scope.row.userPicture" style="height:80px;" :preview-teleported="true"
            :preview-src-list="[scope.row.userPicture]"></el-image>
        </template>
      </el-table-column>
      <el-table-column label="姓名" align="center" prop="userName" />
      <el-table-column label="手机" align="center" prop="userPhone" />
      <el-table-column label="身份证" align="center" prop="cardCode" />
      <el-table-column label="性别" align="center" prop="userSex">
        <template #default="scope">{{ scope.row.userSex == '男' ? '男' : '女' }}</template>
      </el-table-column>
      <el-table-column label="民族" align="center" prop="info.nation" width="80" />
      <el-table-column label="所属单位" align="center" prop="subDeptName" />

      <el-table-column label="联系电话" align="center" prop="user.phonenumber" v-if="false" />
      <el-table-column label="班组" align="center" prop="subDeptGroupName" />
      <el-table-column label="工种类型" align="center" prop="craftType">
        <template #default="scope">
          <dict-tag :options="pro_craft_type" :value="scope.row.craftType" />
        </template>
      </el-table-column>
      <el-table-column label="工种岗位" align="center" prop="craftPost">
        <template #default="scope">
          <dict-tag :options="pro_craft_post" :value="scope.row.craftPost" />
        </template>
      </el-table-column>
      <el-table-column label="三级安全教育" align="center" class-name="small-padding fixed-width" width="100">
        <template #default="scope">
          <div v-if="scope.row.subDeptType=='4' || scope.row.subDeptType=='5'">
            <el-button v-if="scope.row.eduStatus=='0'" link type="primary" icon="Link" @click="handleDownloadFile(scope.row)">查看</el-button>
            <el-button v-if="scope.row.eduStatus!='0'" link type="warning" disabled>未完成</el-button>
          </div>
          <el-button v-if="scope.row.subDeptType!='4' && scope.row.subDeptType!='5'" link  disabled> - </el-button>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="useStatus">
        <template #default="scope">
          <span v-if="scope.row.useStatus == 0" style="color: green;">在场</span>
          <span v-else style="color: red">离场</span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="出生日期" align="center" prop="info.birthDayStr" v-if="false" />
      <el-table-column label="籍贯" align="center" prop="info.nativePlace" v-if="false" /> -->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" width="150">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['manage:proProjectInfoSubdeptsUsers:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
            v-hasPermi="['manage:proProjectInfoSubdeptsUsers:remove']" v-if="1==2">删除</el-button>
          <el-button link type="primary" icon="Delete" @click="handleEnter(scope.row)" v-if="scope.row.useStatus == 0"
            v-hasPermi="['manage:proProjectInfoSubdeptsUsers:remove']">离场</el-button>
          <el-button link type="primary" icon="Delete" @click="handleEnter(scope.row)" v-else
            v-hasPermi="['manage:proProjectInfoSubdeptsUsers:remove']">进场</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改分包单位工人对话框 -->
    <el-drawer v-model="open" size="960px" class="edit-drawer">
      <template #header>
        <div style="position: relative;">{{ title }}</div>
      </template>
      <el-form ref="proProjectInfoSubdeptsUsersRef" :model="form" :rules="rules" label-width="120px"
        style="position: relative;">

        <el-row v-if="data.phoneState || true">
          <el-col :span="12">
            <el-form-item label="所属项目">
              <el-tag effect="plain">{{ form.projectName }}</el-tag>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属单位" prop="subDeptId">
              <el-select v-model="form.subDeptId" placeholder="请选择所属单位" @change="doSubDeptChange()">
                <el-option v-for="(it) in data.subdepts" :key="it.id" :label="it.subDeptName" :value="it.id" />
              </el-select>
            </el-form-item>
          </el-col>
          
          <el-col :span="24">
            <el-form-item label="身份证信息" prop="identificationCard">
              <el-col :span="8">
                <div class="div-header">头像面</div>
                <image-upload v-model="form.certificatePhoto1" :limit="1" class="identification-card-1"
                  @change="doImageUpload" />
              </el-col>
              <el-col :span="8">
                <div class="div-header">国徽面</div>
                <image-upload v-model="form.certificatePhoto2" :limit="1" class="identification-card-2"
                  @change="doImageUpload" />
              </el-col>
              <el-col :span="8">
                <div class="div-header">人脸识别头像</div>
                <image-upload v-model="form.faceImage" :limit="1" class="face-image" @change="doImageUpload" />
              </el-col>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="姓名" prop="userName">
              <el-input v-model="form.userName" placeholder="请输入姓名" />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="证件号码" prop="certificateCode" class="fi-certificate">
              <el-select v-model="form.certificateType">
                <el-option v-for="dict in certificate_type" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
              <el-input v-model="form.certificateCode" placeholder="请输入证件号码" />
            </el-form-item>
          </el-col>
          <div style="width: 100%;">
            <el-form-item label="联系电话" prop="userPhone">
              <el-input v-model="form.userPhone" disabled v-if="data.mode == 'edit'" placeholder="请输入联系电话"
                minlength="11" maxlength="11" style="width: 200px;" />
              <el-input v-model="form.userPhone" v-else placeholder="请输入联系电话" minlength="11" maxlength="11"
                style="width: 200px;" />
              <el-button type="primary" v-if="data.mode != 'edit' && false" style="margin-left:10px;"
                @click="queryPhone">查询</el-button>
              <span style="margin-left:10px;color:#999;">此电话号码将用作登录</span>
            </el-form-item>
          </div>
          <el-col :span="12">
            <el-form-item label="班组名称" prop="subDeptGroup">
              <el-select v-model="form.subDeptGroup" placeholder="请选择班组" @change="doDeptGroupChange">
                <el-option v-for="(it, idx) in data.deptGroups" :key="idx" :label="it.groupName" :value="it.id" />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="岗位">
              <el-input v-model="form.craftTypeName" disabled />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="工种" v-if="data.isManager" prop="craftPost">
              <el-select v-model="form.craftPost">
                <el-option v-for="dict in data.craftPostList" :key="dict.value"
                  :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="工种" v-else>
              <el-input v-model="form.craftPostName" disabled />
            </el-form-item>
          </el-col>

          <el-col :span="12"><el-form-item label="民族">
              <el-select v-model="form.nation">
                <el-option v-for="(it, idx) in data.nationOpts" :key="idx" :label="it" :value="it" />
              </el-select>
            </el-form-item></el-col>
          <el-col :span="12"><el-form-item label="性别">
              <el-radio-group v-model="form.sex">
                <el-radio v-for="(dict, idx) in sys_user_sex" :key="idx" :label="dict.label" :value="dict.value">{{ dict.label }}</el-radio>
              </el-radio-group>
            </el-form-item></el-col>
          <el-col :span="12"><el-form-item label="文件程度">
              <el-select v-model="form.educationalType">
                <el-option v-for="dict in educational_type" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item></el-col>
          <el-col :span="12"><el-form-item label="出生日期">
              <el-date-picker v-model="form.birthDay" type="date" placeholder="请选择出生日期" />
            </el-form-item></el-col>
          <el-col :span="12"><el-form-item label="籍贯">
              <el-input v-model="form.nativePlace" placeholder="请输入籍贯" />
            </el-form-item></el-col>
          <el-col :span="24"><el-form-item label="家庭地址">
              <el-input v-model="form.address" placeholder="请输入家庭地址" />
            </el-form-item></el-col>

          <el-col :span="12"><el-form-item label="紧急联系人">
              <el-input v-model="form.emergencyContact" placeholder="请输入紧急联系人" />
            </el-form-item></el-col>
          <el-col :span="12"><el-form-item label="紧急联系人电话">
              <el-input v-model="form.contactPhone" placeholder="请输入紧急联系人电话" />
            </el-form-item></el-col>
          <el-col :span="12"><el-form-item label="工资卡银行">
              <el-input v-model="form.bankName" placeholder="请输入工资卡银行" />
            </el-form-item></el-col>
          <el-col :span="12"><el-form-item label="工资卡号">
              <el-input v-model="form.bankCardNo" placeholder="请输入工资卡号" />
            </el-form-item></el-col>
          <el-col :span="12"><el-form-item label="开户网点">
              <el-input v-model="form.bankOffice" placeholder="请输入开户网点" />
            </el-form-item></el-col>

          <el-col :span="24">
            <el-form-item label="身份证信息" prop="identificationCard">
              <el-col :span="8">
                <div class="div-header">头像面</div>
                <image-upload v-model="form.certificatePhoto1" :limit="1" class="identification-card-1"
                  @change="doImageUpload(1)" />
              </el-col>
              <el-col :span="8">
                <div class="div-header">国徽面</div>
                <image-upload v-model="form.certificatePhoto2" :limit="1" class="identification-card-2"
                  @change="doImageUpload(2)" />
              </el-col>
              <el-col :span="8">
                <div class="div-header">人脸识别头像</div>
                <image-upload v-model="form.faceImage" :limit="1" class="face-image" @change="doImageUpload(3)" />
              </el-col>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script setup name="ProProjectInfoSubdeptsUsers">
import { listProProjectInfoSubdeptsUsers, getProProjectInfoSubdeptsUsers, updateEnterState, delProProjectInfoSubdeptsUsers, addProProjectInfoSubdeptsUsers, updateProProjectInfoSubdeptsUsers } from "@/api/manage/proProjectInfoSubdeptsUsers";
import { listProProjectInfoSubdepts } from "@/api/manage/proProjectInfoSubdepts";
import { listProProjectInfoSubdeptsGroup } from "@/api/manage/proProjectInfoSubdeptsGroup";
import { listUser } from "@/api/system/user";
import useUserStore from '@/store/modules/user'
import dayjs from 'dayjs'
const userStore = useUserStore()
const { proxy } = getCurrentInstance();
const { sys_use_status, pro_craft_type, sys_is_del, pro_craft_post, certificate_type, educational_type,sys_user_sex } = proxy.useDict('sys_use_status', 'pro_craft_type', 'sys_is_del', 'pro_craft_post', 'certificate_type', 'educational_type','sys_user_sex');

const proProjectInfoSubdeptsUsersList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const validatePhone = (rule, value, callback) => {
  if (!/^1\d{10}$/.test(value)) {
    callback(new Error('请输入有效手机号码!'))
  } else {
    callback()
  }
}
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    projectId: null,
    subDeptId: null,
    subDeptName: null,
    userId: null,
    userName: null,
    bankOffice: '',
    craftTypeName: null,
    craftType: null,
    craftPostName: null,
    craftPost: null,
    eduStatus: null,
    eduFilePath: null,
    eduSignPath: null,
    eduDate: null,
    approveStatus: null,
    useStatus: null,
    subStep: null,
    illnessStatus: null,
    supIllnessStatus: null,
    isDel: null,
  },
  rules: {
    subDeptId: [{ required: true, trigger: ['blur', 'change'], message: "请选择所属单位" }],
    userName: [{ required: true, trigger: ['blur', 'change'], message: "请输入姓名" }],
    userPhone: [
      { required: true, trigger: ['blur', 'change'], message: "请输入手机号码" },
      { min: 11, max: 11, message: '请输入有效手机号码', trigger: 'blur' },
      { validator: validatePhone, trigger: 'blur' }],
    certificateCode: [{ required: true, trigger: ['blur', 'change'], message: "请输入证件号码" }],
    craftPost: [{ required: true, trigger: ['blur', 'change'], message: "请选择工种" }],
    identificationCard: [{ required: true, trigger: ['blur', 'change'], message: "请上传身份证信息" }],
    subDeptGroup: [{ required: true, trigger: ['blur', 'change'], message: "请选择班组" }],
  },
  subdepts: [],
  deptGroups: [],
  queryDeptGroups: [],
  certificateTypeOpts: "身份证".split(","),
  nationOpts: '汉族,壮族,满族,回族,苗族,维吾尔族,土家族,彝族,蒙古族,藏族,布依族,侗族,瑶族,朝鲜族,白族,哈尼族,哈萨克族,黎族,傣族,畲族,傈僳族,仡佬族,东乡族,高山族,拉祜族,水族,佤族,纳西族,羌族,土族,仫佬族,锡伯族,柯尔克孜族,达斡尔族,景颇族,毛南族,撒拉族,布朗族,塔吉克族,阿昌族,普米族,鄂温克族,怒族,京族,基诺族,德昂族,保安族,俄罗斯族,裕固族,乌孜别克族,门巴族,鄂伦春族,独龙族,塔塔尔族,赫哲族,珞巴族'.split(","),

  isManager: false,
  phoneState: '',
  userInfo: null,
  mode: '',
  editData: null,
  craftPostList:[],
});

const { queryParams, form, rules } = toRefs(data);

//进场，离场
function handleEnter(row) {
  let ids = [row.id];
  if (row.useStatus == 0) {
    updateEnterState(ids, 1).then(d => {
      row.useStatus = 1;
    });
  } else {
    updateEnterState(ids, 0).then(d => {
      row.useStatus = 0;
    });
  }
}

//批量入场,批量离场
function handleBatchEnterState(state) {
  if (ids.value.length == 0) {
    proxy.$modal.msgWarning("请选择数据!!!");
    return;
  }
  updateEnterState(ids.value, state).then(d => {
    proProjectInfoSubdeptsUsersList.value.forEach(it => {
      if (ids.value.indexOf(it.id) >= 0) {
        it.useStatus = state;
      }
    });
  });
}

//图片上传
function doImageUpload(type) {  
  setTimeout(() => {
    let url='';
    form.value.identificationCard = form.value.certificatePhoto1 && form.value.certificatePhoto2 && form.value.faceImage ? "yes" : ''
    if(type==1){
      url=form.value.certificatePhoto1;
      if(url){
        url=location.origin+url;
        //url="http://62.234.3.186/statics/2025/01/19/4491f170cd1609142f9a6f097cbf681f_20250119000046A004.jpg"
        proxy.$http.get(`/system/tools/id/front?url=${url}`).then(d=>{
          form.value.userName=form.value.userName||d.data.name||'';
          form.value.certificateCode=form.value.certificateCode||d.data.cardId||'';
          form.value.address=form.value.address||d.data.address||'';
          let nation=d.data.nation||"";
          if(nation){
           let tmps= data.nationOpts.filter(it=>it.indexOf(nation)>=0);
           if(tmps.length>0){
            form.value.nation=form.value.nation||tmps[0]||'';
           }
          }        
          let sex=d.data.sex||'';
          if(sex){
            form.value.sex=form.value.sex||(sex=='男'?0:1);
          }
          let birthDay=d.data.birthday;
          if(birthDay && birthDay.length==8){
            birthDay=birthDay.substr(0,4)+"-"+birthDay.substr(4,2)+"-"+birthDay.substr(6);
            form.value.birthDay=form.value.birthDay||birthDay;
          }
          
        });
      }      
    }else if(type==2){
      url=form.value.certificatePhoto2;
      if(url){
        url=location.origin+url;
        //url="https://gss0.baidu.com/9fo3dSag_xI4khGko9WTAnF6hhy/zhidao/pic/item/a8014c086e061d95103a068779f40ad162d9ca14.jpg"
        proxy.$http.get(`/system/tools/id/back?url=${url}`).then(d=>{
          form.value.nativePlace=form.value.nativePlace||d.data.issuing||'';
        });
      } 
    }
  }, 800);
}

//查询手机号码
function queryPhone() {
  listUser({ phonenumber: form.value.userPhone }).then(d => {
    let userPhone = form.value.userPhone;
    if (d.rows.length > 0) {
      let user = d.rows[0];
      data.userInfo = user;
      data.phoneState = "edit";
      showEditUser(user);
    } else {
      data.userInfo = null;
      showEditUser({});
      data.phoneState = "add";
    }
    form.value.userPhone = userPhone;
  });

}
function tryToJson(str) {
  try {
    return JSON.parse(str);
  } catch {
    return {};
  }
}
/** 查询分包单位工人列表 */
function getList() {
  loading.value = true;
  queryParams.value.comId = userStore.currentComId;
  queryParams.value.projectId = userStore.currentPrjId;
  listProProjectInfoSubdeptsUsers(queryParams.value).then(response => {

    proProjectInfoSubdeptsUsersList.value = (response.rows || []).map(d => {
      d.info = tryToJson(d.userInfos || "{}")
      d.user = d.user || {};
      if (d.info.birthDay) {
        let birthDay = dayjs(d.info.birthDay).format("YYYY-MM-DD");
        d.info.birthDayStr = birthDay;
        d.info.age = dayjs(new Date()).diff(d.info.birthDay, 'year');
      }

      return d;
    });
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    projectId: null,//所属项目ID
    subDeptId: null,//所属单位ID
    subDeptName: null,//所属单位名称
    userName: null,//姓名
    userPhone: "",//联系电话
    certificateType: '',//证件号码
    certificateCode: '',//证件号码
    subDeptGroup: '',//班组ID
    groupName: '',//班组名称
    craftTypeName: '',//岗位
    craftType: '',//岗位编号
    craftPostName: '',//工种
    craftPost: '',//工种编号
    nation: '',//民族
    age: 20,//年龄
    sex: '',//性别
    educationalType: '',//文件程度
    birthDay: '',//出生日期
    nativePlace: '',//籍贯
    address: '',//家庭地址
    emergencyContact: '',//紧急联系人
    contactPhone: '',//紧急联系人电话
    bankName: '',//工资卡银行
    bankCardNo: '',//工资卡号
    bankOffice: '',//开户网点        
  };
  proxy.resetForm("proProjectInfoSubdeptsUsersRef");
  data.phoneState = "";
  data.userInfo = null;
}
//选择所属单位
function doSubDeptChange(type) {
  if (type == "query") {
    if (!queryParams.value.subDeptId) {
      data.queryDeptGroups = [];
      return;
    }
  } else {
    if (!form.value.subDeptId) {
      data.deptGroups = [];
      form.value.subDeptGroup = "";
      form.value.groupName = "";
      form.value.craftPostName = "";
      form.value.craftTypeName = "";
      form.value.craftType = "";
      form.value.craftPost = "";
      return;
    }
  }
  listProProjectInfoSubdeptsGroup({ subDeptId: type == "query" ? queryParams.value.subDeptId : form.value.subDeptId, pageNum: 1, pageSize: 100 }).then(d => {
    if (type == "query") {
      data.queryDeptGroups = d.rows || [];
    } else {
      data.deptGroups = d.rows || [];
      if (data.deptGroups.length > 0) {
        let dg = data.deptGroups[0];
        form.value.groupName = dg.groupName;
        form.value.craftTypeName = getCraftType(dg.craftType);
        form.value.craftPostName = getCraftPost(dg.craftPost).label;
        form.value.craftType = dg.craftType;
        form.value.craftPost = dg.craftPost
        data.isManager = !dg.craftPost
        setTimeout(() => {
          form.value.subDeptGroup = dg.id;
          doDeptGroupChange();
        }, 400);

      }
    }
  });
}

function doDeptGroupChange() {
  data.isManager = false
  if (!form.value.subDeptGroup) {
    form.value.groupName = "";
    form.value.subDeptGroup = "";
    form.value.craftPostName = "";
    form.value.craftTypeName = "";
    form.value.craftType = "";
    form.value.craftPost = "";
    return;
  }
  let tmps = data.deptGroups.filter(d => d.id == form.value.subDeptGroup);
  if (tmps.length > 0 ) {
    let dg = tmps[0];
    form.value.groupName = dg.groupName;
    form.value.craftTypeName = getCraftType(dg.craftType);
    form.value.craftPostName = getCraftPost(dg.craftPost);
    if(dg.craftType==3){
      let subDepts=data.subdepts.filter(d=>d.id==dg.subDeptId)
      let subDeptType=subDepts.length>0?subDepts[0].subDeptType||'':'';
      subDeptType=`,${subDeptType},`
      data.craftPostList=pro_craft_post.value.filter(d=>d.remark.indexOf(subDeptType)>=0 && d.elTagClass==3)
    }
    if(data.mode != 'edit'){
      form.value.craftPost = dg.craftPost
    }
    form.value.craftType = dg.craftType;
    data.isManager = !dg.craftPost;
  }
}

function getCraftType(id) {
  let tmps = pro_craft_type.value.filter(d => d.value == id);
  return tmps.length > 0 ? tmps[0].label : "";
}
function getCraftPost(id) {
  let tmps = pro_craft_post.value.filter(d => d.value == id);
  return tmps.length > 0 ? tmps[0].label : "";
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

function loadSubDepts(cb) {
  listProProjectInfoSubdepts({ projectId: userStore.currentPrjId, pageNum: 1, pageSize: 100 }).then(d => {
    data.subdepts = d.rows || [];
    if (data.subdepts.length > 0) {
      setTimeout(() => {
        let sd = data.subdepts[0];
        form.value.subDeptId = sd.id;
        doSubDeptChange();
        cb && cb();
      }, 400);
    } else {
      cb && cb();
    }

  });
}

/** 新增按钮操作 */
function handleAdd() {
  if (!userStore.currentPrjId) {
    proxy.$modal.msgWarning("请切换到项目数据！！！");
    return false;
  }
  open.value = true;
  title.value = "添加劳务人员信息";
  reset();
  loadSubDepts(() => {
    data.editData = null;
    data.mode = 'add';
    form.value.certificateType = "";
    form.value.projectId = userStore.currentPrjId;
    form.value.comId = userStore.currentComId;
    form.value.projectName = userStore.currentProName;
    form.value.nation = data.nationOpts[0];
    form.value.sex = "0";
  });
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  data.mode = 'edit'
  data.editData = row;
  open.value = true;
  title.value = "修改劳务人员信息";
  loadSubDepts(() => {
    getProProjectInfoSubdeptsUsers(_id).then(response => {
      let obj = JSON.parse(JSON.stringify(response.data));
      obj.info = tryToJson(obj.userInfos || "{}");
      obj.certificateType = obj.cardType;
      obj.certificateCode = obj.cardCode;
      obj.sex = obj.userSex;
      obj.nation = obj.info.nation;
      obj.birthDay = obj.info.birthDay;
      obj.nativePlace = obj.info.nativePlace;
      obj.address = obj.info.address;
      obj.emergencyContact = obj.info.emergencyContact;
      obj.contactPhone = obj.info.contactPhone;
      obj.bankName = obj.info.bankName;
      obj.bankCardNo = obj.info.bankCardNo;
      obj.bankOffice = obj.info.bankOffice;
      obj.certificatePhoto1 = obj.info.certificatePhoto1;
      obj.certificatePhoto2 = obj.info.certificatePhoto2;
      obj.faceImage = obj.userPicture;
      obj.educationalType = obj.degreeGrade
      form.value = obj;
      form.value.userId = obj.userId;
      form.value.projectId = row.projectId;
      form.value.projectName = row.projectName;
      //showEditUser(obj.user);
      data.phoneState = "edit";

      doImageUpload();

      //doDeptGroupChange();
      setTimeout(() => {
        doSubDeptChange();
        setTimeout(() => {
          form.value.craftPost = response.data.craftPost;
          console.log("++++++>",form.value.craftPost)
        }, 400)

      }, 400);
    });
  });
}

function showEditUser(user) {
  user = user || {};
  let info = tryToJson(user?.userInfos || "{}")
  if (info.birthDay) {
    let birthDay = dayjs(info.birthDay).format("YYYY-MM-DD");
    info.birthDayStr = birthDay;
    info.age = dayjs(new Date()).diff(info.birthDay, 'year');
  }
  form.value.userPhone = user.phonenumber
  form.value.userName = user.userName;
  form.value.certificateType = user.cardType;
  form.value.certificateCode = user.cardCode;
  form.value.faceImage = user.userPicture;
  form.value.certificatePhoto1 = user.cardImgPos;
  form.value.certificatePhoto2 = user.cardImgInv;

  form.value.nation = info.nation;
  form.value.sex = user.sex;
  form.value.educationalType = info.educationalType;
  form.value.birthDay = info.birthDay;
  form.value.nativePlace = info.nativePlace;
  form.value.address = info.address;
  form.value.emergencyContact = info.emergencyContact;
  form.value.contactPhone = info.contactPhone;
  form.value.bankName = info.bankName;
  form.value.bankCardNo = info.bankCardNo;
  form.value.bankOffice = info.bankOffice;

}
function imgUrl(url) {
  if (url.indexOf("http://") >= 0 || url.indexOf("https://") >= 0) {
    return url;
  }
  return location.origin + url;
}
/** 提交按钮 */
function submitForm() {
  proxy.$refs["proProjectInfoSubdeptsUsersRef"].validate(valid => {
    if (valid) {
      let depts = data.subdepts.filter(d => d.id == form.value.subDeptId);
      let groups = data.deptGroups.filter(d => d.id == form.value.subDeptGroup);
      let info = {
        nation: form.value.nation,
        birthDay: form.value.birthDay,
        nativePlace: form.value.nativePlace,
        address: form.value.address,
        emergencyContact: form.value.emergencyContact,
        contactPhone: form.value.contactPhone,
        bankName: form.value.bankName,
        bankCardNo: form.value.bankCardNo,
        bankOffice: form.value.bankOffice,
        certificatePhoto1: form.value.certificatePhoto1,
        certificatePhoto2: form.value.certificatePhoto2
      };
      let postData = {
        comId: form.value.comId,
        projectId: form.value.projectId,
        subDeptId: form.value.subDeptId,
        subDeptName: depts.length > 0 ? depts[0].subDeptName : '',
        subDeptGroup: form.value.subDeptGroup,
        subDeptGroupName: groups.length > 0 ? groups[0].groupName : '',
        userName: form.value.userName,
        cardType: form.value.certificateType,
        cardCode: form.value.certificateCode,
        userSex: form.value.sex,
        userPicture: form.value.faceImage,
        userPhone: form.value.userPhone,
        degreeGrade: form.value.educationalType,
        userInfos: JSON.stringify(info),
        craftType: form.value.craftType,
        craftPost: form.value.craftPost,
      };

      if (form.value.id != null) {
        postData.id = form.value.id;
        updateProProjectInfoSubdeptsUsers(postData).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addProProjectInfoSubdeptsUsers(postData).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除分包单位工人编号为"' + _ids + '"的数据项？').then(function () {
    return delProProjectInfoSubdeptsUsers(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => { });
}

/** 打开三级安全教育承诺书 */
function handleDownloadFile(row){
  proxy.$download.resource(row.eduFilePath);
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('manage/proProjectInfoSubdeptsUsers/export', {
    ...queryParams.value
  }, `proProjectInfoSubdeptsUsers_${new Date().getTime()}.xlsx`)
}
loadSubDepts();
getList();
</script>
<style lang="scss">
.pro-project-info-subdepts-users-index {
  .edit-drawer {
    .el-drawer__header {
      margin-bottom: 0px;
    }

    .el-form-item--default {
      margin-bottom: 16px;
    }

    .fi-certificate {
      .el-select {
        width: 120px;

        .el-input {
          width: 100%;
          margin-left: 0px;
        }
      }

      .el-input {
        width: calc(100% - 130px);
        margin-left: 10px;
      }
    }
  }

  .identification-card-1 {
    .el-upload--picture-card {
      width: 240px;
      background-image: url("../../../assets/images/card1.svg");
      background-repeat: no-repeat;
      background-position: center;
    }

    .el-upload__tip {
      display: none;
    }

    .el-upload-list--picture-card {
      .el-upload-list__item {
        width: 240px;
      }
    }
  }

  .div-header {
    text-align: center;
  }

  .identification-card-2 {
    .el-upload--picture-card {
      width: 240px;
      background-image: url("../../../assets/images/card2.svg");
      background-repeat: no-repeat;
      background-position: center;
      background-size: 60%;
    }

    .el-upload__tip {
      display: none;
    }

    .el-upload-list--picture-card {
      .el-upload-list__item {
        width: 240px;
      }
    }
  }

  .face-image {
    &>div {
      text-align: center;
    }

    .el-upload--picture-card {
      background-image: url("../../../assets/images/face.svg");
      background-repeat: no-repeat;
      background-position: center;
      background-size: 60%;
    }

    .el-upload__tip {
      display: none;
    }
  }
}
</style>