<template>
  <div class="sy-content">
    <el-row>
      <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.userName"
              placeholder="请输入用户名称"
              clearable
              style="width: 150px"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="用户状态" prop="state">
            <el-select
              v-model="queryParams.state"
              placeholder="用户状态"
              clearable
              style="width: 150px"
            >
              <el-option
                v-for="status in userStatus"
                :key="status.value"
                :label="status.name"
                :value="status.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="用户类型" prop="userType">
            <el-select
              v-model="queryParams.userType"
              placeholder="用户类型"
              clearable
              style="width: 150px"
            >
              <el-option
                v-for="type in userType"
                :key="type.value"
                :label="type.name"
                :value="type.value"
              />
            </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>
          <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" style="margin-left: 15px;">
            <el-button
              type="danger"
              plain
              icon="el-icon-delete"
              size="mini"
              @click="handleDelete"
            >删除</el-button>
          </el-col>
        </el-row>
        <!-- 表格数据信息 -->
        <el-table v-loading="loading" :data="userList" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="50" align="center"/>
          <el-table-column label="用户编号" align="center" key="userId" prop="userId" v-if="false"/>
          <el-table-column label="用户名称" align="center" key="userName" prop="userName" :show-overflow-tooltip="true"/>
          <el-table-column label="用户状态" align="center" key="state" prop="state" :show-overflow-tooltip="true">
            <template slot-scope="scope">
              <span>{{ convertUserStatus(scope.row.state) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="用户类型" align="center" key="userType" prop="userType" :show-overflow-tooltip="true">
            <template slot-scope="scope">
              <span>{{ convertUserType(scope.row.userType) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="最后登录时间" align="center" key="lastLoginTime" prop="lastLoginTime" width="160"/>
          <el-table-column label="创建时间" align="center" prop="createTime" width="160"/>
          <el-table-column
            label="操作"
            align="center"
            width="250"
            class-name="small-padding fixed-width"
          >
            <template slot-scope="scope" v-if="scope.row.userId !== 1">
              <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>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-key"
                @click="handleResetPwd(scope.row)"
              >重置密码</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页信息 -->
        <pagination
          v-show="total > 0"
          :total="total"
          :page.sync="queryParams.page"
          :limit.sync="queryParams.limit"
          align="right"
          @pagination="getUserList"
        />
      </el-col>
    </el-row>

    <!-- 添加或修改用户配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" 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="userName">
              <el-input v-if="form.userId == undefined" v-model="form.userName" placeholder="请输入用户名称" maxlength="30" />
              <el-input v-else v-model="form.userName" placeholder="请输入用户名称" maxlength="30" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="用户密码" prop="password" v-if="form.userId == undefined">
              <el-input v-model="form.password" placeholder="请输入用户密码" type="password" maxlength="20" show-password auto-complete="new-password"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="用户类型">
              <el-select v-model="form.userType" placeholder="请选择用户类型">
                <el-option
                  v-for="dict in userType"
                  :key="dict.value"
                  :label="dict.name"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="用户状态" v-if="form.userId != undefined">
              <el-radio-group v-model="form.state">
                <el-radio
                  v-for="dict in userStatus"
                  :key="dict.value"
                  :label="dict.value"
                >{{dict.name}}</el-radio>
              </el-radio-group>
            </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 { addUserInfo, getUserList, updateUserInfo, delUserById } from '@/api/system/user'
import { getPubKey } from '@/utils/auth'
import { encrypt } from '@/utils/jsencrypt'

export default {
  name: 'Index',
  data() {
    return {
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 查询参数
      queryParams: {
        page: 1,
        limit: 10,
        userName: undefined,
        userType: undefined,
        state: undefined
      },
      // 总条数
      total: 0,
      // 用户表格数据
      userList: null,
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 表单参数
      form: {},
      // 管理员默认ID
      defaultAdminId: '1',
      // 用户状态
      userStatus: [{
        'name': '正常',
        'value': 0
      }, {
        'name': '锁定',
        'value': 1
      }],
      // 用户类型
      userType: [{
        'name': '客户端用户',
        'value': 0
      }, {
        'name': '管理端用户',
        'value': 1
      }],
      // 表单校验
      rules: {
        userName: [
          { required: true, message: '用户名称不能为空', trigger: 'blur' },
          { min: 2, max: 20, message: '用户名称长度必须介于 2 和 20 之间', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '用户密码不能为空', trigger: 'blur' },
          { min: 5, max: 20, message: '用户密码长度必须介于 5 和 20 之间', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getUserList()
  },
  methods: {
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.page = 1
      this.getUserList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.$refs['queryForm'].resetFields()
      this.handleQuery()
    },
    /** 多选框选中数据 */
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.userId)
    },
    /** 用户状态转换 */
    convertUserStatus(val) {
      let result = ''
      this.userStatus.forEach((e) => {
        if (e.value === val) {
          result = e.name
        }
      })
      return result
    },
    /** 用户类型转换 */
    convertUserType(val) {
      let result = ''
      this.userType.forEach((e) => {
        if (e.value === val) {
          result = e.name
        }
      })
      return result
    },
    /** 查询用户列表 */
    getUserList() {
      this.loading = true
      getUserList(this.queryParams).then(response => {
        const data = response.data
        this.userList = data.userList
        this.total = data.count
        this.loading = false
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const userId = row.userId
      if (!userId) {
        const userIdList = this.ids
        if (!userIdList || userIdList.length === 0) {
          this.$message({
            message: '请选择您要删除的用户',
            type: 'warning'
          })
          return
        }
        this.$confirm('您确定要删除选中的用户吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          for (const i in userIdList) {
            const id = userIdList[i]
            if (id === this.defaultAdminId) {
              continue
            }
            delUserById({
              'userId': id
            }).then(response => {
              this.getUserList()
            })
          }
        }).catch(() => {
        })
        return
      }
      if (userId === this.defaultAdminId) {
        this.$message({
          message: '系统管理员帐号无法进行删除操作',
          type: 'warning'
        })
        return
      }
      this.$confirm('您确定要删除用户【' + row.userName + '】吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        delUserById({
          userId
        }).then(response => {
          this.$message({
            message: '删除成功',
            type: 'success'
          })
          this.getUserList()
        })
      }).catch(() => {
      })
    },
    /** 重置密码按钮操作 */
    handleResetPwd(row) {
      if (row.userId === this.defaultAdminId) {
        this.$message({
          message: '系统管理员帐号无法进行密码重置操作',
          type: 'warning'
        })
        return
      }
      this.$prompt('请输入"' + row.userName + '"的新密码', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        closeOnClickModal: false,
        inputPattern: /^.{5,20}$/,
        inputErrorMessage: '用户密码长度必须介于 5 和 20 之间'
      }).then(({ value }) => {
        // resetUserPwd(row.userId, value).then(response => {
        //   this.$modal.msgSuccess("修改成功，新密码是：" + value);
        // });
      }).catch(() => {})
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      if (row.userId === this.defaultAdminId) {
        this.$message({
          message: '系统管理员帐号无法进行修改操作',
          type: 'warning'
        })
        return
      }
      this.reset()
      this.form = {
        userId: row.userId,
        userName: row.userName,
        password: '',
        userType: row.userType,
        state: row.state
      }
      this.open = true
      this.title = '修改用户'
      this.form.password = ''
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.form.userType = this.userType[0].value
      this.open = true
      this.title = '添加用户'
    },
    /** 表单提交 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.userId !== undefined) {
            updateUserInfo(this.form).then(response => {
              this.$message({
                message: '修改成功',
                type: 'success'
              })
              this.open = false
              this.getUserList()
            })
          } else {
            const publicKey = getPubKey()
            this.form.password = encrypt(this.form.password, publicKey)
            addUserInfo(this.form).then(response => {
              this.$message({
                message: '新增成功',
                type: 'success'
              })
              this.open = false
              this.getUserList()
            })
          }
        }
      })
    },
    /** 表单重置 */
    cancel() {
      this.open = false
      this.reset()
    },
    /** 表单重置 */
    reset() {
      this.form = {
        userId: undefined,
        userName: undefined,
        password: undefined,
        userType: '0',
        state: '0'
      }
      if (this.$refs['form']) {
        this.$refs['form'].resetFields()
      }
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss">
</style>
