<!-- 用户管理 -->
<template>
  <div class="user">
    <div class="header">
      <div class="left">
        <el-button class="btn" @click="goPage">角色管理</el-button>
        <el-button class="btn" @click="showForm(0)">+ 新增</el-button>
      </div>
      <div class="center">
        {{$x_factory.plantName}} - 用户管理
      </div>
      <div class="right">
        <!-- <i class="el-icon-close" @click="back" /> -->
      </div>
    </div>
    <div class="main global">
      <div class="table">
        <el-table ref="table" :data="tableData" height="100%" v-loading="tableLoading" :element-loading-background="loadingColor">
          <el-table-column prop="username" label="用户名" align="center"></el-table-column>
          <el-table-column prop="role.name" label="角色" align="center"></el-table-column>
          <el-table-column prop="name" label="姓名" align="center"></el-table-column>
          <el-table-column prop="phone" label="手机" align="center"></el-table-column>
          <el-table-column prop="sex" label="性别" align="center"></el-table-column>
          <el-table-column label="操作" align="center">
            <template v-slot="scope">
              <span class="table-btn" @click="showForm(scope.row)">编辑</span>
              <el-divider v-if="scope.row.id != 1 && $x_user.checkPermission('UserDelete')" direction="vertical"></el-divider>
              <span v-if="scope.row.id != 1 && $x_user.checkPermission('UserDelete')" class="table-btn" @click="delForm(scope.row)">删除</span>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <el-pagination class="page" layout="prev, pager, next" :total="tableTotal" @current-change="pageChange" />
    </div>

    <el-dialog class="dialog global" width="30%" :title="formTitle" :visible.sync="formShow" destroy-on-close v-loading="formLoading"
      :element-loading-background="loadingColor">
      <el-form ref="form" :model="formData" :rules="formRules" label-width="100px" size="small">
        <el-form-item label="用户名" prop="username">
          <el-input v-model.trim="formData.username" placeholder="请填写用户名(以此登录)" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="formData.password" type="password" :placeholder="placeholderPass" />
        </el-form-item>
        <el-form-item label="角色" prop="roleId">
          <el-select style="width: 100%;" v-model="formData.roleId" :popper-append-to-body="false" popper-class="select-popper"
            placeholder="请选择角色">
            <el-option v-for="(item, index) in roleList" :key="index" :label="item.name" :value="item.roleId" />
          </el-select>
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model.trim="formData.name" placeholder="请填写姓名" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model.trim="formData.phone" placeholder="请填写手机号" />
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-select style="width: 100%;" v-model="formData.sex" :popper-append-to-body="false" popper-class="select-popper"
            placeholder="请选择性别">
            <el-option label="男" value="男" />
            <el-option label="女" value="女" />
          </el-select>
        </el-form-item>
      </el-form>
      <div class="btn-list">
        <el-button class="btn-active" type="primary" @click="onSubmit">保存</el-button>
        <el-button class="btn-default" @click="formShow = false">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {
    ChartStyle
  } from '@/common/const.js';
  import User from '@/api/user.js';
  export default {
    components: {},
    data() {
      // 用户名验证规则，不能包含特殊字符
      const validateUsername = (rule, value, callback) => {
        if (value && /[|]+/.test(value)) {
          callback(new Error('不能包含特殊字符'));
        } else {
          callback();
        }
      };
      // 手机验证规则,可以为空
      const validatePhone = (rule, value, callback) => {
        if (value && !/^((\+?86)|(\(\+86\)))?(1\d{10})$/.test(value)) {
          callback(new Error('手机格式错误'));
        } else {
          callback();
        }
      };
      return {
        tableLoading: false,
        formLoading: false,
        loadingColor: ChartStyle.loadingColor,
        // 查询参数
        tableQuery: {
          pageNo: 0, // 0为第一页
          pageSize: 10
        },
        tableData: null,
        tableTotal: 100,
        formShow: false,
        formTitle: '',
        formData: null,
        formRules: {
          username: [{
            required: true,
            message: '请输入用户名称',
            trigger: 'blur'
          }, {
            validator: validateUsername,
            trigger: 'blur'
          }],
          password: [],
          // name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
          phone: [{
            validator: validatePhone,
            trigger: 'blur'
          }],
          roleId: [{
            required: true,
            message: '请选择角色',
            trigger: 'blur'
          }],
        },
        placeholderPass: '',
        roleList: [],
      };
    },
    created() {
      this.formReset();
      this.getList();
    },
    methods: {
      // 跳转角色管理
      goPage() {
        this.$router.push('/RoleManage');
      },
      // 返回上一页
      back() {
        this.$router.go(-1);
      },
      // 重置表单
      formReset() {
        this.formData = {
          username: '',
          password: '',
          name: '',
          phone: '',
          sex: '男',
          roleId: '',
        };
      },
      // 获取用户列表
      async getList() {
        this.tableLoading = true;
        try {
          let res = await User.getUserList(this.tableQuery);
        	this.tableData = res.content;
        	this.tableTotal = res.totalElements;
        } catch (e) {
        	console.log(e);
        }
        this.tableLoading = false;
      },
      // 翻页
      pageChange(val) {
        this.tableQuery.pageNo = val - 1;
        this.getList();
      },
      // 新增编辑
      async showForm(row) {
        this.getRoleList();
        // 编辑
        if (row) {
          this.formTitle = '编辑用户';
          // 回显赋值，之所以要一个个的赋值，是因为后端的编辑接口不能把多余的数据传过去
          this.formData = {
            id: row.id,
            username: row.username || '',
            name: row.name || '',
            phone: row.phone || '',
            sex: row.sex || '男',
            roleId: row.role?.roleId || '',
          };
          // 密码验证规则
          const validatePass = (rule, value, callback) => {
            if (value && value.length < 6) {
              callback(new Error('密码至少6个字符'));
            } else {
              callback();
            }
          };
          this.placeholderPass = '不填写则不修改';
          // 增加密码验证规则
          this.formRules.password = [{
            validator: validatePass,
            trigger: 'blur'
          }];
          // 新增
        } else {
          this.formTitle = '新增用户';
          this.formReset(); // 清空表单
          this.placeholderPass = '请填写密码，至少6位字符';
          this.formRules.password = [{
            required: true,
            message: '请输入用户密码',
            trigger: 'blur'
          }]; // 增加密码验证规则
        }
        this.formShow = true;
      },
      // 获取角色列表
      async getRoleList() {
        try {
          let res = await User.getRoleList();
          this.roleList = res;
        } catch (e) {
          console.log(e);
        }
      },
      // 删除数据
      async delForm(row) {
        if (!row.id || row.id == 1) return;
        this.tableLoading = true;
        try {
          await this.$confirm('确认删除该用户？');
          await User.delUser(row.id);
          this.$message.success('删除成功');
          if (this.tableData.length == 1 && this.tableQuery.pageNo != 0) this.tableQuery.pageNo--; // 如果删除时是当前页的最后一条，则页数往前翻一页
          this.getList();
        } catch (e) {
          console.log(e);
          this.tableLoading = false;
        }
      },
      // 提交表单
      onSubmit() {
        this.$refs.form.validate(async valid => {
          if (!valid) return;
          this.formData.role = {
            roleId: this.formData.roleId
          };
          let apiName = this.formData.id ? 'editUser' : 'addUser'; // 根据是否有id选择调用对应的接口
          this.formLoading = true;
          try {
          	await User[apiName](this.formData);
          	this.$message.success('操作成功');
          	this.formShow = false;
          	this.getList();
          } catch (e) {
          	console.log(e);
          }
          this.formLoading = false;
        });
      }
    }
  };
