<template>
  <div class="app-container">
    <doc-alert title="员工体系" url="https://doc.iocoder.cn/user-center/"/>
    <doc-alert title="三方登陆" url="https://doc.iocoder.cn/social-user/"/>
    <doc-alert title="Excel 导入导出" url="https://doc.iocoder.cn/excel-import-and-export/"/>
    <!-- 搜索工作栏 -->
    <el-row :gutter="20">
      <!--部门数据-->
      <!--      <el-col :span="4" :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" default-expand-all highlight-current @node-click="handleNodeClick"/>-->
      <!--        </div>-->
      <!--      </el-col>-->
      <!--员工数据-->
      <el-col>
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"
                 label-width="68px">
          <el-form-item label="员工账号" prop="username">
            <el-input v-model="queryParams.nickname" placeholder="请输入员工账号" clearable style="width: 240px"
                      @keyup.enter.native="handleQuery"/>
          </el-form-item>
          <el-form-item label="手机号码" prop="mobile">
            <el-input v-model="queryParams.mobile" placeholder="请输入手机号码" clearable style="width: 240px"
                      @keyup.enter.native="handleQuery"/>
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-select v-model="queryParams.status" placeholder="员工状态" clearable style="width: 240px">
              <el-option v-for="dict in statusDictDatas" :key="parseInt(dict.value)" :label="dict.label"
                         :value="parseInt(dict.value)"/>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
            <el-button icon="el-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="el-icon-plus" size="mini" @click="handleAdd">新增
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="chooseUser">选择员工
            </el-button>
          </el-col>
