<template>
    <div class="app-container">
      <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.userName"
            placeholder="请输入姓名"
            clearable
            style="width: 240px"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="部门名称" prop="orgId">
          <treeselect v-model="queryParams.orgId" :options="deptOptions" :normalizer="normalizer" placeholder="选择部门" style="width: 240px"/>
        </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="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="info" plain icon="el-icon-upload2" size="mini" @click="handleImport" v-hasPermi="['system:user:excelUpload']"
          >导入</el-button>
        </el-col>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>

      <el-table v-loading="loading" :data="userList" @selection-change="handleSelectionChange">
        <el-table-column label="序号" align="center" width="80" type="index">
          <template slot-scope="scope">
            <span>{{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1 }}</span>
          </template>
        </el-table-column>
        <el-table-column label="姓名" align="center" prop="userName" />
        <el-table-column label="所属部门" align="center" prop="orgName" :show-overflow-tooltip="true" />
        <el-table-column label="岗位" align="center" prop="postName" :show-overflow-tooltip="true"/>
        <el-table-column label="人员角色" align="center" prop="roleName" :show-overflow-tooltip="true" />
        <el-table-column label="身份证号" align="center" prop="idNumber" :show-overflow-tooltip="true" />
        <el-table-column label="手机号(登录名称)" align="center" prop="phone" :show-overflow-tooltip="true" />
        <el-table-column label="操作" align="center" width="300">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="primary"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['system:user:edit']"
            >编辑</el-button>
            <el-button
              size="mini"
              type="danger"
              v-hasPermi="['system:user:del']"
              @click="handleDelete(scope.row)"
            >删除</el-button>
            <el-button
              size="mini"
              type="warning"
              v-hasPermi="['system:user:pwd']"
              @click="handleResetPwd(scope.row)"
            >重置密码</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-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
        <el-form ref="form" :model="form" :rules="rules" label-width="100px">
            <el-row>
                <el-col :span="12">
                    <el-form-item label="姓名" prop="userName">
                        <el-input v-model="form.userName" placeholder="请输入姓名" maxlength="20"/>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="所属部门" prop="orgIds">
                      <treeselect v-model="form.orgIds" :multiple="true" :flat="true" :options="deptOptions" :normalizer="normalizer" placeholder="选择所属部门"/>
                    </el-form-item>
                </el-col>
            </el-row>

            <el-row>
                <el-col :span="12">
                    <el-form-item label="岗位名称" prop="postIds">
                        <el-select v-model="form.postIds" multiple  placeholder="人员岗位" clearable>
                          <el-option v-for="dict in dict.type.post_list" :key="dict.value" :label="dict.label"
                          :value="dict.value"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="人员角色" prop="roleIds">
                        <el-select v-model="form.roleIds" multiple  placeholder="人员角色" clearable>
                            <el-option
                            v-for="item in roleList"
                            :key="item.roleId"
                            :label="item.roleName"
                            :value="item.roleId"
                            />
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>

            <el-row>
                <el-col :span="12">
                    <el-form-item label="手机号码" prop="phone">
                        <el-input v-model="form.phone" placeholder="请输入手机号码" maxlength="11"/>
                    </el-form-item>
                </el-col>

              <el-col :span="12">
                <el-form-item label="身份证号" prop="idNumber">
                  <el-input v-model="form.idNumber" placeholder="请输入身份证号码" maxlength="18"/>
                </el-form-item>
              </el-col>

            </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" 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, getUserById, delUser, addUser, updateUser, getSelectRole, exportUser,resetPwd,userTempFile } from "@/api/system/userInfo";
  import { listDept } from "@/api/system/dept";
  import { getToken } from "@/utils/auth";
  import Treeselect from "@riophae/vue-treeselect";
  import "@riophae/vue-treeselect/dist/vue-treeselect.css";
  import {downloadFile} from "@/utils/download";
  export default {
    name: "Dict",
    dicts: ['post_list'],
    components: { Treeselect },
    data() {
      return {
        // 遮罩层
        loading: false,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 字典表格数据
        userList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        deptOptions:[],
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          userName: undefined,
          orgId: undefined,
        },
        roleList:[],
        // 表单参数
        form: {},
        // 表单校验
        rules: {
          userName: [
            { required: true, message: "人员姓名不能为空", trigger: "blur" }
          ],
          orgIds: [
            { required: true, message: "所属部门不能为空", trigger: "blur" }
          ],
          postIds: [
            { required: true, message: "岗位名称不能为空", trigger: "blur" }
          ],
          roleIds: [
            { required: true, message: "人员角色不能为空", trigger: "blur" }
          ],
          phone: [
            { required: true, message: "手机号码不能为空", trigger: "blur" },
            {
              pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
              message: "请输入正确的手机号码",
              trigger: "blur"
            }
          ],
          idNumber: [
            { required: true, message: "身份证号码不能为空", trigger: "blur" },
            {
              pattern: /^[1-9]\d{5}(18|19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[1-2]\d|3[0-1])\d{3}[\dXx]$/,
              message: "身份证号码格式不正确",
              trigger: "blur"
            }
          ],
        },
        // 用户导入参数
        upload: {
          // 是否显示弹出层（用户导入）
          open: false,
          // 弹出层标题（用户导入）
          title: "",
          // 是否禁用上传
          isUploading: false,
          // 是否更新已经存在的用户数据
          updateSupport: 0,
          // 设置上传的请求头部
          headers: { Authorization: "Bearer " + getToken() },
          // 上传的地址
          url: process.env.VUE_APP_BASE_API + "/system/user/excelUpload"
        },
      };
    },
    created() {
      this.getList();
      this.getDeptList();
      this.getRoleList();
      console.log(this.dict.type.post_list)
    },
    methods: {
      getRoleList(){
        getSelectRole().then(response => {
            this.roleList = response.data
        });
      },
      getDeptList(){
        listDept().then(response => {
            this.deptOptions = this.handleTree(response.data, "id");
        });
      },
      /** 转换部门数据结构 */
      normalizer(node) {
        if (node.children && !node.children.length) {
            delete node.children;
        }
        return {
            id: node.id,
            label: node.orgName,
            children: node.children
        };
      },
      /** 查询列表 */
      getList() {
        this.loading = true;
        listUser(this.queryParams).then(response => {
            this.userList = response.rows;
            this.total = response.total;
            this.loading = false;
          }
        );
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          userName: undefined,
          orgIds:[],
          roleIds:[],
          postIds:[],
        };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.open = true;
        this.title = "新增人员";
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.userId)
        this.single = selection.length!=1
        this.multiple = !selection.length
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        let param={
          userId:row.userId
        }
        getUserById(param).then(response => {
          this.form = response.data[0];
          let arr = this.form.postIds.map(item=>{return item.toString()})
          this.$set(this.form,'postIds',arr)
          this.open = true;
          this.title = "编辑人员";
          this.$forceUpdate()
        });
      },
      /** 提交按钮 */
      submitForm: function() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.userId != undefined) {
              updateUser(this.form).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            } else {
              addUser(this.form).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        let param={
          userId:row.userId
        }
        this.$modal.confirm('是否确认删除？').then(function() {
          return delUser(param);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {});
      },
      /** 重置密码按钮操作 */
      handleResetPwd(row) {
        let param={
          userId:row.userId
        }
        this.$modal.confirm('是否确认重置该用户密码？').then(function() {
          return resetPwd(param);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("重置成功");
        }).catch(() => {});
      },
      /** 导出按钮操作 */
      handleExport() {
        exportUser(this.queryParams).then(res => {
          downloadFile({ fileName: `用户_${new Date().getTime()}.xlsx`, fileData: res, fileType: 'application/vnd.ms-excel;charset=utf-8' })
        })
      },
      /** 导入按钮操作 */
      handleImport() {
        this.upload.title = "用户导入";
        this.upload.open = true;
      },
      /** 下载模板操作 */
      importTemplate() {
        this.download('/system/user/userFile', {}, `用户模板_${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();
      }
    }
  };
  </script>
