<template>
  <!-- 用户管理 -->
  <div class="home">
    <actionBar :operateList="operateList" :formList="formList" :ruleForm="searchRuleForm" @openModel="openModel"
      @searchProtocol="searchProtocol"></actionBar>
    <div class="card_content_interior">
      <div class="left_interior">
        <el-tree style="max-width: 250px" :data="companyData" :props="defaultProps" highlight-current
          check-on-click-node node-key="id" :expand-on-click-node="false" @node-click="handleNodeClick">
          <!-- <template #default="{ node, data }"> -->
          <el-tooltip :disabled="showTitle" effect="dark" :content="tooltipTitle" placement="top"
            slot-scope="{ node, data }">
            <span class="span-ellipsis" @mouseover="onShowNameTips">{{node.label}}</span>
          </el-tooltip>
          <!-- </template> -->
        </el-tree>
      </div>
      <div class="right_interior">
        <!-- 表单 -->
        <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>
    </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 {
    getCompanyUser,
    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 "./interiorUserTable.js";
  export default {
    name: 'UserManagement',
    components: {
      actionBar,
      tables,
      pagination,
      forms
    },
    data() {
      return {
        defaultProps: {
          children: 'children',
          label: 'name'
        },
        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: '',
        },
        confirmLoading: false,
        selectingData: {},
        companyData: [],
        companyId: '',
        showTitle: false,
        tooltipTitle: '',
      }
    },
    mounted() {
      this.getCompany()
      this.getList()
    },
    methods: {
      onShowNameTips(e) {
        var target = e.target;
        let textLength = target.clientWidth;
        let containerLength = target.scrollWidth;
        if (textLength < containerLength) {
          this.tooltipTitle = e.target.innerText;
          this.showTitle = false;
        } else {
          this.showTitle = true;
        }
      },
      // 点击公司获取用户列表
      handleNodeClick(data) {
        this.companyId = data.id
        this.getList()
      },
      // 搜索
      searchProtocol(value) {
        this.Pagination.PageIndex = 1
        this.searchValue = value
        this.getList()
      },
      // 获取用户列表
      getList(ID) {
        var params = {
          page: this.Pagination.PageIndex,
          pageSize: this.Pagination.PageSize,
          companyId: this.companyId,
          ...this.searchValue
        }
        getCompanyUser(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,
                id: item.id,
                parentId: item.parentId,
              }
              arrList.push(commodity)
            })

            function formatToTree(ary, pid) {
              return ary
                .filter((item) =>
                  // 如果没有父id（第一次递归的时候）将所有父级查询出来
                  // 这里认为 item.parentId === 1 就是最顶层 需要根据业务调整
                  pid === undefined ? item.parentId === 0 : item.parentId === pid
                )
                .map((item) => {
                  // 通过父节点ID查询所有子节点
                  item.children = formatToTree(ary, item.id);
                  return item;
                });
            }
            let arrfag = formatToTree(arr)
            this.companyData = arrfag
            if (this.operationType) {
              let arrui = formatToTree(arrList)
              this.optionMatching(arrui, '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'
              });
              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" scoped>
  .card_content_interior {
    display: flex;
    border-radius: 5px;
    background-color: rgba(95, 99, 127, 0.3);
    box-shadow: 0 2px 4px rgba(0, 0, 0, .05);
    margin-top: 15px;
  }

  .left_interior {
    width: 20%;
    padding: 10px 0px;
    border-right: 1px solid rgba(95, 99, 127, 0.6);
  }

  .right_interior {
    width: 80%;
  }

  .span-ellipsis {
    width: 100%;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
    margin-right: 20px;
  }
</style>
