<template>
  <!-- 用户管理 -->
  <div class="home">
    <actionBar :operateList="operateList" :formList="formList" :ruleForm="searchRuleForm" @openModel="openModel"
      @searchProtocol="searchProtocol"></actionBar>
    <div class="card_content">
      <!-- 表单 -->
      <tables :suspension="true" :tableList="tableList" :tableData="tableData" @buttonData="buttonData"></tables>
      <!-- 分页 -->
      <div v-if="Total">
        <pagination :total="Total" :currentPage="Pagination.PageIndex" @changeSize="changeSize"
          @changeCurrent="changeCurrent">
        </pagination>
      </div>
    </div>
    <el-dialog :title="staffTitle" :visible.sync="staffDialogVisible" width="600px" :close-on-click-modal="false"
      @close="closeDialog">
      <forms ref="childRules" :formNewList="formRuleList" :ruleForm="ruleForm" labelWidth="100px">
      </forms>
      <span slot="footer" class="dialog-footer">
        <el-button plain @click="staffDialogVisible = false">取 消</el-button>
        <el-button type="primary" :loading="confirmLoading" @click="handleAdd">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  import {
    getUser,
    getCompanyAll,
    getUserDetails,
    addUser,
    putUser,
    putResetUser,
    delUser
  } from '@/api/user'
  import actionBar from '@/components/actionBar'
  import tables from '@/components/tables'
  import pagination from '@/components/pagination'
  import forms from '@/components/forms'
  import {
    formRules,
    employee,
    formRulesil
  } from "./userTable.js";
  export default {
    name: 'UserManagement',
    components: {
      actionBar,
      tables,
      pagination,
      forms
    },
    data() {
      return {
        operateList: [{
          type: 'add',
          title: '添加用户',
          icon: 'el-icon-plus',
        }],
        formList: [{
          type: 'input',
          label: '姓名',
          field: 'name',
          placeholder: '姓名',
        }],
        searchRuleForm: {
          name: '',
          type: '',
        },
        searchValue: {},
        Pagination: {
          PageIndex: 1,
          PageSize: 10,
        },
        Total: 0,
        tableData: [],
        operationType: '',
        tableList: employee(),
        staffTitle: '添加',
        staffDialogVisible: false,
        formRuleList: [],
        ruleForm: {
          deptId: '',
          name: '',
          username: '',
          phone: '',
          newPassword: '',
          password: '',
          type: null,
        },
        confirmLoading: false,
        selectingData: {},
      }
    },
    mounted() {
      this.getList()
    },
    methods: {
      // 搜索
      searchProtocol(value) {
        this.Pagination.PageIndex = 1
        this.searchValue = value
        this.getList()
      },
      // 获取用户列表
      getList() {
        var params = {
          page: this.Pagination.PageIndex,
          pageSize: this.Pagination.PageSize,
          ...this.searchValue
        }
        getUser(params).then(res => {
          if (res.code == 200) {
            this.tableData = res.data.list
            this.Total = res.data.count
          }
        })
      },
      // 获取公司
      getCompany() {
        getCompanyAll().then(res => {
          if (res.code == 200) {
            const arrList = []
            const arr = res.data.list
            arr.forEach((item, index) => {
              const commodity = {
                label: item.name,
                value: item.id,
              }
              arrList.push(commodity)
            })
            this.optionMatching(arrList, 'deptId')
          }
        })
      },
      // 选项赋值
      optionMatching(value, field) {
        this.formRuleList.forEach((item, index) => {
          if (item.field == field) {
            item.options = value
          }
        })
        this.$nextTick(() => {
          if (value.length == 1) {
            this.ruleForm.deptId = String(value[0].value)
          }
        })
      },
      // 弹窗表单添加
      handleAdd() {
        let flag = this.$refs['childRules'].validateForm();
        if (flag) {
          if (this.operationType == 'add') {
            if (this.ruleForm.password == this.ruleForm.newPassword) {
              this.confirmLoading = true
              var params = {
                ...this.ruleForm
              }
              params.deptId = Number(params.deptId)
              delete params.newPassword
              addUser(params).then(res => {
                if (res.code == 200) {
                  this.$message({
                    message: '操作成功',
                    type: 'success'
                  });
                  this.getList()
                }
                this.staffDialogVisible = false
                this.confirmLoading = false
              }).catch(() => {
                this.confirmLoading = false
              })
            } else {
              this.$message.error('输入两次密码不相同');
            }
          } else if (this.operationType == 'edit') {
            this.confirmLoading = true
            var params = {
              id: this.selectingData.id,
              name: this.ruleForm.name,
              phone: this.ruleForm.phone,
              type: this.ruleForm.type,
            }
            putUser(params).then(res => {
              if (res.code == 200) {
                this.$message({
                  message: '操作成功',
                  type: 'success'
                });
                this.getList()
              }
              this.staffDialogVisible = false
              this.confirmLoading = false
            }).catch(() => {
              this.confirmLoading = false
            })
          }
        } else {
          this.$message.error('表单信息不完整，请继续填写完整');
        }
      },
      buttonData(row, type) {
        this.selectingData = row
        this.operationType = type
        if (type == 'edit') {
          this.getCompany()
          const dataList = formRulesil();
          this.formRuleList = dataList;
          this.staffTitle = '编辑'
          this.staffDialogVisible = true
          setTimeout(() => {
            this.$nextTick(() => {
              this.ruleForm.name = row.nickName
              this.ruleForm.phone = row.phone
              this.ruleForm.type = row.type
            })
          })
        } else if (type == 'reset') {
          this.resetPasswords(row.id)
        } else if (type == 'del') {
          this.deleteUser(row.id)
        }
      },
      openModel(type) {
        const dataList = formRules();
        this.formRuleList = dataList;
        this.getCompany()
        this.staffTitle = '添加'
        this.staffDialogVisible = true
        this.operationType = type
      },
      // 删除用户
      deleteUser(id) {
        this.$confirm('此操作将永久删除用户, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          delUser({
            id: id,
          }).then(res => {
            if (res.code == 200) {
              this.$message({
                message: '操作成功',
                type: 'success'
              });
              const precisePage = Math.ceil((this.Total - 1) / this.Pagination.PageSize)
              this.Pagination.PageIndex = this.Pagination.PageIndex > precisePage ? precisePage : this
                .Pagination.PageIndex
              this.Pagination.PageIndex = this.Pagination.PageIndex < 1 ? 1 : this.Pagination.PageIndex
              this.getList()
            }
          })
        }).catch(() => {});
      },
      // 重置密码
      resetPasswords(userID) {
        this.$prompt('请输入新密码', '重置密码', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputPattern: /^\S{6,}$/,
          inputErrorMessage: '长度不能小于6个字符'
        }).then(({
          value
        }) => {
          putResetUser({
            id: userID,
            password: value
          }).then(res => {
            if (res.code == 200) {
              this.$message({
                type: 'success',
                message: '重置成功'
              });
            }
          })
        }).catch(() => {});
      },
      changeSize(val) {
        this.Pagination.PageSize = val
        this.getList()
      },
      changeCurrent(val) {
        this.Pagination.PageIndex = val
        this.getList()
      },
      // 清空表单
      closeDialog() {
        this.$refs.childRules.resetCheck();
      }
    }
  }
</script>
<style lang="scss">
</style>
