<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--部门数据-->
      <el-col :span="5" :xs="24">
        <div class="head-container">
          <el-input v-model="deptName" placeholder="请输入部门名称" clearable size="small" prefix-icon="el-icon-search"
            style="margin-bottom: 20px" />
        </div>
        <div class="head-container">
          <el-tree :data="deptOptions" :props="defaultProps" :expand-on-click-node="false"
            :filter-node-method="filterNode" ref="tree" node-key="id" default-expand-all highlight-current
            @node-click="handleNodeClick" />
        </div>
      </el-col>
      <!--用户数据-->
      <el-col :span="19" :xs="24">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"
          label-width="68px">
          <el-form-item label="姓名" prop="nickName">
            <el-input v-model="queryParams.nickName" placeholder="请输入姓名" clearable style="width: 140px"
              @keyup.enter.native="handleQuery" />
          </el-form-item>
          <el-form-item label="职称" prop="titles">
            <el-select v-model="queryParams.titles" clearable placeholder="请输入职称" style="width:100%;">
              <el-option v-for="dict in dict.type.sys_user_titles" :key="dict.value" :label="dict.label"
                :value="dict.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="职业资格" prop="certificates">
            <el-select v-model="queryParams.certificates" clearable placeholder="请输入职业资格" style="width:100%;">
              <el-option v-for="dict in dict.type.sys_user_certificates" :key="dict.value" :label="dict.label"
                :value="dict.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="学历" prop="degree">
            <el-select v-model="queryParams.degree" clearable placeholder="请输入学历" style="width:100%;">
              <el-option v-for="dict in dict.type.sys_user_degree" :key="dict.value" :label="dict.label"
                :value="dict.value" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @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="el-icon-plus" size="mini" @click="handleAdd"
              v-hasPermi="['system:user:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
              v-hasPermi="['system:user:edit']">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
              v-hasPermi="['system:user:remove']">删除</el-button>
          </el-col>
          <!-- <el-col :span="1.5">
          <el-button type="info" plain icon="el-icon-upload2" size="mini" @click="handleImport"
            v-hasPermi="['system:user:import']">导入</el-button>
        </el-col> -->
          <el-col :span="1.5">
            <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
              v-hasPermi="['system:user:export']">导出</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="text" plain size="mini" @click="lookOnTheJob()"
              v-hasPermi="['system:user:edit']">查看在岗员工</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="text" plain size="mini" @click="lookResign()"
              v-hasPermi="['system:user:edit']">查看离职人员</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="text" plain size="mini" @click="lookRetire()"
              v-hasPermi="['system:user:edit']">查看退休人员</el-button>
          </el-col>
          <el-col :span="1.5">
            <div style="text-align:right;font-size:14px;line-height:28px;">共{{ total }}条数据</div>
          </el-col>
          <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" border :data="userList" @selection-change="handleSelectionChange"
          @sort-change="handleSortChange">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="序号" width="50" align="center" prop="userId">
            <template slot-scope="scope">
              {{ scope.row.userId - 1 }}
            </template>
          </el-table-column>
          <!-- <el-table-column label="用户编号" align="center" key="userId" prop="userId" v-if="columns[0].visible" /> -->
          <el-table-column label="姓名" align="center" key="nickName" prop="nickName" v-if="columns[0].visible"
            :show-overflow-tooltip="true" />
          <el-table-column label="年龄" align="center" key="age" prop="age" v-if="columns[1].visible" sortable
            :sort-method="sortAge">
            <template slot-scope="scope">
              {{ String(getAgeByIdCard(scope.row.idCard)).slice(0,2) }}
            </template>
          </el-table-column>
          <el-table-column label="性别" align="center" key="sex" prop="sex" v-if="columns[2].visible"
            :show-overflow-tooltip="true" sortable>
            <template slot-scope="scope">
              {{ scope.row.sex == 0 ? '男' : '女' }}
            </template>
          </el-table-column>
          <el-table-column label="手机号码" align="center" key="phonenumber" prop="phonenumber" v-if="columns[3].visible"
            width="120" />
          <el-table-column label="部门" align="center" key="deptName" prop="dept.deptName" v-if="columns[4].visible"
            :show-overflow-tooltip="true" sortable />
          <el-table-column label="岗级" align="center" key="postLevel" v-if="columns[5].visible"
            :show-overflow-tooltip="true" sortable :sort-method="sortPostLevel">
            <template slot-scope="scope">
              {{ selectDictLabel(dict.type.sys_user_postlevel, scope.row.postLevel) +
                selectDictLabel(dict.type.sys_user_salarylevel, scope.row.salaryLevel) }}
            </template>
          </el-table-column>
          <el-table-column label="职务" align="center" key="postNames" prop="postNames" v-if="columns[17].visible"
            :show-overflow-tooltip="true"></el-table-column>
          <el-table-column label="职称" align="center" key="titles" prop="titles" v-if="columns[6].visible"
            :show-overflow-tooltip="true" sortable :sort-method="sortTitles">
            <template slot-scope="scope">
              {{ selectDictLabel(dict.type.sys_user_titles, scope.row.titles) }}
            </template>
          </el-table-column>
          <el-table-column label="职业资格" align="center" key="certificates" prop="certificates" v-if="columns[18].visible"
            :formatter="formatterCertificates" />
          <el-table-column label="最高学历毕业院校" align="center" key="graduateSchool" prop="graduateSchool"
            v-if="columns[10].visible" sortable="custom" />
          <el-table-column label="最高学历专业" align="center" key="major" prop="major" v-if="columns[11].visible" />
          <el-table-column label="最高学历" sortable align="center" key="degree" prop="degree" :formatter="formatterDegree"
            v-if="columns[12].visible" />
          <el-table-column label="初始学历毕业院校" align="center" key="initialSchool" prop="initialSchool"
            v-if="columns[21].visible" sortable="custom" />
          <el-table-column label="初始学历专业" align="center" key="initialMajor" prop="initialMajor" v-if="columns[20].visible" />
          <el-table-column label="初始学历" sortable align="center" key="initialDegree" prop="initialDegree" :formatter="formatterInitialDegree"
            v-if="columns[19].visible" />
          <el-table-column label="籍贯" align="center" key="nativePlace" prop="nativePlace" v-if="columns[13].visible" />
          <el-table-column label="政治面貌" align="center" key="politicalAffiliation"
            :formatter="formatterPoliticalAffiliation" prop="politicalAffiliation" v-if="columns[14].visible" />
          <el-table-column label="民族" align="center" key="ethnic" prop="ethnic" v-if="columns[15].visible" sortable />
          <el-table-column label="入职时间" sortable align="center" key="entryDate" prop="entryDate"
            v-if="columns[16].visible" :show-overflow-tooltip="true">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.entryDate, '{y}-{m}-{d}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="合同签订" align="center" key="contractSign" prop="contractSign" v-if="columns[7].visible"
            :show-overflow-tooltip="true" sortable :sort-method="sortContractSign">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.contractSign, '{y}-{m}-{d}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="合同期满" align="center" key="contractExpire" prop="contractExpire"
            v-if="columns[8].visible" :show-overflow-tooltip="true" sortable :sort-method="sortContractExpire">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.contractExpire, '{y}-{m}-{d}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="状态" align="center" key="status" v-if="columns[9].visible" sortable
            :sort-method="sortStatus">
            <template slot-scope="scope">
              <el-tag type="success" v-if="scope.row.status == 0">在职</el-tag>
              <el-tag type="danger" v-if="scope.row.status == 1">离职</el-tag>
              <el-tag type="warning" v-if="scope.row.status == 2">退休</el-tag>
              <el-tag type="primary" v-if="scope.row.status == 3">试用</el-tag>
              <el-tag type="info" v-if="scope.row.status == 4">返聘</el-tag>
            </template>
          </el-table-column>

          <el-table-column label="备注" align="center" key="remark" prop="remark" v-if="columns[22].visible"
            :show-overflow-tooltip="true"></el-table-column>
          <el-table-column label="操作" align="center" width="160" class-name="small-padding fixed-width">
            <template slot-scope="scope" v-if="scope.row.userId !== 1">
              <el-button size="mini" type="text" icon="el-icon-view" v-hasPermi="['system:user:query']"
                @click="handleView(scope.row)">详情</el-button>
              <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
                v-hasPermi="['system:user:edit']">修改</el-button>
              <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                v-hasPermi="['system:user:remove']">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
          @pagination="getList" /> -->
      </el-col>
    </el-row>
    <!-- 添加或修改用户配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="900px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="姓名" prop="nickName">
              <el-input v-model="form.nickName" placeholder="请输入姓名" maxlength="30" />
            </el-form-item>
            <el-form-item v-if="form.userId == undefined" label="登录账号" prop="userName">
              <el-input v-model="form.userName" placeholder="请输入登录账号" maxlength="30" />
            </el-form-item>
            <el-form-item label="用户性别">
              <el-radio-group v-model="form.sex">
                <el-radio v-for="dict in dict.type.sys_user_sex" :key="dict.value" :label="dict.value">
                  {{ dict.label }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="状态">
              <el-radio-group v-model="form.status">
                <el-radio v-for="dict in dict.type.sys_post_status" :key="dict.value" :label="dict.value">
                  {{ dict.label }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="年龄" prop="age" v-if="form.userId != undefined">
              {{ String(form.age).slice(0,2) + '岁' }}
            </el-form-item>
            <el-form-item label="手机号码" prop="phonenumber">
              <el-input v-model="form.phonenumber" placeholder="请输入手机号码" maxlength="11" />
            </el-form-item>
            <el-form-item label="身份证" prop="idCard">
              <el-input v-model="form.idCard" placeholder="请输入身份证号码" maxlength="18" />
            </el-form-item>
            <el-form-item label="出生年月" prop="birthday">
              <el-date-picker v-model="form.birthday" type="month" placeholder="请输入出生年月" style="width:100%;"
                value-format="yyyy-MM" />
            </el-form-item>
            <el-form-item label="籍贯" prop="nativePlace">
              <el-input v-model="form.nativePlace" placeholder="请输入籍贯" />
            </el-form-item>
            <el-form-item label="民族" prop="ethnic">
              <el-input v-model="form.ethnic" placeholder="请输入民族" />
            </el-form-item>
            <el-form-item label="初始学历专业" prop="initialDegree">
              <el-col :span="8">
                <el-select v-model="form.initialDegree" placeholder="请选择" style="width:100%;" clearable>
                  <el-option v-for="dict in dict.type.sys_user_degree" :key="dict.value" :label="dict.label"
                  :value="dict.value" />
                </el-select>
              </el-col>
              <el-col :span="16">
                <el-input v-model="form.initialMajor" placeholder="请输入专业" />
              </el-col>
            </el-form-item>
            <el-form-item label="初始学历毕业学校" prop="initialSchool">
              <el-input v-model="form.initialSchool" placeholder="请输入初始学历毕业学校" />
            </el-form-item>
            <el-form-item label="最高学历专业" prop="degree">
              <el-col :span="8">
                <el-select v-model="form.degree" placeholder="请选择" style="width:100%;" clearable>
                  <el-option v-for="dict in dict.type.sys_user_degree" :key="dict.value" :label="dict.label"
                  :value="dict.value" />
                </el-select>
              </el-col>
              <el-col :span="16">
                <el-input v-model="form.major" placeholder="请输入专业" />
              </el-col>
            </el-form-item>
            <el-form-item label="最高学历毕业学校" prop="graduateSchool">
              <el-input v-model="form.graduateSchool" placeholder="请输入最高学历毕业学校" />
            </el-form-item>
            <el-form-item label="家庭住址" prop="homePlace">
              <el-input type="textarea" v-model="form.homePlace" placeholder="请输入家庭住址" />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="归属部门" prop="deptId" style="width:100%;">
              <treeselect v-model="form.deptId" :options="deptOptions" :show-count="true" placeholder="请选择归属部门" />
            </el-form-item>
            <el-form-item label="入职年月" prop="entryDate">
              <el-date-picker v-model="form.entryDate" type="date" placeholder="请输入入职年月" style="width:100%;"
                value-format="yyyy-MM-dd" />
            </el-form-item>
            <el-form-item label="合同签订" prop="contractSign">
              <el-date-picker v-model="form.contractSign" type="date" placeholder="请输入合同签订" style="width:100%;"
                value-format="yyyy-MM-dd" />
            </el-form-item>
            <el-form-item label="合同期满" prop="contractExpire">
              <el-date-picker v-model="form.contractExpire" type="date" placeholder="请输入合同期满" style="width:100%;"
                value-format="yyyy-MM-dd" />
            </el-form-item>
            <el-form-item label="政治面貌" prop="politicalAffiliation">
              <el-select v-model="form.politicalAffiliation" multiple clearable placeholder="请选择政治面貌"
                style="width:100%;">
                <el-option v-for="dict in dict.type.sys_user_political" :key="dict.value" :label="dict.label"
                  :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="技术职称">
              <el-select v-model="form.titles" clearable placeholder="请输入技术职称" style="width:100%;">
                <el-option v-for="dict in dict.type.sys_user_titles" :key="dict.value" :label="dict.label"
                  :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="职称专业" prop="titleProfession">
              <el-input type="textarea" v-model="form.titleProfession" placeholder="职称专业" />
            </el-form-item>
            <el-form-item label="职业资格">
              <el-select v-model="form.certificates" clearable multiple placeholder="请输入职业资格" style="width:100%;">
                <el-option v-for="dict in dict.type.sys_user_certificates" :key="dict.value" :label="dict.label"
                  :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="项目经理">
              <el-select v-model="form.pmLevel" clearable placeholder="请输入项目经理等级" style="width:100%;">
                <el-option v-for="dict in dict.type.sys_user_pmlevel" :key="dict.value" :label="dict.label"
                  :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="工程师等级">
              <el-select v-model="form.engineerLevel" clearable placeholder="请输入工程师等级" style="width:100%;">
                <el-option v-for="dict in dict.type.sys_user_engineerlevel" :key="dict.value" :label="dict.label"
                  :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="技工等级">
              <el-select v-model="form.operatorLevel" clearable placeholder="请输入技工等级" style="width:100%;">
                <el-option v-for="dict in dict.type.sys_user_operatorlevel" :key="dict.value" :label="dict.label"
                  :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="职务">
              <el-select v-model="form.postIds" multiple placeholder="请选择职务" style="width:100%;">
                <el-option v-for="item in postOptions" :key="item.postId" :label="item.postName" :value="item.postId"
                  :disabled="item.status == 1"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="岗级" prop="postlevel">
              <el-col :span="12">
                <el-select v-model="form.postLevel" placeholder="请选择" style="width:100%;" clearable>
                  <el-option v-for="dict in dict.type.sys_user_postlevel" :key="dict.value" :label="dict.label"
                    :value="dict.value" />
                </el-select>
              </el-col>
              <el-col :span="12">
                <el-select v-model="form.salaryLevel" placeholder="请选择" style="width:100%;" clearable>
                  <el-option v-for="dict in dict.type.sys_user_salarylevel" :key="dict.value" :label="dict.label"
                    :value="dict.value" />
                </el-select>
              </el-col>
            </el-form-item>            
            <el-form-item label="紧急联系人" prop="contact">
              <el-input v-model="form.contact" placeholder="请输入紧急联系人" />
            </el-form-item>
            <el-form-item label="紧急联系电话" prop="telephone">
              <el-input v-model="form.telephone" placeholder="请输入紧急联系电话" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注">
              <el-input v-model="form.remark" type="textarea" placeholder="若员工属生产部门，请输入（检查员、内业、外业）"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <div slot="footer" class="text-center">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 用户导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload ref="upload" :limit="1" accept=".xlsx, .xls" :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport" :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false" drag>
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <div class="el-upload__tip" slot="tip">
            <el-checkbox v-model="upload.updateSupport" /> 是否更新已经存在的用户数据
          </div>
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;"
            @click="importTemplate">下载模板</el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listUser, getUser, delUser, addUser, updateUser, resetUserPwd, changeUserStatus, deptTreeSelectNew } from "@/api/system/user";
import { getToken } from "@/utils/auth";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "People",
  dicts: ['sys_post_status', 'sys_user_sex', 'sys_user_titles', 'sys_user_certificates', 'sys_user_pmlevel', 'sys_user_engineerlevel', 'sys_user_operatorlevel', 'sys_user_postlevel', 'sys_user_salarylevel', 'sys_user_political', 'sys_user_degree'],
  components: { Treeselect },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 用户表格数据
      userList: null,
      // 弹出层标题
      title: "",
      // 部门树选项
      deptOptions: undefined,
      // 是否显示弹出层
      open: false,
      // 部门名称
      deptName: undefined,
      // 默认密码
      initPassword: undefined,
      // 日期范围
      dateRange: [],
      // 岗位选项
      postOptions: [],
      // 角色选项
      roleOptions: [],
      // 更新原因选项
      updateReasonOptions: [
        { value: '0', label: '误录修改' },
        { value: '1', label: '正常调整' }
      ],
      // 表单参数
      form: {},
      pm: false,
      defaultProps: {
        children: "children",
        label: "label"
      },
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/system/user/importData"
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 300,
        userName: undefined,
        phonenumber: undefined,
        status: undefined,
        deptId: undefined
      },
      // 列信息
      columns: [
        { key: 0, label: `姓名`, visible: true },
        { key: 1, label: `年龄`, visible: true },
        { key: 2, label: `性别`, visible: true },
        { key: 3, label: `手机号码`, visible: true },
        { key: 4, label: `部门`, visible: true },
        { key: 5, label: `岗级`, visible: true },
        { key: 6, label: `职称`, visible: true },
        { key: 7, label: `合同签订`, visible: true },
        { key: 8, label: `合同期满`, visible: true },
        { key: 9, label: `状态`, visible: true },
        { key: 10, label: `最高学历毕业院校`, visible: false },
        { key: 11, label: `最高学历专业`, visible: false },
        { key: 12, label: `最高学历`, visible: false },
        { key: 13, label: `籍贯`, visible: false },
        { key: 14, label: `政治面貌`, visible: false },
        { key: 15, label: `民族`, visible: false },
        { key: 16, label: `入职时间`, visible: true },
        { key: 17, label: `职务`, visible: false },
        { key: 18, label: `职业资格`, visible: false },
        { key: 19, label: `初始学历`, visible: false },
        { key: 20, label: `初始学历专业`, visible: false },
        { key: 21, label: `初始学历毕业院校`, visible: false },
        { key: 22, label: `备注`, visible: false },
      ],
      // 表单校验
      rules: {
        userName: [
          { required: true, message: "用户名称不能为空", trigger: "blur" },
          { min: 2, max: 20, message: '用户名称长度必须介于 2 和 20 之间', trigger: 'blur' }
        ],
        nickName: [
          { required: true, message: "用户昵称不能为空", trigger: "blur" }
        ],
        password: [
          { required: true, message: "用户密码不能为空", trigger: "blur" },
          { min: 5, max: 20, message: '用户密码长度必须介于 5 和 20 之间', trigger: 'blur' }
        ],
        email: [
          {
            type: "email",
            message: "请输入正确的邮箱地址",
            trigger: ["blur", "change"]
          }
        ],
        phonenumber: [
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: "请输入正确的手机号码",
            trigger: "blur"
          }
        ]
      },
      certificates: '',
      postSalary: '',
      postData: ''
    };
  },
  watch: {
    // 根据名称筛选部门树
    deptName(val) {
      this.$refs.tree.filter(val);
    }
  },
  created() {
    this.getList();
    this.getDeptTree();
    this.getConfigKey("sys.user.initPassword").then(response => {
      this.initPassword = response.msg;
    });
  },
  methods: {
    /** 查询用户列表 */
    getList() {
      this.loading = true;
      listUser(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
        this.userList = response.rows;
        this.total = response.total;
        if (this.queryParams.status != 1 && this.queryParams.status != 2) {
          this.userList = this.userList.filter(user =>
            user.status != '1' && user.status != '2'
          )
          this.total = this.userList.length;
        }
        this.loading = false;
      }
      );
    },
    /** 查询部门下拉树结构 */
    getDeptTree() {
      deptTreeSelectNew().then(response => {
        this.deptOptions = response.data;
      });
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.deptId = data.id;
      this.handleQuery();
    },
    // 用户状态修改
    handleStatusChange(row) {
      let text = row.status === "0" ? "启用" : "停用";
      this.$modal.confirm('确认要"' + text + '""' + row.userName + '"用户吗？').then(function () {
        return changeUserStatus(row.userId, row.status);
      }).then(() => {
        this.$modal.msgSuccess(text + "成功");
      }).catch(function () {
        row.status = row.status === "0" ? "1" : "0";
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        userId: undefined,
        deptId: undefined,
        userName: undefined,
        nickName: undefined,
        password: undefined,
        phonenumber: undefined,
        sex: undefined,
        titles: undefined,
        status: "0",
        remark: undefined,
        roleIds: [],
        idCard: undefined,
        nativePlace: undefined,
        ethnic: undefined,
        graduateSchool: undefined,
        major: undefined,
        degree: undefined,
        initialSchool: undefined,
        initialMajor: undefined,
        initialDegree: undefined,
        homePlace: undefined,
        entryDate: undefined,
        contractSign: undefined,
        contractExpire: undefined,
        birthday: undefined,
        politicalAffiliation: [],
        titles: undefined,
        certificates: [],
        pmLevel: undefined,
        engineerLevel: undefined,
        operatorLevel: undefined,
        postIds: [],
        postLevel: undefined,
        salaryLevel: undefined,
        titleProfession: undefined,
        contact: null,
        telephone: null
      };
      // this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.queryParams.deptId = undefined;
      this.$refs.tree.setCurrentKey(null);
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.userId);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    // 更多操作触发
    handleCommand(command, row) {
      switch (command) {
        case "handleResetPwd":
          this.handleResetPwd(row);
          break;
        case "handleAuthRole":
          this.handleAuthRole(row);
          break;
        default:
          break;
      }
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加用户";
    },
    // 查看人员详情按钮
    handleView(row) {
      this.formatCrtificates(this.dict.type.sys_user_certificates, row.certificates)
      this.$router.push({
        path: '/staff/info',
        query: {
          userId: row.userId,
          nickName: row.nickName,
          postIds: this.form.postIds,
          // certificates: this.certificates,
          // postSalary: this.postSalary,
        }
      })
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const userId = row.userId || this.ids;
      getUser(userId).then(response => {
        this.form = response.data;
        if (this.form.politicalAffiliation) {
          this.form.politicalAffiliation = this.form.politicalAffiliation.split(',')
        }
        this.form.birthday = this.getBirthdayByIdCard(this.form.idCard);
        this.form.age = this.getAgeByIdCard(this.form.idCard);
        this.postOptions = response.posts;
        this.roleOptions = response.roles;
        this.$set(this.form, "postIds", response.postIds);
        this.$set(this.form, "roleIds", response.roleIds);
        if (this.form.certificates != "" && this.form.certificates != undefined && this.form.certificates != null) {
          let certificateList = [];
          for (let i = 0; i < this.form.certificates.split(",").length; i++)
            certificateList[i] = this.form.certificates.split(",")[i]
          this.$set(this.form, "certificates", certificateList);
        }
        this.open = true;
        this.title = "修改用户";
        this.form.password = "";
      });
    },
    lookOnTheJob() {
      this.queryParams.status = ''
      this.getList();
    },
    lookResign() {
      this.queryParams.status = 1
      this.getList();
    },
    lookRetire() {
      this.queryParams.status = 2
      this.getList();
    },
    /** 重置密码按钮操作 */
    handleResetPwd(row) {
      this.$prompt('请输入"' + row.userName + '"的新密码', "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        closeOnClickModal: false,
        inputPattern: /^.{5,20}$/,
        inputErrorMessage: "用户密码长度必须介于 5 和 20 之间"
      }).then(({ value }) => {
        resetUserPwd(row.userId, value).then(response => {
          this.$modal.msgSuccess("修改成功，新密码是：" + value);
        });
      }).catch(() => { });
    },
    /** 分配角色操作 */
    handleAuthRole: function (row) {
      const userId = row.userId;
      this.$router.push("/system/user-auth/role/" + userId);
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.userId != undefined) {
            // if (this.form.certificates != "" && this.form.certificates != undefined && this.form.certificates != null)
            //   this.form.certificates = this.form.certificates.join(',')
            // else
            //   this.form.certificates = '';
            this.form.certificates = this.formatArrayToString(this.form.certificates, ',') == '' ? '' : this.formatArrayToString(this.form.certificates, ',');
            this.form.politicalAffiliation = this.formatArrayToString(this.form.politicalAffiliation, ',') ? this.formatArrayToString(this.form.politicalAffiliation, ',') : '';
            updateUser(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            this.form.certificates = this.formatArrayToString(this.form.certificates, ',') == '' ? '' : this.formatArrayToString(this.form.certificates, ',');
            this.form.politicalAffiliation = this.formatArrayToString(this.form.politicalAffiliation, ',') ? this.formatArrayToString(this.form.politicalAffiliation, ',') : '';
            addUser(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const userIds = row.userId || this.ids;
      this.$modal.confirm('是否确认删除用户编号为"' + userIds + '"的数据项？').then(function () {
        return delUser(userIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/user/export', {
        ...this.queryParams
      }, `user_${new Date().getTime()}.xlsx`)
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "用户导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download('system/user/importTemplate', {
      }, `user_template_${new Date().getTime()}.xlsx`)
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    formatCrtificates(arr, val) {
      if (val != null && val != undefined && val != "") {
        let valArr = val.split(',');
        let outCrtificates = []
        for (let i of valArr) {
          outCrtificates.push(arr[i].label)
        }
        this.certificates = outCrtificates.join(' / ')
        return outCrtificates.join(' / ')
      }
    },

    getBirthdayByIdCard(idCard) {
      if (idCard) {
        // 使用 substring() 方法和 split() 方法提取出生年月日信息
        const birthday = [idCard.substr(6, 4), idCard.substr(10, 2), idCard.substr(12, 2)].join('-')
        // 使用 Date 对象的 toISOString() 方法将出生年月日信息转换为日期格式
        const date = new Date(birthday);
        const formattedDate = this.parseTime(date, '{y}-{m}-{d}')
        return formattedDate;
      } else {
        return null
      }
    },
    getAgeByIdCard(idCard) {
      const birthStr = idCard.substring(6, 14);
      const birthYear = parseInt(birthStr.substring(0, 4), 10);
      const birthMonth = parseInt(birthStr.substring(4, 6), 10) - 1; // 月份从0开始
      const birthDay = parseInt(birthStr.substring(6, 8), 10);
      // 创建日期对象
      const birthDate = new Date(birthYear, birthMonth, birthDay);
      const now = new Date();
      // 基础年龄计算
      let age = now.getFullYear() - birthDate.getFullYear();
      // 判断是否已过生日
      const monthDiff = now.getMonth() - birthDate.getMonth();
      if (monthDiff < 0 || (monthDiff === 0 && now.getDate() < birthDate.getDate())) {
        age--;
      }
      // 计算上次生日日期
      let lastBirthday = new Date(now.getFullYear(), birthDate.getMonth(), birthDate.getDate());
      if (now < lastBirthday) {
        lastBirthday.setFullYear(lastBirthday.getFullYear() - 1);
      }
      // 计算时间比例
      const nextBirthday = new Date(lastBirthday.getFullYear() + 1, lastBirthday.getMonth(), lastBirthday.getDate());
      const daysInYear = (nextBirthday - lastBirthday) / (1000 * 60 * 60 * 24);
      const daysPassed = (now - lastBirthday) / (1000 * 60 * 60 * 24);
      return Number((age + (daysPassed / daysInYear)).toFixed(4));
    },
    formatArrayToString(str, splitStr) {
      let newStr = "";
      if (str) {
        newStr = str.join(splitStr)
      }
      return newStr
    },
    handleSortChange({ prop, order }) {
      if (prop == 'graduateSchool') {
        // 自定义排序  
        this.userList.sort((a, b) => {
          let valueA = a[prop];
          let valueB = b[prop];
          // 检查值是否为字符串，如果不是，则将其视为空字符串（或根据需要处理）  
          if (typeof valueA !== 'string') valueA = '';
          if (typeof valueB !== 'string') valueB = '';

          if (order === 'ascending') {
            return valueA.localeCompare(valueB, 'zh-Hans-CN', { sensitivity: 'base' });
          } else if (order === 'descending') {
            return valueB.localeCompare(valueA, 'zh-Hans-CN', { sensitivity: 'base' });
          }
          return 0; // 如果没有指定排序顺序，则不改变数组顺序  
        });
      }
    },
    sortAge(a, b) {
      return this.getAgeByIdCard(a.idCard) - this.getAgeByIdCard(b.idCard);
    },
    sortPostLevel(a, b) {
      // 安全地解析postLevel，如果无法解析，则视为Infinity  
      let aPostLevel = parseInt(a.postLevel, 10);
      if (isNaN(aPostLevel)) {
        aPostLevel = Infinity; // 无法解析时视为无穷大  
      }
      let bPostLevel = parseInt(b.postLevel, 10);
      if (isNaN(bPostLevel)) {
        bPostLevel = Infinity; // 同上  
      }
      // 首先比较postLevel  
      if (aPostLevel !== bPostLevel) {
        return aPostLevel - bPostLevel; // 注意：这里直接返回差值，但由于Infinity的特殊性，它会按预期工作  
      }
      // 如果postLevel相等，则比较salaryLevel（同样需要安全解析）  
      let aSalaryLevel = parseInt(a.salaryLevel, 10) || 0; // 如果无法解析，则视为0  
      let bSalaryLevel = parseInt(b.salaryLevel, 10) || 0; // 同上  
      // 返回salaryLevel的差值  
      return aSalaryLevel - bSalaryLevel;
    },
    sortTitles(a, b) {
      let res = Number(b.titles) - Number(a.titles)
      return res
    },
    sortStatus(a, b) {
      let res = Number(a.status) - Number(b.status)
      return res
    },
    sortContractSign(a, b) {
      a = a.contractSign;
      b = b.contractSign;
      if (!a && b) return 1; // 如果a为空且b不为空，则a排在b前面  
      if (a && !b) return -1; // 如果a不为空且b为空，则b排在a前面  
      if (!a && !b) return 0; // 如果a和b都为空，则它们相等，排序位置不变  
      // 将字符串转换为日期对象进行比较  
      const dateA = new Date(a);
      const dateB = new Date(b);
      // 如果日期有效，则比较日期；如果无效，则将它们视为大于有效日期  
      if (isNaN(dateA.getTime())) return 1; // a不是有效日期，则b（假设为有效日期）应该排在a前面  
      if (isNaN(dateB.getTime())) return -1; // b不是有效日期，则a（假设为有效日期）应该排在b前面  
      // 比较两个日期  
      return dateA - dateB;
    },
    sortContractExpire(a, b) {
      a = a.contractExpire;
      b = b.contractExpire;
      if (!a && b) return -1; // 如果a为空且b不为空，则a排在b前面  
      if (a && !b) return 1; // 如果a不为空且b为空，则b排在a前面  
      if (!a && !b) return 0; // 如果a和b都为空，则它们相等，排序位置不变  
      // 将字符串转换为日期对象进行比较  
      const dateA = new Date(a);
      const dateB = new Date(b);
      // 如果日期有效，则比较日期；如果无效，则将它们视为大于有效日期  
      if (isNaN(dateA.getTime())) return 1; // a不是有效日期，则b（假设为有效日期）应该排在a前面  
      if (isNaN(dateB.getTime())) return -1; // b不是有效日期，则a（假设为有效日期）应该排在b前面  
      // 比较两个日期  
      return dateA - dateB;
    },
    sortGraduateSchool(a, b) {

    },
    formatterDegree(row) {
      let v = this.selectDictLabel(this.dict.type.sys_user_degree, row.degree)
      return v
    },
    formatterInitialDegree(row){
      let v = this.selectDictLabel(this.dict.type.sys_user_degree, row.initialDegree)
      return v
    },
    formatterPoliticalAffiliation(row) {
      let v = this.selectDictLabels(this.dict.type.sys_user_political, row.politicalAffiliation, ',')
      return v
    },
    formatterCertificates(row) {
      let v = this.selectDictLabels(this.dict.type.sys_user_certificates, row.certificates, ',')
      return v
    },
    async getPostByUser(row) {
      const userId = row.userId || this.ids;
      let resData = await getUser(userId);
      let postArr = [];
      for (let post of resData.posts) {
        for (let postid of resData.postIds) {
          if (postid == post.postId) {
            postArr.push(post.postName)
          }
        }
      }
      let postStr = postArr.join('/');
      this.$set(row, 'postName', postStr)

    }
  }
};
</script>