</script>

<style lang="scss" scoped>
  .user {
    height: 100%;
    padding: 1.875rem 3.125rem;
    box-sizing: border-box;

    .header {
      height: 4.25rem;
	  line-height: 4.25rem;
      background-image: linear-gradient(270deg, rgba(197, 254, 255, 0.10) 0%, rgba(147, 252, 255, 0.50) 52%, rgba(147, 252, 255, 0.10) 100%);
      padding: 0 1.875rem;
      box-sizing: border-box;
      position: relative;
      display: flex;
      align-items: center;
      justify-content: space-between;

      .left {
        display: flex;
        z-index: 1;

        .btn {
          @extend %btn-default;
        }

        .btn:hover {
          @extend %btn-hover;
        }
      }

      .center {
        @extend %pos-center;
        font-size: 1.625rem;
        letter-spacing: 0.1625rem;
        text-shadow: 0 2px 8px rgba(78, 97, 214, 0.50);
      }

      .right {
        z-index: 1;

        i {
          font-size: 1.6rem;
        }
      }
    }

    .main {
      height: calc(100% - 4.25rem);
      background: rgba(147, 252, 255, 0.08);
      padding: 1.875rem 1.875rem 0;
      box-sizing: border-box;

      .table {
        height: calc(100% - 40px);

        .table-btn {
          color: $color-cyan;
          cursor: pointer;
        }
      }

      .page {
        margin: 0.3125rem 0;
      }
    }
    
    .dialog {
      /deep/ .el-form-item__label {
          color: #fff;
      }
      
      .btn-list{
        @extend %flex-center;
        margin-top: 2rem;
      }
      
      .btn-active{
        @extend %btn-active;
      }
      
      .btn-default {
        @extend %btn-default;
      }
    }
  }
</style>
