<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, idx) 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.user.userPicture" style="height:80px;" :preview-teleported="true" :preview-src-list="[scope.row.user.userPicture]"></el-image>
        </template>
      </el-table-column>
      <el-table-column label="姓名" align="center" prop="user.userName" />
      <el-table-column label="身份证" align="center" prop="user.cardCode" />
      <el-table-column label="性别" align="center" prop="user.sex" width="80" />
      <el-table-column label="民族" align="center" prop="info.nation" width="80" />
      <el-table-column label="年龄" align="center" prop="info.age" 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" prop="enterState">
        <template #default="scope">
          <span v-if="scope.row.enterState==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']">删除</el-button>
          <el-button link type="primary" icon="Delete" @click="handleEnter(scope.row)" v-if="scope.row.enterState==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;">
        <div style="width: 50%;">
          <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'" style="margin-left:10px;"
              @click="queryPhone">查询</el-button>
          </el-form-item>
        </div>
        <el-row v-if="data.phoneState">
          <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, idx) in data.subdepts" :key="it.id" :label="it.subDeptName" :value="it.id" />
              </el-select>
            </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>

          <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 pro_craft_post.filter(d => d.remark == '3')" :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="(it, idx) in data.sexOpts" :key="idx" :label="it" :value="it">{{ it }}</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" />
              </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-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 } = proxy.useDict('sys_use_status', 'pro_craft_type', 'sys_is_del', 'pro_craft_post', 'certificate_type', 'educational_type');

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(","),
  sexOpts: "男,女".split(","),
  isManager: false,
  phoneState: '',
  userInfo: null,
  mode: '',
  editData:null,
});

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

//进场，离场
function handleEnter(row){
  let ids=[row.id];
  if(row.enterState==0){
    updateEnterState(ids,1).then(d=>{
      row.enterState=1;
    });
  }else{
    updateEnterState(ids,0).then(d=>{
      row.enterState=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.enterState=state;
      }
    });
  });
}

//图片上传
function doImageUpload() {
  setTimeout(() => {
    form.value.identificationCard = form.value.certificatePhoto1 && form.value.certificatePhoto2 && form.value.faceImage ? "yes" : ''
  }, 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;
  listProProjectInfoSubdeptsUsers(queryParams.value).then(response => {
    proProjectInfoSubdeptsUsersList.value = (response.rows || []).map(d => {
      d.info = tryToJson(d.user?.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.subDeptGroup = dg.id;
        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

      }
    }
  });
}

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);
    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.currentProId, pageNum: 1, pageSize: 100 }).then(d => {
    data.subdepts = d.rows || [];
    if (data.subdepts.length > 0) {
      let sd = data.subdepts[0];
      form.value.subDeptId = "" + sd.id;
      doSubDeptChange();
    }
    cb && cb();
  });
}

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

/** 修改按钮操作 */
function handleUpdate(row) {  
  reset();
  const _id = row.id || ids.value
  data.mode = 'edit'
  data.editData=row;
  getProProjectInfoSubdeptsUsers(_id).then(response => {
    let obj = JSON.parse(JSON.stringify(response.data));
    obj.info = tryToJson(obj.user?.userInfos || "{}")
    obj.user = obj.user || {};

    form.value = obj;
    form.value.userId = obj.userId;

    form.value.projectId = row.projectId;
    form.value.projectName = row.projectName;
    showEditUser(obj.user);
    data.phoneState = "edit";
    open.value = true;
    title.value = "修改劳务人员信息";
    doImageUpload();
    doDeptGroupChange();
    setTimeout(() => {
      form.value.craftPost = response.data.craftPost;
    }, 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 info=form.value.info;
      info.nation=form.value.nation;
      info.educationalType=form.value.educationalType;
      info.birthDay=form.value.birthDay;
      info.nativePlace=form.value.nativePlace;
      info.address=form.value.address;
      info.emergencyContact=form.value.emergencyContact;
      info.emergencyContact= form.value.emergencyContact;
      info.contactPhone=form.value.contactPhone;
      info.bankName=form.value.bankName;
      info.bankCardNo= form.value.bankCardNo;
      info.bankOffice= form.value.bankOffice;
      form.value.subDeptName = depts.length > 0 ? depts[0].subDeptName : '';
      form.value.comId = depts.length > 0 ? depts[0].comId : '';
      let groups = data.deptGroups.filter(d => d.id == form.value.subDeptGroup);
      form.value.subDeptGroupName = groups.length > 0 ? groups[0].groupName : '';
      form.value.userId = data.userInfo ? data.userInfo.userId : '';
      form.value.user = {
        userId: data.userInfo ? data.userInfo.userId : '',
        comId: form.value.comId,
        deptId: form.value.projectId,
        nickName: form.value.userName,
        userName: form.value.userName,
        userType: 99,
        cardType: form.value.certificateType,
        cardCode: form.value.certificateCode,
        userPicture: imgUrl(form.value.faceImage),
        cardImgPos: form.value.certificatePhoto1,
        cardImgInv: form.value.certificatePhoto2,
        userInfos: JSON.stringify(info),
        phonenumber: form.value.userPhone,
        sex: form.value.sex,
        avatar: form.value.faceImage
      };
      if (form.value.id != null) {
        form.value.user.userId = form.value.userId;
        updateProProjectInfoSubdeptsUsers(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addProProjectInfoSubdeptsUsers(form.value).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 handleExport() {
  proxy.download('manage/proProjectInfoSubdeptsUsers/export', {
    ...queryParams.value
  }, `proProjectInfoSubdeptsUsers_${new Date().getTime()}.xlsx`)
}

getList();
loadSubDepts();  
</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>