<template>
  <div class="app-container">
    <el-row :gutter="24">
      <!--用户数据-->
      <el-col :span="24" :xs="24">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" label-width="68px">
          <el-form-item label="用户账号" prop="username">
            <el-input
              maxlength="20"
              v-model="queryParams.username"
              placeholder="请输入用户账号"
              clearable
              style="width: 240px"
            />
          </el-form-item>
          <el-form-item label="手机号码" prop="phonenumber">
            <el-input
              maxlength="11"
              v-model="queryParams.phonenumber"
              placeholder="请输入手机号码"
              clearable
              style="width: 240px"
            />
          </el-form-item>
          <el-form-item label="用户状态" prop="status">
            <el-select
              v-model="queryParams.status"
              placeholder="请选择用户状态"
              clearable
              style="width: 240px"
            >
              <el-option
                v-for="item in statusOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </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"
              @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"
              @click="handleDelete"
              v-hasPermi="['system:user:remove']"
            >删除
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="success"
              plain
              icon="el-icon-unlock"
              size="mini"
              @click="handleRelock"
              v-hasPermi="['system:user:relock']"
            >解锁
            </el-button>
          </el-col>
        </el-row>
        <div style="padding-top: 10px">
          <vxe-table
            ref="userTable"
            align="center"
            :loading="loading"
            class="mytable-style"
            auto-resize
            border
            resizable
            export-config
            highlight-current-row
            show-overflow
            max-height="700"
            :data="userList"
            :radio-config="{trigger: 'row'}"
          >
            <vxe-column type="radio" width="60"/>
            <vxe-table-column field="username" title="用户账号"/>
            <vxe-table-column field="nickname" title="用户姓名"/>
            <vxe-table-column field="mailbox" title="用户邮箱"/>
            <vxe-table-column field="phonenumber" title="手机号码"/>
            <vxe-table-column field="status" title="用户状态" :formatter="statusFormat"/>
            <vxe-table-column field="usertype" title="用户类型" :formatter="typeFormat"/>
            <vxe-table-column field="expDate" title="账号截止日期"/>
            <vxe-table-column title="操作" width="320">
              <template slot-scope="scope" v-if="scope.row.id !== 1">
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-edit"
                  @click="handleResetPwd(scope.row)"
                  v-hasPermi="['system:user:send']"
                >初始/重置密码
                </el-button>
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-delete"
                  @click="handleAuthRole(scope.row)"
                  v-hasPermi="['system:user:role']"
                >分配角色
                </el-button>
              </template>
            </vxe-table-column>
          </vxe-table>
          <vxe-pager
            v-show="showTable"
            perfect
            :current-page.sync="currentPage"
            :page-size.sync="pageSize"
            :total="total"
            :page-sizes="[10,50,100]"
            :layouts="['PrevJump', 'PrevPage','JumpNumber', 'NextPage', 'NextJump', 'Sizes', 'FullJump', 'Total']"
            @page-change="handlePageChange"
          >
          </vxe-pager>
        </div>
      </el-col>
    </el-row>

    <!-- 添加或修改用户配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="650px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" width="630px" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="用户账号" prop="username">
              <el-input id="un" ref="un" style="width: 220px" v-model="form.username" placeholder="请输入用户账号"
                        maxlength="20" :disabled="edit"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="用户姓名" prop="nickname">
              <el-input style="width: 220px" v-model="form.nickname" placeholder="请输入用户姓名" maxlength="30"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="用户邮箱" prop="mailbox">
              <el-input style="width: 220px" v-model="form.mailbox" placeholder="请输入邮箱" maxlength="50"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="手机号码" prop="phonenumber">
              <el-input style="width: 220px" v-model="form.phonenumber" placeholder="请输入手机号码" maxlength="11"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="用户状态">
              <el-select style="width: 220px" v-model="form.status" placeholder="请选择状态">
                <el-option
                  v-for="item in statusOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="用户类型">
              <el-select style="width: 220px" v-model="form.usertype" placeholder="请选择类型">
                <el-option
                  v-for="item in typeOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="截止日期">
              <el-date-picker
                value-format="yyyy-MM-dd"
                v-model="form.expDate"
                type="date"
                placeholder="请选择截止日期">
              </el-date-picker>
            </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="jstitle" :visible.sync="jsopen" width="650px" append-to-body>
      <el-form width="630px" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="用户账号">
              <el-input style="width: 220px" v-model="jsusername"
                        maxlength="20" :disabled="true"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="用户姓名">
              <el-input style="width: 220px" v-model="jsnickname" maxlength="30" :disabled="true"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div style="padding-top: 10px">
        <vxe-table
          ref="xTable"
          align="center"
          :loading="loading"
          class="mytable-style"
          auto-resize
          border
          resizable
          export-config
          highlight-current-row
          show-overflow
          max-height="700"
          :data="roleList"
        >
          <vxe-column type="selection" :reserve-selection="true" width="60"/>
          <vxe-table-column field="roleName" title="角色名称"/>
        </vxe-table>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="jssubmitForm">确 定</el-button>
        <el-button @click="jscancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {debounce} from 'lodash'

