<template>
  <el-row>
    <el-col :span="5">
      <div class="box">
        <el-scrollbar>
          <basic-container>
            <avue-tree :option="treeOption" :data="treeData" @node-click="nodeClick" />
          </basic-container>
        </el-scrollbar>
      </div>
    </el-col>
    <el-col :span="19">
      <basic-container>
        <avue-crud
          :option="userOption"
          v-model:search="search"
          :table-loading="loading"
          :data="data"
          ref="crud"
          v-model="form"
          :permission="permissionList"
          @row-del="rowDel"
          @row-update="rowUpdate"
          @row-save="rowSave"
          :before-open="beforeOpen"
          v-model:page="page"
          @search-change="searchChange"
          @search-reset="searchReset"
          @selection-change="selectionChange"
          @current-change="currentChange"
          @size-change="sizeChange"
          @refresh-change="refreshChange"
          @on-load="onLoad"
        >
          <template #menu-left>
            <el-button
              v-if="permission.user_add && !auditMode"
              type="primary"
              icon="el-icon-plus"
              @click="openUserDialog('add')"
              >新 增
            </el-button>
            <el-button
              type="danger"
              plain
              icon="el-icon-delete"
              v-if="permission.user_delete && !auditMode"
              @click="handleDelete"
              >删除
            </el-button>
            <el-button
              type="primary"
              plain
              icon="el-icon-operation"
              v-if="userInfo.authority.includes('admin') && !auditMode"
              @click="handleAudit"
              >审 核
            </el-button>
            <el-button
              type="success"
              plain
              icon="el-icon-check"
              v-if="userInfo.authority.includes('admin') && auditMode"
              @click="handleAuditPass"
              >通 过
            </el-button>
            <el-button
              type="danger"
              plain
              icon="el-icon-close"
              v-if="userInfo.authority.includes('admin') && auditMode"
              @click="handleAuditRefuse"
              >拒 绝
            </el-button>
            <el-button
              type="primary"
              plain
              icon="el-icon-refresh-left"
              v-if="userInfo.authority.includes('admin') && auditMode"
              @click="handleAuditBack"
              >返 回
            </el-button>
            <el-button
              type="info"
              plain
              v-if="permission.user_role && !auditMode"
              icon="el-icon-user"
              @click="handleGrant"
              >角色配置
            </el-button>
            <el-dropdown
              v-if="userInfo.authority.includes('admin') && !auditMode"
              @command="handleDataManageCommand"
              style="margin-left: 10px"
            >
              <el-button type="primary" plain icon="el-icon-files">
                数据管理<i class="el-icon-arrow-down el-icon--right"></i>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="import">
                    <el-icon><upload /></el-icon>
                    导入数据
                  </el-dropdown-item>
                  <el-dropdown-item command="export">
                    <el-icon><download /></el-icon>
                    导出数据
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
          <template #menu-right>
            <el-button
              v-if="userInfo.authority.includes('admin') && !auditMode"
              icon="el-icon-document"
              @click="$refs.authLog.openAuthLog()"
              >认证日志
            </el-button>
            <el-button
              v-if="userInfo.authority.includes('admin') && !auditMode"
              icon="el-icon-lock"
              @click="$refs.authLock.openLockLog()"
              >锁定管理
            </el-button>
          </template>
          <template #menu="{ row, index, size }">
            <el-link
              type="primary"
              v-if="this.permission.user_view"
              @click.stop="$refs.crud.rowView(row, index)"
              >查看
            </el-link>
            <el-link
              type="primary"
              v-if="this.permission.user_edit"
              @click.stop="openUserDialog('edit', row)"
              >编辑
            </el-link>
            <el-dropdown @command="command => handleDropdownCommand(command, row, index)">
              <el-link type="primary">更 多 </el-link>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="setLeader" v-if="userInfo.authority.includes('admin')">
                    {{ row.isLeader === 1 ? '取消主管' : '设置主管' }}
                  </el-dropdown-item>
                  <el-dropdown-item command="grantRole" v-if="permission.user_role">
                    角色配置
                  </el-dropdown-item>
                  <el-dropdown-item command="authLog" v-if="userInfo.authority.includes('admin')">
                    认证日志
                  </el-dropdown-item>
                  <el-dropdown-item command="lockUser" v-if="userInfo.authority.includes('admin')">
                    锁定账号
                  </el-dropdown-item>
                  <el-dropdown-item command="resetPassword" v-if="permission.user_reset">
                    密码重置
                  </el-dropdown-item>
                  <el-dropdown-item command="setPassword" v-if="permission.user_reset">
                    修改密码
                  </el-dropdown-item>
                  <el-dropdown-item command="delete" v-if="this.permission.user_delete">
                    删除用户
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
          <template #roleName="{ row }">
            <el-tag>{{ row.roleName }}</el-tag>
          </template>
          <template #deptName="{ row }">
            <el-tag>{{ row.deptName }}</el-tag>
          </template>
        </avue-crud>

        <el-dialog
          v-model="userDialog"
          :title="userDialogMode === 'add' ? '新增用户' : '编辑用户'"
          width="90%"
          top="5vh"
          append-to-body
          destroy-on-close
          class="user-edit-dialog"
        >
          <template #header>
            <span class="dialog-title">{{ userDialogMode === 'add' ? '新增用户' : '编辑用户' }}</span>
          </template>
          <el-form ref="userFormRef" :model="form" :rules="userRules" label-position="right" label-width="120px">
            <el-row :gutter="20">
              <el-col :span="6"><el-form-item label="账号名" prop="account"><el-input v-model="form.account" /></el-form-item></el-col>
              <el-col :span="6"><el-form-item label="姓名" prop="realName"><el-input v-model="form.realName" /></el-form-item></el-col>
              <el-col :span="6"><el-form-item label="手机号" prop="phone"><el-input v-model="form.phone" /></el-form-item></el-col>
              <el-col :span="6"><el-form-item label="邮箱"><el-input v-model="form.email" /></el-form-item></el-col>
              <el-col :span="6"><el-form-item label="性别"><el-select v-model="form.sex" class="full-width"><el-option label="男" :value="1" /><el-option label="女" :value="2" /><el-option label="未知" :value="3" /></el-select></el-form-item></el-col>
              <el-col :span="6"><el-form-item label="岗位" prop="postId"><el-tree-select v-model="form.postId" :data="postList" :props="{ label: 'postName', value: 'id' }" check-strictly class="full-width" /></el-form-item></el-col>
              <el-col :span="6"><el-form-item label="所属组织" prop="deptId"><el-tree-select v-model="form.deptId" :data="permissionDeptTree" :props="{ label: 'title', value: 'id' }" multiple check-strictly show-checkbox class="full-width" /></el-form-item></el-col>
              <el-col :span="6"><el-form-item label="工号"><el-input v-model="form.code" /></el-form-item></el-col>
              <el-col :span="6"><el-form-item label="人员类别"><el-select v-model="form.personCategory" class="full-width"><el-option label="内部员工" :value="1" /><el-option label="承运商" :value="2" /></el-select></el-form-item></el-col>
              <el-col :span="18"><el-form-item label="数据权限范围"><el-radio-group v-model="form.dataScopeRange"><el-radio :value="1">仅所属组织</el-radio><el-radio :value="2">全部组织</el-radio><el-radio :value="3">自定义</el-radio></el-radio-group></el-form-item></el-col>
              <el-col :span="18" :offset="6"><el-form-item label="数据层级范围"><el-radio-group v-model="form.dataLevelRange"><el-radio :value="1">包含下级</el-radio><el-radio :value="2">仅本级</el-radio></el-radio-group></el-form-item></el-col>
              <el-col :span="24"><el-form-item label="备注"><el-input v-model="form.remark" type="textarea" :rows="3" maxlength="200" show-word-limit /></el-form-item></el-col>
            </el-row>
          </el-form>
          <el-tabs class="user-permission-tabs">
            <el-tab-pane label="已拥有角色">
              <el-table :data="formRoleList" border>
                <el-table-column type="index" label="序号" width="70" />
                <el-table-column prop="id" label="角色编号" />
                <el-table-column prop="title" label="角色名称" />
                <el-table-column label="操作" width="90"><template #default="{ row }"><el-link type="danger" @click="removeFormRole(row.id)">删除</el-link></template></el-table-column>
              </el-table>
            </el-tab-pane>
            <el-tab-pane v-if="form.dataScopeRange === 3" label="数据权限">
              <el-tree :data="permissionDeptTree" show-checkbox node-key="id" :default-checked-keys="form.dataScopeDeptIds || []" :props="{ label: 'title', children: 'children' }" @check="handleDataScopeCheck" />
            </el-tab-pane>
            <el-tab-pane label="客商权限">
              <div class="permission-toolbar customer-toolbar"><el-checkbox v-model="form.includeNewCustomer" :true-value="1" :false-value="0">包含新增的客商</el-checkbox></div>
              <el-table ref="customerTable" :data="customerList" border @selection-change="handleCustomerSelection"><el-table-column type="selection" width="55" /><el-table-column prop="customerCode" label="客商编码" /><el-table-column prop="fullName" label="客商名称" /></el-table>
            </el-tab-pane>
          </el-tabs>
          <template #footer><span class="dialog-footer"><el-button type="primary" @click="submitUserForm">保存</el-button><el-button @click="userDialog = false">返回</el-button><el-button v-if="userDialogMode === 'edit'" @click="resetDialogPassword">重置密码</el-button><el-button @click="handleAddRole">添加角色</el-button></span></template>
        </el-dialog>

        <!-- 用户角色配置 -->
        <el-dialog title="用户角色配置" append-to-body v-model="roleBox" width="345px">
          <el-row
            justify="space-between"
            align="middle"
            style="margin-bottom: 12px; background: #f5f7fa; padding: 6px 10px; border-radius: 4px"
          >
            <span style="display: inline-flex; align-items: center">
              <el-switch
                v-model="roleLinked"
                active-text="节点联动"
                size="small"
                @change="handleLinkedChange('treeRole')"
              />
              <el-tooltip
                content="开启后勾选父节点会自动勾选所有子节点，关闭则可独立勾选任意节点"
                placement="top"
              >
                <el-icon style="margin-left: 4px; color: #909399; cursor: pointer"
                  ><el-icon-question-filled
                /></el-icon>
              </el-tooltip>
            </span>
            <el-button-group>
              <el-button size="small" plain @click="handleSelectAll('treeRole', roleGrantList)"
                >全选</el-button
              >
              <el-button
                size="small"
                plain
                @click="handleInvertSelect('treeRole', roleGrantList, roleLinked)"
                >反选</el-button
              >
            </el-button-group>
          </el-row>
          <el-tree
            :data="roleGrantList"
            show-checkbox
            :check-strictly="!roleLinked"
            default-expand-all
            node-key="id"
            ref="treeRole"
            :default-checked-keys="roleTreeObj"
            :props="props"
          >
          </el-tree>
          <template #footer>
            <span class="dialog-footer">
              <el-button @click="roleBox = false">取 消</el-button>
              <el-button type="primary" @click="submitRole">确 定</el-button>
            </span>
          </template>
        </el-dialog>

        <!-- 用户数据导入 -->
        <el-dialog title="用户数据导入" append-to-body v-model="excelBox" width="555px">
          <avue-form :option="excelOption" v-model="excelForm" :upload-after="uploadAfter">
            <template #excelTemplate>
              <el-button type="primary" @click="handleTemplate">
                点击下载<i class="el-icon-download el-icon--right"></i>
              </el-button>
            </template>
          </avue-form>
        </el-dialog>

        <!-- 管理员修改密码 -->
        <el-dialog title="修改密码" append-to-body v-model="passwordBox" width="460px">
          <el-form
            ref="passwordFormRef"
            :model="passwordForm"
            :rules="passwordRules"
            label-width="auto"
          >
            <el-form-item label="账号名">
              <el-input v-model="passwordForm.account" disabled />
            </el-form-item>
            <el-form-item label="新密码" prop="password">
              <el-input v-model="passwordForm.password" type="password" show-password />
            </el-form-item>
            <el-form-item label="确认密码" prop="password2">
              <el-input v-model="passwordForm.password2" type="password" show-password />
            </el-form-item>
          </el-form>
          <template #footer>
            <span class="dialog-footer">
              <el-button @click="passwordBox = false">取 消</el-button>
              <el-button type="primary" @click="submitPassword">确 定</el-button>
            </span>
          </template>
        </el-dialog>

        <!-- 认证日志组件 -->
        <auth-log ref="authLog" />
        <!-- 认证锁定配置组件 -->
        <auth-lock ref="authLock" @lock-success="onLoad(page)" />
      </basic-container>
    </el-col>
  </el-row>