<!--          <el-col :span="1.5">-->
<!--            <el-button type="info" icon="el-icon-upload2" size="mini" @click="handleImport">导入-->
<!--            </el-button>-->
<!--          </el-col>-->
<!--          <el-col :span="1.5">-->
<!--            <el-button type="warning" icon="el-icon-download" size="mini" @click="handleExport"-->
<!--                       :loading="exportLoading">导出-->
<!--            </el-button>-->
<!--          </el-col>-->
          <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="userList">
          <el-table-column label="员工编号" align="center" key="id" prop="id" v-if="columns[0].visible"/>
          <el-table-column label="员工账号" align="center" key="username" prop="username" v-if="columns[1].visible"
                           :show-overflow-tooltip="true"/>
          <el-table-column label="员工昵称" align="center" key="nickname" prop="nickname" v-if="columns[2].visible"
                           :show-overflow-tooltip="true"/>
          <el-table-column label="部门" align="center" key="deptName" prop="dept.name" v-if="columns[3].visible"
                           :show-overflow-tooltip="true"/>
          <el-table-column label="手机号码" align="center" key="mobile" prop="mobile" v-if="columns[4].visible"
                           width="120"/>
          <el-table-column label="状态" key="status" v-if="columns[5].visible" align="center">
            <template v-slot="scope">
              <el-switch v-model="scope.row.status" :active-value="0" :inactive-value="1"
                         @change="handleStatusChange(scope.row)"/>
            </template>
          </el-table-column>
          <!--          <el-table-column label="创建时间" align="center" prop="createTime" v-if="columns[6].visible" width="160">-->
          <!--            <template v-slot="scope">-->
          <!--              <span>{{ parseTime(scope.row.createTime) }}</span>-->
          <!--            </template>-->
          <!--          </el-table-column>-->
          <el-table-column label="操作" align="center" width="160" class-name="small-padding fixed-width">
            <template v-slot="scope">
              <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
              >修改
              </el-button>
              <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
              >删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNo" :limit.sync="queryParams.pageSize"
                    @pagination="getList"/>
      </el-col>
    </el-row>

    <!-- 添加或修改参数配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="700px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="员工名称" prop="nickname">
              <el-input v-model="form.nickname" placeholder="请输入员工名称"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="岗位" prop="postId">
              <el-select multiple v-model="form.roleIds" placeholder="请选择岗位">
                <el-option v-for="item in postOptions" :key="item.id" :label="item.name" :value="item.id"/>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="手机号码" prop="mobile">
              <el-input v-model="form.mobile" placeholder="请输入手机号码" maxlength="11"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="form.email" placeholder="请输入邮箱" maxlength="50"/>
            </el-form-item>
          </el-col>
        </el-row>
        <!--        <el-row>-->
        <!--          <el-col :span="12">-->
        <!--            <el-form-item v-if="form.id === undefined" label="员工账号" prop="username">-->
        <!--              <el-input v-model="form.username" placeholder="请输入员工账号"/>-->
        <!--            </el-form-item>-->
        <!--          </el-col>-->
        <!--          <el-col :span="12">-->
        <!--            <el-form-item v-if="form.id === undefined" label="员工密码" prop="password">-->
        <!--              <el-input v-model="form.password" placeholder="请输入员工密码" type="password" show-password/>-->
        <!--            </el-form-item>-->
        <!--          </el-col>-->
        <!--        </el-row>-->
        <el-row>
          <el-col :span="12">
            <el-form-item label="身份证号码" prop="idCard">
              <el-input v-model="form.idCard" placeholder="请输入身份证号码"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="居住地" prop="address">
              <el-input v-model="form.address" placeholder="请输入居住地"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="学历" prop="educational">
              <!--              <el-input v-model="form.educational" placeholder="请输入学历"/>-->
              <el-select v-model="form.educational" placeholder="请选择学历">
                <el-option
                  v-for="dict in educationOptions"
                  :key="dict.label"
                  :label="dict.label"
                  :value="dict.label"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="毕业院校" prop="school">
              <el-input v-model="form.school" placeholder="请输入毕业院校"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="短号" prop="shortNumber">
              <el-input v-model="form.shortNumber" placeholder="请输入短号"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="入职时间" prop="joinDate">
              <el-date-picker v-model="form.joinDate" type="date" placeholder="请选择入职时间"
                              value-format="yyyy-MM-dd"/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="紧急联系人" prop="emergencyContactName">
              <el-input v-model="form.emergencyContactName" placeholder="请输入紧急联系人"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话" prop="emergencyContactPhone">
              <el-input v-model="form.emergencyContactPhone" placeholder="请输入联系电话"/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="员工性别">
              <el-select v-model="form.sex" placeholder="请选择">
                <el-option v-for="dict in sexDictDatas" :key="parseInt(dict.value)" :label="dict.label"
                           :value="parseInt(dict.value)"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="驾照类型" prop="driverLicenseType">
              <el-select
                multiple
                collapse-tags
                v-model="form.driverLicenseTypeArr" placeholder="请选择">
                <el-option
                  v-for="dict in driverLicenseTypeOptions" :key="dict.id" :label="dict.id"
                  :value="dict.id"/>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>

          <el-col :span="12">
            <el-form-item label="社保购买日期" prop="socialSecurityBuyDate">
              <el-date-picker v-model="form.socialSecurityBuyDate" type="date" value-format="yyyy-MM-dd"
                              placeholder="请选择社保购买日期"></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="1">
            <el-form-item label="转正时间" prop="shortNumber">
              <!--              <el-input v-model="form.probationPeriod" placeholder="请输入试用期"/>-->
              <el-date-picker v-model="form.probationPeriod" type="date" value-format="yyyy-MM-dd"
                              placeholder="请选择试用期"></el-date-picker>
            </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-item label="查看附件" v-if="this.form.id">
          <div @click="addFolder">点击查看附件</div>
        </el-form-item>
        <!--        导入附件-->
        <!--        <el-row style="display: flex; justify-content: center;">-->
        <!--          <el-upload-->
        <!--            class="upload-demo"-->
        <!--            :action="imageUpload.url"-->
        <!--            :on-preview="handlePreview"-->
        <!--            :on-remove="handleRemove"-->
        <!--            :before-remove="beforeRemove"-->
        <!--            multiple-->
        <!--            :limit="3"-->
        <!--            :on-exceed="handleExceed"-->
        <!--            :headers="imageUpload.headers"-->
        <!--            :on-success="handleFileSuccessAttachments"-->
        <!--            :file-list="fileList">-->
        <!--            <el-button size="small" type="primary">点击上传</el-button>-->
        <!--            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>-->
        <!--          </el-upload>-->
        <!--        </el-row>-->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <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" append-to-body>
      <el-upload ref="upload" :limit="1" accept=".xlsx, .xls" :headers="upload.headers"
                 :action="upload.url" :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>
      <el-table
        v-if="isFail"
        :data="failList"
        stripe
        style="width: 100%">
        <el-table-column
          prop="username"
          label="员工姓名"
          width="180">
        </el-table-column>
        <el-table-column
          prop="reason"
          label="失败原因">
        </el-table-column>
        <el-table-column
          prop="roleName"
          label="岗位">
        </el-table-column>
        <el-table-column
          prop="idCard"
          label="身份证号">
        </el-table-column>
        <el-table-column
          prop="address"
          label="地址">
        </el-table-column>
        <el-table-column
          prop="educational"
          label="学历">
        </el-table-column>
        <el-table-column
          prop="school"
          label="毕业院校">
        </el-table-column>
        <el-table-column
          prop="mobile"
          label="电话号码">
        </el-table-column>
        <el-table-column
          prop="shortNumber"
          label="短号">
        </el-table-column>
        <el-table-column
          prop="joinDate"
          label="入职日期">
        </el-table-column>
        <el-table-column
          prop="probationPeriod"
          label="转正日期">
        </el-table-column>
        <el-table-column
          prop="socialSecurityBuyDate"
          label="社保购买日期">
        </el-table-column>
        <el-table-column
          prop="emergencyContactName"
          label="紧急联系人">
        </el-table-column>
        <el-table-column
          prop="emergencyContactPhone"
          label="紧急联系人电话">
        </el-table-column>
        <el-table-column
          prop="driverLicenseType"
          label="驾驶证类型">
        </el-table-column>
        <el-table-column
          prop="remark"
          label="备注">
        </el-table-column>
      </el-table>
      <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>
    <ChooseUserDraw ref="chooseUserRef" @success="getList"></ChooseUserDraw>
  </div>