export default {
  name: "User",
  data() {
    return {
      id: undefined,
      username: undefined,
      nickname: undefined,
      phonenumber: undefined,
      mailbox: undefined,
      status: "0",
      usertype: "0",
      remark: undefined,
      expDate: undefined,
      // 角色表格数据
      jsuserid: '',
      roleList: [],
      jsusername: '',
      jsnickname: '',
      jsusertype: '',
      statusOptions: [
        {value: '0', label: '正常'},
        {value: '1', label: '锁定'},
        {value: '2', label: '注销'}
      ],
      typeOptions: [
        {value: '0', label: '管理员'},
        {value: '1', label: '业务用户'}
      ],
      // 遮罩层
      loading: true,
      showTable: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      currentPage: 1,
      pageSize: 10,
      // 总条数
      total: 0,
      // 用户表格数据
      userList: null,
      // 弹出层标题
      title: "",
      // 角色分配弹出层标题
      jstitle: "",
      // 是否显示弹出层
      open: false,
      // 角色是否显示弹出层
      jsopen: false,
      // 默认密码
      initPassword: undefined,
      // 角色选项
      roleOptions: [],
      // 表单参数
      form: {},
      // 查询参数
      queryParams: {
        username: undefined,
        phonenumber: undefined,
        status: undefined
      },
      edit: false,
      // 表单校验
      rules: {
        username: [
          {required: true, message: "用户账号不能为空", trigger: "blur"},
          {min: 5, max: 20, message: '用户账号长度必须介于 5 和 20 之间', trigger: 'blur'}
        ],
        nickname: [
          {required: true, message: "用户姓名不能为空", trigger: "blur"},
          {min: 2, max: 20, message: '用户姓名长度必须介于 2 和 20 之间', trigger: 'blur'}
        ],
        mailbox: [
          {required: true, message: "邮箱不能为空", trigger: "blur"},
          {type: "email", message: "请输入正确的邮箱地址", trigger: ["blur", "change"]}
        ],
        phonenumber: [
          {required: true, message: "手机号码不能为空", trigger: "blur"},
          {pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: "请输入正确的手机号码", trigger: "blur"}
        ]
      }
    };
  },
  watch: {},
  created() {
    this.getList()
  },
  methods: {
    handlePageChange({currentPage, pageSize}) {
      this.currentPage = currentPage
      this.pageSize = pageSize
      this.getList()
    },
    // 列表状态格式化
    statusFormat({cellValue}) {
      let belongTo = '未知的类型'
      for (let i = 0; i < this.statusOptions.length; i++) {
        if (cellValue == "0") {
          belongTo = "正常"
        } else if (cellValue == "1") {
          belongTo = "锁定"
        } else if (cellValue == "2") {
          belongTo = "注销"
        }
      }
      return belongTo
    },
    // 列表状态格式化
    typeFormat({cellValue}) {
      let belongTo = '未知的类型'
      for (let i = 0; i < this.typeOptions.length; i++) {
        if (cellValue == "0") {
          belongTo = "管理员"
        } else if (cellValue == "1") {
          belongTo = "普通用户"
        }
      }
      return belongTo
    },
    /** 搜索按钮操作 */
    handleQuery: debounce(function () {
      this.currentPage = 1
      this.pageSize = 10
      this.getList()
    }, 1000),
    /** 查询用户列表 */
    async getList() {
      this.loading = true;
      let sysTime
      let lk
      await this.$axios.get('/sysPolicyController/getLicenseKey').then((res) => {
        sysTime = res.data.sysTime
        lk = res.data.lk
      }).catch((error) => {
        this.loading = false;
      })

      var searchParams = {
        currentPage: this.currentPage,
        pageSize: this.pageSize,
        username: this.queryParams.username,
        phonenumber: this.queryParams.phonenumber,
        status: this.queryParams.status,
        sysTime: sysTime,
        lk: lk
      }
      await this.$axios.get('/sysUserController/getAll',
        {params: searchParams}).then((res) => {
        this.userList = res.data.records
        this.total = res.data.total

        if (res.data.records == '') {
          this.showTable = false
        } else {
          this.showTable = true
        }
        this.loading = false
      }).catch((error) => {
        this.loading = false;
        // this.$message.error(error)
      })
    },
    // 用户状态修改
    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();
    },
    // 角色取消按钮
    jscancel() {
      this.jsopen = false;
    },
    // 表单重置
    reset() {
      this.edit = false;
      this.form = {
        id: undefined,
        username: undefined,
        nickname: undefined,
        phonenumber: undefined,
        mailbox: undefined,
        status: "0",
        usertype: "0",
        remark: undefined,
        expDate: undefined
      };
      // this.resetForm("form");
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.edit = false;
      this.open = true;
      this.title = "添加用户";
      this.form.password = this.initPassword;
    },
    /** 提交按钮 */
    submitForm: debounce(function () {
      this.$refs["form"].validate(async valid => {
        if (valid) {
          let sysTime
          let lk
          await this.$axios.get('/sysPolicyController/getLicenseKey').then((res) => {
            sysTime = res.data.sysTime
            lk = res.data.lk
          }).catch((error) => {
          })

          this.form.sysTime = sysTime
          this.form.lk = lk
          if (this.form.id != undefined) {
            // 更新操作
            await this.$axios.post('/sysUserController/updateUser', this.form).then((res) => {
              if (res.code == 0) {
                this.$message.success('修改成功')
                this.open = false;
                this.reset();
                this.getList();
              }
              if (res.code == 1) {
                this.$message.error(res.data)
              }
              this.loading = false
            }).catch((error) => {
              // this.$message.error(error)
              this.loading = false
            })
          } else {
            await this.$axios.post('/sysUserController/addUser', this.form).then((res) => {
              if (res.code == 0) {
                this.$message.success('新增成功')
                this.open = false;
                this.reset();
                this.getList();
              }
              if (res.code == 1) {
                this.$message.error(res.data)
              }
              this.loading = false
            }).catch((error) => {
              // this.$message.error(error)
              this.loading = false
            })
          }
        }
      });
    }, 1000),
    /** 重置密码按钮操作 */
    handleResetPwd(row) {
      this.$confirm('创建密码并发送到邮箱：' + row.mailbox, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        beforeClose(action, instance, done) {
          if (action === "confirm") {
            instance.$refs["confirm"].$el.onclick = (function (e) {
              e = e || window.event;
              if (e.detail != 0) {
                done();
              }
            })();
          } else {
            done();
          }
        }
      }).then(() => {
        this.doResetPwd(row)
      }).catch(() => {
        //取消操作
      });
    },
    doResetPwd: debounce(async function (row) {
      let sysTime
      let lk
      await this.$axios.get('/sysPolicyController/getLicenseKey').then((res) => {
        sysTime = res.data.sysTime
        lk = res.data.lk
      }).catch((error) => {
      })

      const param = {
        id: row.id,
        sysTime: sysTime,
        lk: lk
      }
      await this.$axios.post('/sysUserController/resetPassword', param).then((res) => {
        if (res.code == 0) {
          this.$message({
            type: 'success',
            message: '创建并发送成功!'
          });
        } else {
          this.$message({
            type: 'error',
            message: res.data
          });
        }
      }).catch((error) => {
        this.$message({
          type: 'error',
          message: '创建密码失败!'
        });
        console.log(error)
        this.loading = false
      })
    }, 1000),

    /** 删除按钮操作 */
    handleDelete() {
      const _selectData = this.$refs.userTable.getRadioRecord(true)
      if (_selectData == null) {
        this.$message({
          type: 'warning',
          message: '请选择记录!'
        });
        return
      }
      if (_selectData.id == 1) {
        this.$message({
          type: 'warning',
          message: '内置系统管理员不能删除!'
        });
        return
      }
      this.$prompt('请输入密码', '鉴别操作', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputType: 'password',
        inputValidator: (val) => {
          if (val === null || val.length < 1 || val.length > 20) {
            return false;
          }
        },
        inputErrorMessage: '不能为空,最多可录入20个字符',
        beforeClose(action, instance, done) {
          if (action === "confirm") {
            instance.$refs["confirm"].$el.onclick = (function (e) {
              e = e || window.event;
              if (e.detail != 0) {
                done();
              }
            })();
          } else {
            done();
          }
        }
      }).then(async ({value}) => {
        this.doDelete(_selectData, value)
      }).catch((e) => {
      })
    },
    /**
     * 删除提交
     */
    doDelete: debounce(async function (_selectData, againPwd) {
      let sysTime
      let lk
      await this.$axios.get('/sysPolicyController/getLicenseKey').then((res) => {
        sysTime = res.data.sysTime
        lk = res.data.lk
      }).catch((error) => {
      })

      const param = {
        id: _selectData.id,
        againPwd: againPwd,
        sysTime: sysTime,
        lk: lk
      }
      await this.$axios.post('/sysUserController/delUser', param).then((res) => {
        if (res.code == 0) {
          this.$message({
            type: 'success',
            message: res.data
          });
          this.getList();
        } else {
          this.$message({
            type: 'error',
            message: res.data
          });
        }
      }).catch((error) => {
        this.$message({
          type: 'error',
          message: '删除失败!'
        });
        this.loading = false
      })
    }, 500),
    /** 修改按钮操作 */
    handleUpdate() {
      this.reset();
      let _selectData = this.$refs.userTable.getRadioRecord(true)
      if (_selectData == null) {
        this.$message({
          type: 'warning',
          message: '请选择记录!'
        });
        return
      }
      this.form = _selectData;
      this.open = true;
      this.title = "修改用户";
      this.edit = true;
    },
    /** 解锁按钮操作 */
    handleRelock() {
      const _selectData = this.$refs.userTable.getRadioRecord(true)
      if (_selectData == null) {
        this.$message({
          type: 'warning',
          message: '请选择记录!'
        });
        return
      }
      if (_selectData.status !== '1') {
        this.$message({
          type: 'warning',
          message: '只能对【锁定】状态的进行解锁!'
        });
        return
      }
      this.$confirm('是否解锁用户?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        beforeClose(action, instance, done) {
          if (action === "confirm") {
            instance.$refs["confirm"].$el.onclick = (function (e) {
              e = e || window.event;
              if (e.detail != 0) {
                done();
              }
            })();
          } else {
            done();
          }
        }
      }).then(() => {
        this.doRelock(_selectData)
      }).catch(() => {
        //取消操作
      });
    },
    /**
     * 解锁提交
     */
    doRelock: debounce(async function (_selectData) {
      let sysTime
      let lk
      await this.$axios.get('/sysPolicyController/getLicenseKey').then((res) => {
        sysTime = res.data.sysTime
        lk = res.data.lk
      }).catch((error) => {
      })
      const param = {
        id: _selectData.id,
        sysTime: sysTime,
        lk: lk
      }
      await this.$axios.post('/sysUserController/relockUser', param).then((res) => {
        if (res.code == 0) {
          this.$message({
            type: 'success',
            message: '解锁成功!'
          });
          this.getList();
        } else {
          this.$message({
            type: 'error',
            message: res.data
          });
        }
      }).catch((error) => {
        this.$message({
          type: 'error',
          message: '解锁失败!'
        });
        console.log(error)
        this.loading = false
      })
    }, 1000),
    getUserRole(userid) {
      const a = this.$axios
      return new Promise(async function (resolve, reject) {
        let sysTime
        let lk
        await a.get('/sysPolicyController/getLicenseKey').then((res) => {
          sysTime = res.data.sysTime
          lk = res.data.lk
        }).catch((error) => {
        })

        var userRoleParams = {
          userId: userid,
          sysTime: sysTime,
          lk: lk
        }
        await a.get('/sysUserController/getUserRole',
          {params: userRoleParams}).then(res => {
          // 返回userRole对象
          resolve(res.data)
        })
      }).catch((error) => {
        this.loading = false
        console.error('获取用户角色出错' + error)
      })
    },
    getRoleByType(usertype) {
      // 根据用户类型获取角色列表
      const a = this.$axios
      let _this = this
      return new Promise(async function (resolve, reject) {
        let sysTime
        let lk
        await a.get('/sysPolicyController/getLicenseKey').then((res) => {
          sysTime = res.data.sysTime
          lk = res.data.lk
        }).catch((error) => {
        })

        var searchParams = {
          usertype: usertype,
          sysTime: sysTime,
          lk: lk
        }
        await a.get('/sysRoleController/getRoleByType',
          {params: searchParams}).then(res => {
          if (res.code == 0) {
            // 返回角色列表
            _this.roleList = res.data
            resolve(res.data)
          } else {
            // 输出后端返回信息
            this.$message({
              type: 'error',
              message: res.data
            });
          }
        })
      }).catch((error) => {
        this.loading = false
        this.$message.error(error)
      })
    },
    /** 分配角色操作 */
    handleAuthRole: debounce(function (row) {
      this.jsuserid = row.id
      this.jsusername = row.username
      this.jsnickname = row.nickname
      this.jsopen = true;
      this.title = "分配角色";

      Promise.all([this.getRoleByType(row.usertype), this.getUserRole(this.jsuserid)]).then((res) => {
        if (res[1] != '' && res[1] != undefined) {
          const roleTable = this.$refs.xTable.getTableData()
          for (var i = 0; i < roleTable.tableData.length; i++) {
            if (res[1].roleId == roleTable.tableData[i].roleId) {
              // 将原有的角色勾选上
              this.$refs.xTable.setCheckboxRow(roleTable.tableData[i], true)
            }
          }
        }
      }).catch(e => {
        this.loading = false
        this.$message.error("获取分配角色异常：" + e)
      })
    }, 1000),
    /** 角色分配提交按钮 */
    jssubmitForm: debounce(async function () {
      const _selectData = this.$refs.xTable.getCheckboxRecords(true)
      if (_selectData.length > 1) {
        this.$message({
          type: 'warning',
          message: '每个用户只能分配一个角色!'
        });
        return
      }
      let roleid = '';
      if (_selectData.length == 1) {
        roleid = _selectData[0].roleId
      } else {
        this.$message({
          type: 'warning',
          message: '请选择角色!'
        });
        return
      }

      let sysTime
      let lk
      await this.$axios.get('/sysPolicyController/getLicenseKey').then((res) => {
        sysTime = res.data.sysTime
        lk = res.data.lk
      }).catch((error) => {
      })

      // 提交后台角色分配
      const param = {
        userId: this.jsuserid,
        roleId: roleid,
        sysTime: sysTime,
        lk: lk
      }
      await this.$axios.post('/sysUserController/authRole', param).then((res) => {
        if (res.code == 0) {
          this.$message({
            type: 'success',
            message: '角色分配成功!'
          });
          this.jscancel()
        } else {
          this.$message({
            type: 'error',
            message: res.data
          });
        }
      }).catch((error) => {
        this.$message({
          type: 'error',
          message: '角色分配失败!'
        });
        this.loading = false
      })
    }, 1000)
  }
};
</script>
