<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
              v-model="queryParams.username"
              placeholder="请输入用户账号"
              clearable
              style="width: 240px"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="手机号码" prop="phonenumber">
            <el-input
              v-model="queryParams.phonenumber"
              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="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"
            >新增
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="success"
              plain
              icon="el-icon-edit"
              size="mini"
              @click="handleUpdate"
            >修改
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="danger"
              plain
              icon="el-icon-delete"
              size="mini"
              @click="handleDelete"
            >删除
            </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 title="操作" width="320">
              <template slot-scope="scope" v-if="scope.row.userId !== 1">
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-edit"
                  @click="handleResetPwd(scope.row)"
                >初始/重置密码
                </el-button>
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-delete"
                  @click="handleAuthRole(scope.row)"
                >分配角色
                </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.roleIds" multiple placeholder="请选择角色">
                <el-option
                  v-for="item in roleOptions"
                  :key="item.roleId"
                  :label="item.roleName"
                  :value="item.roleId"
                  :disabled="item.status == 1"
                ></el-option>
              </el-select>
            </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>
  </div>
</template>

<script>
import { debounce } from 'lodash'
export default {
  name: "User",
  data() {
    return {
      statusOptions: [
        {value: '0', label: '正常'},
        {value: '1', label: '锁定'},
        {value: '2', label: '注销'}
      ],
      // 遮罩层
      loading: true,
      showTable: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      currentPage: 1,
      pageSize: 10,
      // 总条数
      total: 0,
      // 用户表格数据
      userList: null,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: 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
    },
    /** 查询用户列表 */
    getList:debounce(function(){
      this.loading = true;
      var searchParams = {
        currentPage: this.currentPage,
        pageSize: this.pageSize,
        username: this.queryParams.username,
        phonenumber: this.queryParams.phonenumber,
        status: this.queryParams.status
      }
      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.$message.error('获取数据出错' + error)
      })
    },1000),
    // 用户状态修改
    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.edit = false;
      this.form = {
        id: undefined,
        username: undefined,
        nickname: undefined,
        phonenumber: undefined,
        mailbox: undefined,
        status: "0",
        remark: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList();
    },
    /** 重置按钮操作 */
    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(valid => {
        if (valid) {
          if (this.form.id != undefined) {
            // 更新操作
            this.$axios.put('/sysUserController', 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 {
            // const param = {
            //   username: this.form.username,
            //   nickname: this.form.nickname,
            //   phonenumber: this.form.phonenumber,
            //   mailbox: this.form.mailbox
            // }
            this.$axios.post('/sysUserController', 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:debounce(function(row){
      this.$confirm('创建密码并发送到邮箱：' + row.mailbox, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const param = {
          id: row.id
        }
        this.$axios.post('/sysUserController/resetPassword', param).then((res) => {
          if (res.code == 0) {
            this.$message({
              type: 'success',
              message: '创建并发送成功!'
            });
          } else {
            this.$message({
              type: 'error',
              message: '创建密码失败!'
            });
          }
        }).catch((error) => {
          console.log(error)
          this.loading = false
        })
      }).catch(() => {
      });
    },1000),
    /** 删除按钮操作 */
    handleDelete(){
      const _selectData = this.$refs.userTable.getRadioRecord(true)
      if (_selectData == null) {
        this.$message({
          type: 'warning',
          message: '请选择记录!'
        });
        return
      }
      this.$confirm('是否确认删除用户?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const param = {
          id: _selectData.id
        }
        this.$axios.post('/sysUserController/delUser', param).then((res) => {
          if (res.code == 0) {
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
            this.getList();
          } else {
            this.$message({
              type: 'error',
              message: '删除失败!'
            });
          }
        }).catch((error) => {
          console.log(error)
          this.loading = false
        })
      }).catch(() => {
      });
    },
    /** 修改按钮操作 */
    handleUpdate() {
      this.reset();
      const _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;
    },
    /** 分配角色操作 */
    handleAuthRole: function (row) {
      const userId = row.userId;
      this.$router.push("/system/user-auth/role/" + userId);
    }
  }
};
</script>