</template>

<script>
import {
  getList,
  getUser,
  remove,
  update,
  add,
  grant,
  resetPassword,
  setPassword,
  auditPass,
  auditRefuse,
  setLeader,
  getLeaderList,
  getCustomerOptions,
} from '@/api/system/user';
import { exportBlob } from '@/api/common';
import { getDeptTree } from '@/api/system/dept';
import { getRoleTree } from '@/api/system/role';
import { getPostList } from '@/api/system/post';
import { mapGetters } from 'vuex';
import { h } from 'vue';
import { getToken } from '@/utils/auth';
import { downloadXls } from '@/utils/util';
import NProgress from 'nprogress';
import 'nprogress/nprogress.css';
import func from '@/utils/func';
import { sensitive } from '@/utils/sensitive';
import { excelOption, treeOption, userOption } from '@/option/system/user';
import AuthLog from './authlog.vue';
import AuthLock from './authlock.vue';

export default {
  components: { AuthLog, AuthLock },
  data() {
    return {
      form: {},
      userDialog: false,
      userDialogMode: 'add',
      search: {},
      sensitiveManager: null,
      roleBox: false,
      roleLinked: false,
      roleFormMode: false,
      grantUserId: '',
      excelBox: false,
      passwordBox: false,
      initFlag: true,
      auditMode: false,
      selectionList: [],
      query: {},
      loading: true,
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0,
      },
      props: {
        label: 'title',
        value: 'key',
      },
      roleGrantList: [],
      roleTreeObj: [],
      treeDeptId: '',
      treeData: [],
      permissionDeptTree: [],
      postList: [],
      customerList: [],
      treeOption: treeOption,
      userOption: userOption(this),
      data: [],
      passwordForm: {},
      passwordRules: {
        password: [
          { required: true, message: '请输入新密码', trigger: 'blur' },
          { min: 6, max: 32, message: '密码长度在6到32个字符', trigger: 'blur' },
        ],
        password2: [
          { required: true, message: '请再次输入新密码', trigger: 'blur' },
          { validator: this.validatePassword2, trigger: 'blur' },
        ],
      },
      userRules: {
        account: [{ required: true, message: '请输入账号名', trigger: 'blur' }],
        realName: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
        phone: [{ required: true, message: '请输入手机号', trigger: 'blur' }],
        deptId: [{ required: true, message: '请选择所属组织', trigger: 'change' }],
      },
      excelForm: {},
      excelOption: excelOption,
    };
  },
  watch: {
    'excelForm.isCovered'() {
      if (this.excelForm.isCovered !== '') {
        const column = this.findColumn(this.excelOption.column, 'excelFile');
        column.action = `/blade-system/user/import-user?isCovered=${this.excelForm.isCovered}`;
      }
    },
  },
  computed: {
    ...mapGetters(['userInfo', 'permission']),
    permissionList() {
      return {
        addBtn: this.validData(this.permission.user_add, false),
        viewBtn: false,
        delBtn: false,
        editBtn: false,
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach(ele => {
        ids.push(ele.id);
      });
      return ids.join(',');
    },
    formRoleList() {
      const selected = new Set(func.split(this.form.roleId || '').map(String));
      const roles = [];
      const walk = nodes =>
        (nodes || []).forEach(node => {
          if (selected.has(String(node.id))) roles.push(node);
          walk(node.children);
        });
      walk(this.roleGrantList);
      return roles;
    },
  },
  mounted() {
    this.initData(this.userInfo.tenantId || this.website.tenantId);
  },
  created() {
    // 创建脱敏工具实例
    this.sensitiveManager = sensitive.create({
      fields: ['phone', 'email'], // 配置需要脱敏的字段
    });
  },
  methods: {
    nodeClick(data) {
      this.treeDeptId = data.id;
      this.page.currentPage = 1;
      this.onLoad(this.page);
    },
    handleDropdownCommand(command, row, index) {
      if (command === 'setLeader') {
        this.handleSetLeader(row);
      } else if (command === 'grantRole') {
        this.handleGrantForRow(row);
      } else if (command === 'authLog') {
        this.$refs.authLog.openUserAuthLog(row.id, row.name);
      } else if (command === 'lockUser') {
        this.$refs.authLock.openLockUser(row.id, row.account);
      } else if (command === 'resetPassword') {
        this.handleResetForRow(row);
      } else if (command === 'setPassword') {
        this.handlePasswordForRow(row);
      } else if (command === 'delete') {
        this.$refs.crud.rowDel(row, index);
      }
    },
    handleResetForRow(row) {
      this.$confirm(`确定将账号【${row.account}】的密码重置为随机密码?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          return resetPassword(row.id);
        })
        .then(res => {
          this.showResetPassword(res.data.data);
        });
    },
    handleDataManageCommand(command) {
      if (command === 'import') {
        this.handleImport();
      } else if (command === 'export') {
        this.handleExport();
      }
    },
    handleSetLeader(row) {
      const tip = row.isLeader === 1 ? '确定取消用户的主管职务?' : '确定设置用户为主管职务?';
      const message = row.isLeader === 1 ? '取消主管成功!' : '设置主管成功!';
      this.$confirm(tip, {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          return setLeader(row.id);
        })
        .then(() => {
          this.$message({
            type: 'success',
            message: message,
          });
          this.onLoad(this.page);
        });
    },
    initData(tenantId) {
      getRoleTree(tenantId).then(res => {
        this.roleGrantList = res.data.data;
        const column = this.findColumn(this.userOption.group, 'roleId');
        column.dicData = res.data.data;
      });
      getDeptTree(tenantId).then(res => {
        this.permissionDeptTree = res.data.data;
        const column = this.findColumn(this.userOption.group, 'deptId');
        column.dicData = res.data.data;
      });
      getPostList(tenantId).then(res => {
        this.postList = res.data.data;
        const column = this.findColumn(this.userOption.group, 'postId');
        column.dicData = res.data.data;
      });
      getLeaderList(tenantId).then(res => {
        const column = this.findColumn(this.userOption.group, 'leaderId');
        column.dicData = res.data.data;
      });
      getCustomerOptions().then(res => {
        this.customerList = res.data.data || [];
      });
    },
    submitRole() {
      const roleList = this.$refs.treeRole.getCheckedKeys().join(',');
      if (this.roleFormMode) {
        this.form.roleId = roleList;
        this.roleBox = false;
        this.roleFormMode = false;
        return;
      }
      grant(this.grantUserId, roleList).then(() => {
        this.roleBox = false;
        this.$message({
          type: 'success',
          message: '操作成功!',
        });
        this.onLoad(this.page);
      });
    },
    handleAddRole() {
      this.roleFormMode = true;
      this.roleTreeObj = func.split(this.form.roleId || '');
      this.roleLinked = false;
      getRoleTree(this.userInfo.tenantId).then(res => {
        this.roleGrantList = res.data.data;
        this.roleBox = true;
        this.$nextTick(() => this.applyCheckedKeys('treeRole', this.roleTreeObj));
      });
    },
    removeFormRole(roleId) {
      this.form.roleId = func
        .split(this.form.roleId || '')
        .filter(id => String(id) !== String(roleId));
    },
    handleDataScopeCheck(_, checked) {
      this.form.dataScopeDeptIds = checked.checkedKeys;
    },
    handleCustomerSelection(rows) {
      this.form.customerIds = rows.map(row => row.id);
    },
    openUserDialog(mode, row = {}) {
      this.userDialogMode = mode;
      if (mode === 'add') {
        this.form = {
          account: '',
          realName: '',
          phone: '',
          email: '',
          sex: 3,
          postId: '',
          deptId: [],
          code: '',
          personCategory: 1,
          dataScopeRange: 1,
          dataLevelRange: 1,
          remark: '',
          roleId: '',
          dataScopeDeptIds: [],
          customerIds: [],
          includeNewCustomer: 0,
        };
        this.userDialog = true;
        this.$nextTick(() => this.$refs.userFormRef && this.$refs.userFormRef.clearValidate());
        return;
      }
      getUser(row.id).then(res => {
        const user = res.data.data;
        this.form = {
          ...user,
          deptId: func.split(user.deptId || ''),
          postId: func.split(user.postId || '')[0] || '',
          roleId: func.join(user.roleId || ''),
          dataScopeDeptIds: user.dataScopeDeptIds || [],
          customerIds: user.customerIds || [],
          includeNewCustomer: user.includeNewCustomer || 0,
          personCategory: user.personCategory || 1,
          dataScopeRange: user.dataScopeRange || 1,
          dataLevelRange: user.dataLevelRange || 1,
        };
        this.sensitiveManager.saveInitialData(this.form);
        this.userDialog = true;
        this.$nextTick(() => {
          this.$refs.userFormRef && this.$refs.userFormRef.clearValidate();
          (this.form.customerIds || []).forEach(id => {
            const customer = this.customerList.find(item => String(item.id) === String(id));
            if (customer) this.$refs.customerTable && this.$refs.customerTable.toggleRowSelection(customer, true);
          });
        });
      });
    },
    submitUserForm() {
      this.$refs.userFormRef.validate(valid => {
        if (!valid) return;
        const row = {
          ...this.form,
          deptId: func.join(this.form.deptId),
          postId: func.join(this.form.postId),
          roleId: func.join(this.form.roleId),
          leaderId: func.join(this.form.leaderId),
        };
        const request = this.userDialogMode === 'add' ? add(row) : update(this.sensitiveManager.getSubmitData(row));
        request.then(() => {
          this.userDialog = false;
          this.onLoad(this.page);
          this.$message.success('操作成功!');
        });
      });
    },
    resetDialogPassword() {
      this.handleResetForRow(this.form);
    },
    rowSave(row, done, loading) {
      row.deptId = func.join(row.deptId);
      row.roleId = func.join(row.roleId);
      row.postId = func.join(row.postId);
      row.leaderId = func.join(row.leaderId);
      add(row).then(
        () => {
          this.initFlag = false;
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!',
          });
          done();
        },
        error => {
          window.console.log(error);
          loading();
        }
      );
    },
    rowUpdate(row, index, done, loading) {
      row.deptId = func.join(row.deptId);
      row.roleId = func.join(row.roleId);
      row.postId = func.join(row.postId);
      row.leaderId = func.join(row.leaderId);
      // 获取需要提交的数据
      const submitData = this.sensitiveManager.getSubmitData(row);
      update(submitData).then(
        () => {
          this.initFlag = false;
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!',
          });
          done();
        },
        error => {
          window.console.log(error);
          loading();
        }
      );
    },
    rowDel(row) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          return remove(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!',
          });
        });
    },
    searchReset() {
      this.query = {};
      this.treeDeptId = '';
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning('请选择至少一条数据');
        return;
      }
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          return remove(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!',
          });
          this.$refs.crud.toggleSelection();
        });
    },
    handleAudit() {
      this.auditMode = true;
      this.onLoad(this.page, this.query);
    },
    handleAuditPass() {
      if (this.selectionList.length === 0) {
        this.$message.warning('请选择至少一条数据');
        return;
      }
      this.$confirm('确定将选择数据通过审核?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          return auditPass(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!',
          });
          this.$refs.crud.toggleSelection();
        });
    },
    handleAuditRefuse() {
      if (this.selectionList.length === 0) {
        this.$message.warning('请选择至少一条数据');
        return;
      }
      this.$confirm('确定将选择数据拒绝审核?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          return auditRefuse(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!',
          });
          this.$refs.crud.toggleSelection();
        });
    },
    handleAuditBack() {
      this.auditMode = false;
      this.onLoad(this.page, this.query);
    },
    handleReset() {
      if (this.selectionList.length === 0) {
        this.$message.warning('请选择至少一条数据');
        return;
      }
      this.$confirm('确定将选择账号密码重置为随机密码?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          return resetPassword(this.ids);
        })
        .then(res => {
          this.showResetPassword(res.data.data);
          this.$refs.crud.toggleSelection();
        });
    },
    showResetPassword(passwordMap) {
      const passwordList = Object.keys(passwordMap || {}).map(account =>
        h('div', null, `${account}：${passwordMap[account]}`)
      );
      this.$alert(h('div', null, passwordList), '密码重置成功，请立即保存', {
        confirmButtonText: '我已保存',
        type: 'success',
      });
    },
    handleGrant() {
      if (this.selectionList.length === 0) {
        this.$message.warning('请选择至少一条数据');
        return;
      }
      this.roleTreeObj = [];
      this.roleLinked = false;
      this.grantUserId = this.ids;
      if (this.selectionList.length === 1) {
        this.roleTreeObj = this.selectionList[0].roleId.split(',');
      }
      getRoleTree().then(res => {
        this.roleGrantList = res.data.data;
        this.roleBox = true;
        this.$nextTick(() => this.applyCheckedKeys('treeRole', this.roleTreeObj));
      });
    },
    handleGrantForRow(row) {
      this.roleTreeObj = row.roleId ? row.roleId.split(',') : [];
      this.roleLinked = false;
      this.grantUserId = row.id;
      getRoleTree().then(res => {
        this.roleGrantList = res.data.data;
        this.roleBox = true;
        this.$nextTick(() => this.applyCheckedKeys('treeRole', this.roleTreeObj));
      });
    },
    getAllNodeKeys(nodes) {
      let keys = [];
      nodes.forEach(node => {
        keys.push(node.id);
        if (node.children && node.children.length > 0) {
          keys = keys.concat(this.getAllNodeKeys(node.children));
        }
      });
      return keys;
    },
    getLeafKeys(nodes) {
      let keys = [];
      nodes.forEach(node => {
        if (!node.children || node.children.length === 0) {
          keys.push(node.id);
        } else {
          keys = keys.concat(this.getLeafKeys(node.children));
        }
      });
      return keys;
    },
    handleSelectAll(treeRef, dataList) {
      const tree = this.$refs[treeRef];
      if (!tree) return;
      const allKeys = this.getAllNodeKeys(dataList);
      tree.setCheckedKeys(allKeys);
    },
    handleInvertSelect(treeRef, dataList, isLinked) {
      const tree = this.$refs[treeRef];
      if (!tree) return;
      const checkedKeys = new Set(tree.getCheckedKeys());
      if (isLinked) {
        const leafKeys = this.getLeafKeys(dataList);
        const invertedKeys = leafKeys.filter(key => !checkedKeys.has(key));
        tree.setCheckedKeys(invertedKeys);
      } else {
        const allKeys = this.getAllNodeKeys(dataList);
        const invertedKeys = allKeys.filter(key => !checkedKeys.has(key));
        tree.setCheckedKeys(invertedKeys);
      }
    },
    handleLinkedChange(treeRef) {
      const tree = this.$refs[treeRef];
      if (!tree) return;
      const checkedKeys = tree.getCheckedKeys();
      const halfCheckedKeys = tree.getHalfCheckedKeys();
      this.$nextTick(() => {
        tree.setCheckedKeys([...checkedKeys, ...halfCheckedKeys]);
      });
    },
    // el-tree 会把 setCheckedKeys 的入参记录为默认勾选集并在树数据重载时回放，
    // 复用的树实例需在打开配置时整体覆盖勾选状态，避免残留上一次配置的勾选
    applyCheckedKeys(treeRef, keys) {
      const tree = this.$refs[treeRef];
      if (!tree) return;
      tree.setCheckedKeys(keys);
    },
    handlePasswordForRow(row) {
      this.passwordForm = {
        userId: row.id,
        account: row.account,
        password: '',
        password2: '',
      };
      this.passwordBox = true;
      this.$nextTick(() => {
        this.$refs.passwordFormRef && this.$refs.passwordFormRef.clearValidate();
      });
    },
    validatePassword2(rule, value, callback) {
      if (value !== this.passwordForm.password) {
        callback(new Error('两次输入密码不一致!'));
      } else {
        callback();
      }
    },
    submitPassword() {
      this.$refs.passwordFormRef.validate(valid => {
        if (!valid) {
          return;
        }
        setPassword(
          this.passwordForm.userId,
          this.passwordForm.password,
          this.passwordForm.password2
        ).then(() => {
          this.passwordBox = false;
          this.$message({ type: 'success', message: '密码修改成功!' });
        });
      });
    },
    handleImport() {
      this.excelBox = true;
    },
    uploadAfter(res, done, loading, column) {
      window.console.log(column);
      this.excelBox = false;
      this.refreshChange();
      done();
    },
    handleExport() {
      const account = func.toStr(this.search.account);
      const realName = func.toStr(this.search.realName);
      this.$confirm('是否导出用户数据?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        NProgress.start();
        exportBlob(
          `/blade-system/user/export-user?${
            this.website.tokenHeader
          }=${getToken()}&account=${account}&realName=${realName}`
        ).then(res => {
          downloadXls(res.data, `用户数据表${this.$dayjs().format('YYYY-MM-DD')}.xlsx`);
          NProgress.done();
        });
      });
    },
    handleTemplate() {
      exportBlob(
        `/blade-system/user/export-template?${this.website.tokenHeader}=${getToken()}`
      ).then(res => {
        downloadXls(res.data, '用户数据模板.xlsx');
      });
    },
    beforeOpen(done, type) {
      if (['edit', 'view'].includes(type)) {
        getUser(this.form.id).then(res => {
          this.form = res.data.data;
          if (this.form.hasOwnProperty('deptId')) {
            this.form.deptId = func.split(this.form.deptId);
          }
          if (this.form.hasOwnProperty('roleId')) {
            this.form.roleId = func.split(this.form.roleId);
          }
          if (this.form.hasOwnProperty('postId')) {
            this.form.postId = func.split(this.form.postId);
          }
          if (this.form.hasOwnProperty('leaderId')) {
            this.form.leaderId = func.split(this.form.leaderId);
          }
          if (this.form.sex === -1) {
            this.form.sex = '';
          }
          // 保存初始脱敏数据
          this.sensitiveManager.saveInitialData(this.form);
        });
      }
      this.initFlag = true;
      done();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      this.loading = true;
      const queryParams = { ...this.query, ...params };
      if (this.auditMode) {
        queryParams.status = 0;
      }
      getList(page.currentPage, page.pageSize, queryParams, this.treeDeptId).then(res => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
    },
  },
};
</script>

<style>
.box {
  height: 800px;
}

.el-scrollbar {
  height: 100%;
}

.box .el-scrollbar__wrap {
  overflow: scroll;
}

.user-permission-tabs {
  width: 100%;
  margin-top: 8px;
}

.user-edit-dialog .dialog-title {
  display: inline-flex;
  align-items: center;
  font-size: 16px;
  font-weight: 600;
}

.user-edit-dialog .dialog-title::before {
  width: 4px;
  height: 18px;
  margin-right: 8px;
  background: #409eff;
  content: '';
}

.user-edit-dialog .el-form-item {
  margin-bottom: 16px;
}

.user-edit-dialog .el-form-item__label {
  white-space: nowrap;
}

.user-edit-dialog .el-radio-group {
  white-space: nowrap;
}

.full-width {
  width: 100%;
}

.user-permission-tabs .el-tabs__header {
  margin-bottom: 12px;
}

.permission-toolbar {
  display: flex;
  justify-content: flex-end;
  margin-bottom: 12px;
}

.customer-toolbar {
  justify-content: flex-start;
}

.avue-dialog .el-form-item__label {
  white-space: nowrap;
}

.avue-dialog .el-radio-group {
  white-space: nowrap;
}
</style>
