<template>
  <div class="charge-box">
    <div class="routename">{{ $route.meta.title }}</div>
    <div class="charge-tools">
      <el-form ref="SerchForm" :inline="true">
        <el-form-item label="账号:" style="margin-left: 35px;">
          <el-input v-model.trim="queryParams.userAccount" placeholder="请输入账号" clearable />
        </el-form-item>

        <el-form-item label="账号状态:" style="margin-left: 50px;">
          <el-select v-model="queryParams.state" clearable placeholder="请选择状态">
            <el-option label="启用" value="1" />
            <el-option label="禁用" value="0" />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" class="serch actve" @click="handleQuery">查询</el-button>
          <el-button type="primary" class="serch" @click="resetForm">重置</el-button>
        </el-form-item>

      </el-form>
    </div>
    <div class="charge-table">
      <div class="adduser">
        <el-button type="primary" class="addbtn" @click="handleAddRole">新增账号</el-button>
      </div>
      <div class="charge-table-bottom">
        <el-table
          :data="UserList"
          :header-cell-style="{
            background: '#1d283e',
            borderColor: '#2f3c86',
            height: '36px',
            lineHeight: '36px',
            color:'white',
            fontSize: '16px',
          }"
          stripe
          style="width: 100%"
          :default-sort="{prop: 'date', order: 'descending'}"
        >
          <el-table-column label="序号" type="index" :index="indexMethod" width="300" />
          <el-table-column prop="userAccount" label="账号" />

          <el-table-column prop="updateTime" label="创建时间" sortable>
            <template slot-scope="{row}">
              {{ row.updateTime }}
            </template>
          </el-table-column>
          <el-table-column label="状态">
            <template slot-scope="{row}">
              <el-badge is-dot class="item" :class="{disable:row.state === 0}">{{ row.state === 0 ? '停用' : '启用' }}</el-badge>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="160">
            <template v-if="scope.row.userAccount !== 'admin'" slot-scope="scope">
              <el-button type="primary" class="handle" size="small" @click="handleEdit(scope.row)">编辑</el-button>
              <el-button type="primary" class="handle" size="small" @click="handleDelete(scope.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div class="pageblock">
        <el-pagination
          :current-page="queryParams.page"
          :page-sizes="[10, 20, 30, 40]"
          :page-size="queryParams.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
    <!--新增账号弹窗-->
    <div class="rolemanage">
      <el-dialog
        :title="dialogType==='edit'?'编辑账号':'新增账号'"
        :visible.sync="dialogUserVisible"
        :destroy-on-close="true"
        @close="dialogClose"
      >
        <el-form
          ref="ruleForm"
          v-loading="loading"
          :model="formData"
          :rules="rules"
        >
          <el-form-item label="账号：" :label-width="formLabelWidth" prop="userAccount">
            <el-input v-model.trim="formData.userAccount" autocomplete="off" placeholder="请输入账号" :disabled="dialogType==='edit'" />
          </el-form-item>
          <el-form-item v-if="dialogType==='edit'" label="密码：" :label-width="formLabelWidth">
            <el-button type="primary" class="reset" @click="resetpwd">重置密码</el-button>
          </el-form-item>
          <el-form-item v-if="dialogType==='new' || pwdIsShow" label="默认密码：" :label-width="formLabelWidth">
            <el-input v-model="formData.pwd" autocomplete="off" placeholder="88888888" disabled />
          </el-form-item>
          <el-form-item label="状态" :label-width="formLabelWidth">
            <el-select v-model="formData.state" placeholder="请选择状态">
              <el-option label="启用" value="1" />
              <el-option label="禁用" value="0" />
            </el-select>
          </el-form-item>
          <el-form-item label="备注：" :label-width="formLabelWidth" prop="remark">
            <el-input v-model="formData.remark" type="textarea" :rows="4" placeholder="请输入30字以内" maxlength="30" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button class="exit" @click="dialogUserVisible = false">取 消</el-button>
          <el-button type="primary" class="save" @click="AddUserinfo">确 定</el-button>
        </div>
      </el-dialog>
    </div>
    <!--新增账号弹窗结束-->
  </div>
</template>