</template>

<script>
import {
  addUser,
  changeUserStatus,
  delUser,
  exportUser,
  getUser,
  importTemplate,
  listUser,
  resetUserPwd,
  getDriverLicenseType,
  updateUser, getPost, permissionAssign, addFolder
} from "./api/staff";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import ChooseUserDraw from "@/views/inspection/staff/ChooseUserDraw";

import {listSimpleDepts} from "@/api/system/dept";
import {listSimplePosts} from "@/api/system/post";

import {CommonStatusEnum} from "@/utils/constants";
import {DICT_TYPE, getDictDatas} from "@/utils/dict";
import {assignUserRole, listUserRoles} from "@/api/system/permission";
import {listSimpleRoles} from "@/api/system/role";
import {getBaseHeader} from "@/utils/request";

export default {
  name: "SystemUser",
  components: {Treeselect, ChooseUserDraw},
  data() {
    return {
      failList: [],
      isFail: false,
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 员工表格数据
      userList: null,
      // 弹出层标题
      title: "",
      // 部门树选项
      deptOptions: undefined,
      // 是否显示弹出层
      open: false,
      // 部门名称
      deptName: undefined,
      // 默认密码
      initPassword: undefined,
      // 性别状态字典
      sexOptions: [],
      // 岗位选项
      postOptions: [],
      // 角色选项
      roleOptions: [],
      isInsert: false,
      // 表单参数
      form: {
        driverLicenseTypeArr: []
      },
      defaultProps: {
        children: "children",
        label: "name"
      },
      // 文件列表
      fileList: [],
      // 驾驶证类型
      driverLicenseTypeOptions: [],
      // 员工导入参数
      upload: {
        // 是否显示弹出层（员工导入）
        open: false,
        // 弹出层标题（员工导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的员工数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: getBaseHeader(),
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + '/admin-api/inspectionStaff/import'
      },
      //图片
      imageUpload: {
        // 是否显示弹出层（员工导入）
        open: false,
        // 弹出层标题（员工导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: getBaseHeader(),
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + '/admin-api/infra/file/uploadDetail'
      },
      // 查询参数
      queryParams: {
        pageNo: 1,
        pageSize: 10,
        username: undefined,
        mobile: undefined,
        status: undefined,
        postId: undefined,
        createTime: []
      },
      // 列信息
      columns: [
        {key: 0, label: `员工编号`, visible: true},
        {key: 1, label: `员工名称`, visible: true},
        {key: 2, label: `员工昵称`, visible: true},
        {key: 3, label: `部门`, visible: false},
        {key: 4, label: `手机号码`, visible: true},
        {key: 5, label: `状态`, visible: false},
        {key: 6, label: `创建时间`, visible: true}
      ],
      // 表单校验
      rules: {
        username: [
          {required: true, message: "员工名称不能为空", trigger: "blur"}
        ],
        nickname: [
          {required: true, message: "员工昵称不能为空", trigger: "blur"}
        ],
        password: [
          {required: true, message: "员工密码不能为空", trigger: "blur"}
        ],
        email: [
          {
            type: "email",
            message: "'请输入正确的邮箱地址",
            trigger: ["blur", "change"]
          }
        ],
        mobile: [
          {
            required: true,
            pattern: /^(?:(?:\+|00)86)?1(?:3[\d]|4[5-79]|5[0-35-9]|6[5-7]|7[0-8]|8[\d]|9[189])\d{8}$/,
            message: "请输入正确的手机号码",
            trigger: "blur"
          }
        ]
      },
      // 是否显示弹出层（角色权限）
      openRole: false,

      // 枚举
      SysCommonStatusEnum: CommonStatusEnum,
      // 数据字典
      statusDictDatas: getDictDatas(DICT_TYPE.COMMON_STATUS),
      sexDictDatas: getDictDatas(DICT_TYPE.SYSTEM_USER_SEX),
      // 学历数组
      educationOptions: getDictDatas(DICT_TYPE.COMPANY_STAFF_EDU),
    };
  },
  watch: {
    // 根据名称筛选部门树
    deptName(val) {
      this.$refs.tree.filter(val);
    }
  },
  created() {
    this.getList();
    // this.getTreeselect();
    this.getDriverLicenseType();
    // this.getConfigKey("sys.user.init-password").then(response => {
    //   this.initPassword = response.msg;
    // });
  },
  methods: {
    // 更多操作
    handleCommand(command, index, row) {
      switch (command) {
        case 'handleUpdate':
          this.handleUpdate(row);//修改客户信息
          break;
        case 'handleDelete':
          this.handleDelete(row);//红号变更
          break;
        case 'handleResetPwd':
          this.handleResetPwd(row);
          break;
        case 'handleRole':
          this.handleRole(row);
          break;
        default:
          break;
      }
    },
    /** 查询员工列表 */
    getList() {
      this.loading = true;
      listUser(this.queryParams).then(response => {
          this.userList = response.data.records;
          this.total = response.data.total;
          this.loading = false;
        }
      );
    },
    /**
     * 选择用户
     **/
    chooseUser(){
      this.$refs["chooseUserRef"].open();
    },
    addFolder() {
      if (!this.form.folderId) {
        addFolder(this.form.id).then(response => {
          this.form.folderId = response.data
          this.$router.push({path: '/jc/shop/nbgl/partner/file/file', query: {"folderId": this.form.folderId}})
        })
      } else {
        this.$router.push({path: '/jc/shop/nbgl/partner/file/file', query: {"folderId": this.form.folderId}})
      }
    },
    // 查询驾驶证类型
    getDriverLicenseType() {
      getDriverLicenseType().then(response => {
        this.driverLicenseTypeOptions = response.data;
      });
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.name.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.postId = data.id;
      this.getList();
    },
    // 员工状态修改
    handleStatusChange(row) {
      let text = row.status === CommonStatusEnum.ENABLE ? "启用" : "停用";
      this.$modal.confirm('确认要"' + text + '""' + row.username + '"员工吗?').then(function () {
        return changeUserStatus(row.id, row.status);
      }).then(() => {
        this.$modal.msgSuccess(text + "成功");
      }).catch(function () {
        row.status = row.status === CommonStatusEnum.ENABLE ? CommonStatusEnum.DISABLE
          : CommonStatusEnum.ENABLE;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 取消按钮（角色权限）
    cancelRole() {
      this.openRole = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        postId: undefined,
        username: undefined,
        nickname: undefined,
        password: undefined,
        mobile: undefined,
        email: undefined,
        sex: undefined,
        status: "0",
        remark: undefined,
        postIds: [],
        roleIds: []
      };
      this.fileList = [];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNo = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.isInsert = true;
      // 获得下拉数据
      this.getPostsByDeptId();
      // 打开表单，并设置初始化
      this.open = true;
      this.title = "添加员工";
      this.form.password = this.initPassword;
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.getPostsByDeptId();
      const id = row.id;
      this.isInsert = false;
      getUser(id).then(response => {
        this.form = response.data;
        // 获取roles中的id
        this.form.roleIds = response.data.roles.map(item => item.id);
        this.fileList = this.form.fileList == null ? [] : this.form.fileList;
        this.open = true;
        this.title = "修改员工";
      });
    },
    /** 重置密码按钮操作 */
    handleResetPwd(row) {
      this.$prompt('请输入"' + row.username + '"的新密码', "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消"
      }).then(({value}) => {
        resetUserPwd(row.id, value).then(response => {
          this.$modal.msgSuccess("修改成功，新密码是：" + value);
        });
      }).catch(() => {
      });
    },
    /** 获取检测岗位集合 */
    getPostsByDeptId() {
      getPost().then(response => {
        this.postOptions = response.data;
        // this.form.postId = this.postOptions[0].id
      });
    },
    /** 分配员工角色操作 */
    handleRole(row) {
      this.reset();
      const id = row.id
      // 处理了 form 的员工 username 和 nickname 的展示
      this.form.id = id;
      this.form.username = row.username;
      this.form.nickname = row.nickname;
      // 打开弹窗
      this.openRole = true;
      // 获得角色列表
      listSimpleRoles().then(response => {
        // 处理 roleOptions 参数
        this.roleOptions = [];
        this.roleOptions.push(...response.data);
      });
      // 获得角色拥有的菜单集合
      listUserRoles(id).then(response => {
        // 设置选中
        this.form.roleIds = response.data;
      })
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.fileList = this.fileList
          if (this.form.id !== undefined) {
            this.form.userId = this.form.id;
            console.log(this.form)
            updateUser(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              let data = {
                userId: this.form.userId,
                roleIds: this.form.roleIds
              }
              permissionAssign(data)
              this.getList();
            });
          } else {
            this.form.username = this.form.mobile
            this.form.password = '123456'
            addUser(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              let data = {
                userId: response.data,
                roleIds: this.form.roleIds
              }
              permissionAssign(data)
            });

          }
        }
      });
    },
    /** 提交按钮（角色权限） */
    submitRole: function () {
      if (this.form.id !== undefined) {
        assignUserRole({
          userId: this.form.id,
          roleIds: this.form.roleIds,
        }).then(response => {
          this.$modal.msgSuccess("分配角色成功");
          this.openRole = false;
          this.getList();
        });
      }
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除员工编号为"' + ids + '"的数据项?').then(function () {
        return delUser(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.$modal.confirm('是否确认导出所有员工数据项?').then(() => {
        // 处理查询参数
        let params = {...this.queryParams};
        params.pageNo = undefined;
        params.pageSize = undefined;
        this.exportLoading = true;
        return exportUser(params);
      }).then(response => {
        this.$download.excel(response, '员工数据.xls');
      }).finally(() => {
        this.exportLoading = false;
      });
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "员工导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      importTemplate().then(response => {
        this.$download.excel(response, '员工导入模板.xls');
      });
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      if (response.code !== 0) {
        this.$modal.msgError(response.msg)
        return;
      }
      // this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      if (response.data.failList.length > 0) {
        this.isFail = true
        console.log('执行了吗')
        this.$set(this, 'failList', response.data.failList);  // 确保响应式
        console.log(this.failList)
      }
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
      this.failList = []
      this.isFail = false
      console.log('执行')
      this.getList()
    },
    handleRemove(file) {
      console.log(file);
      //在fileList中删除附件
      this.fileList.splice(this.fileList.indexOf(file), 1);
    },
    handlePreview(file) {
      console.log(file);
    },
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`);
    },
    // 文件上传成功处理
    handleFileSuccessAttachments(response, file, fileList) {
      if (response.code !== 0) {
        this.$modal.msgError(response.msg)
        return;
      }
      console.log(response)
      this.fileList.push(response.data)
    },
  }
};
</script>