<script>
import './permission.scss'
import { addUserinfo, getUserlist, deleteUser, updateUser, resetpwd } from '@/api/user'
export default {
  name: 'UpdatePassword',
  components: {},
  data() {
    return {
      UserList: [],
      dialogUserVisible: false, // 弹窗显示
      // 新增账号弹窗
      formData: {
        userAccount: '',
        state: '1',
        pwd: '88888888',
        remark: '',
        id: 0
      },
      formLabelWidth: '120px',
      // 新增账号弹窗结束
      dialogType: 'new', // 按钮类型(new、edit)
      loading: false,
      // 表单校验
      rules: {
        userAccount: [
          { required: true, message: '账号不能为空', trigger: 'blur' },
          { min: 4, max: 16, message: '长度在 4 到 16 个字符', trigger: 'blur' }
        ],
        remark: [
          { min: 0, max: 30, message: '长度最大30个字符', trigger: 'blur' }
        ]
      },
      pwdIsShow: false, // 默认密码显示
      total: 0, // 总条数
      queryParams: {
        page: 1, // 当前页
        pageSize: 10, // 每页条数
        state: undefined,
        userAccount: undefined,
        orderByField: undefined, // 排序字段
        orderByWays: 'desc'// 排序方式
      }
    }
  },
  mounted() {
    this.getUserlist()
  },
  methods: {
    // 添加用户、编辑用户
    AddUserinfo() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          // 添加用户
          if (this.dialogType === 'new') {
            addUserinfo(this.formData).then(res => {
              if (res.code === 0) {
                this.loading = false
                this.dialogUserVisible = false
                this.$message({
                  type: 'success',
                  message: '操作成功！'
                })
                this.getUserlist()
              } else {
                this.loading = false
                return this.$message.error(res.msg)
              }
            })
          }
          // 修改用户
          else {
            const updateFrom = this.formData
            delete updateFrom.pwd
            console.log(updateFrom)
            updateUser(updateFrom).then(res => {
              if (res.code === 0) {
                this.loading = false
                this.dialogUserVisible = false
                this.$message({
                  type: 'success',
                  message: '操作成功！'
                })
                this.getUserlist()
              } else {
                this.loading = false
                return this.$message.error(res.msg)
              }
            })
          }
        }
      })
    },
    // 获取用户列表
    getUserlist() {
      const params = this.queryParams
      getUserlist(params).then(res => {
        this.UserList = res.data.records
        this.total = res.data.total
        // console.log(res.data)
      })
    },
    /** 分页下一页 */
    handleSizeChange(val) {
      this.queryParams.pageSize = val
      this.getUserlist()
    },
    /** 分页选择页数 */
    handleCurrentChange(val) {
      this.queryParams.page = val
      this.getUserlist()
    },
    // 添加、编辑、删除账号
    handleAddRole() {
      this.dialogType = 'new'
      this.dialogUserVisible = true
    },
    handleEdit(row) {
      this.formData.userAccount = row.userAccount
      this.formData.state = row.state + ''
      this.formData.remark = row.remark
      this.formData.id = row.id
      this.dialogType = 'edit'
      this.dialogUserVisible = true
    },
    handleDelete(userId) {
      this.$confirm('删除数据将丢失,请确认是否删除', '确认删除', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          await deleteUser({ id: userId })
          this.$message({
            type: 'success',
            message: '删除成功！'
          })
          this.getUserlist()
        })
        .catch(err => { console.error(err) })
    },
    // 序号自定义
    indexMethod(index) {
      return '1010' + (index + 1)
    },
    // 清空表单数据
    dialogClose() {
      this.formData.userAccount = ''
      this.pwdIsShow = false
    },
    // 重置密码
    resetpwd() {
      this.$confirm('确认初始化密码？', '重置密码', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          await resetpwd({ id: this.formData.id, userAccount: this.formData.userAccount })
          this.$message({
            type: 'success',
            message: '重置成功！'
          })
          this.pwdIsShow = true
          setTimeout(() => {
            this.dialogUserVisible = false
          }, 2000)
        })
        .catch(err => { console.error(err) })
    },
    // 搜索
    handleQuery() {
      if (this.queryParams.userAccount === '') {
        this.queryParams.userAccount = undefined
      }
      this.getUserlist()
    },
    // 搜索重置
    resetForm() {
      this.queryParams.userAccount = undefined
      this.queryParams.state = undefined
    }
  }
}
</script>
<style lang="scss" scoped>
.routename {
  padding: 25px 10px;
  font-size: 20px;
  color: white;
  font-weight: 600;
}

.adduser {
  padding: 20px 0;

  .addbtn {
    background-color: #91fdb9;
    color: #111827;
    border: none;
    font-size: 15px;
    font-weight: 600;
    height: 40px;
    width: 110px;
  }
  .addbtn:hover{
      background-color: #69b889;
      border-color: #69b889;
      color: white;
  }
}
</style>
