<template>
  <!-- 用户管理 -->
  <div class="app-container">
    <TableModel :formLabel="formLabel" :showOperation="true" :showRightTools="true" ref="userTableRef"
                :columnsList="columnsList" :request-api="listUser" :sendParams="sendParams"
    >
      <template #form="{ queryParams }">
        <el-form-item prop="deptId" style="width: 240px;">
          <treeselect v-model="queryParams.deptId" :options="treeDataList" placeholder="请选择部门" value-key="id"
                      :disable-branch-nodes="false" noChildrenText="没有数据了" noOptionsText="没有数据了" noResultsText="没有搜索结果"
          />
        </el-form-item>
      </template>
      <template slot="btn">
        <el-button plain size="mini" type="primary" icon="el-icon-plus" v-hasPermi="['system:user:add']"
                   @click="handleAdd">
          新增
        </el-button>

        <el-button plain size="mini" type="success" icon="el-icon-download" v-hasPermi="['system:user:import']"
                   @click="handleModelExport">
          模板下载
        </el-button>

        <el-button plain size="mini" type="warning" icon="el-icon-upload2" v-hasPermi="['system:user:import']"
                   @click="handleBatchImport">
          批量导入
        </el-button>
      </template>
      <template slot="deptName" slot-scope="{ data }">
        <span>{{ data.dept.deptName || '--' }}</span>
      </template>
      <template slot="roleName" slot-scope="{ data }">
        <span>{{ data.roles[0].roleName || '--'}}</span>
      </template>
      <template slot="handle" slot-scope="{ data }">
        <el-button plain size="mini" type="primary" icon="el-icon-edit" v-hasPermi="['system:user:edit']"
                   @click="handleUpdate(data)">
          修改
        </el-button>
        <el-button plain size="mini" type="danger" icon="el-icon-delete" v-hasPermi="['system:user:remove']"
                   @click="handleDelete(data)" v-if="!data.admin">
          删除
        </el-button>
        <el-button plain size="mini" style="color: #039088"
                   @click="handleResetPwd(data)" v-hasPermi="['system:user:remove']">
          重置密码
        </el-button>
      </template>
    </TableModel>
    <!-- 新增/编辑 -->
    <UserForm v-if="isflag" :isAdd="isAdd" :rowData="row" @handleQuery="handleQuery" :title="title"
              @closeDialog="closeDialog" @showColose="showColose" :dataForm="row" :disabled="loading" :width="600" />
    <ImportExcelDialog
      :visible.sync="importExcelDialogVisible"
      ref="importExcelDialog"
      title="用户数据导入"
      :upload-url="importExcelDialogUploadUrl"
      @upload-success="handleImportSuccess"
      @close="handleImportClose"
      :maxFileTips="maxFileTips"
    />
  </div>
</template>

<script>
import TableModel from '@/components/TableModel'
import { columnsList, formLabel } from './config'
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import {
  listUser,
  delUser,
  resetUserPwd,
  importUser,
  downloadUserImportTemplate
} from '@/api/system/user'
import { getDeptSelectApi,getRoleSelectApi } from '@/api/select'
import UserForm from './profile/userForm'
import ImportExcelDialog from '@/views/common/ImportExcelDialog'
import { downloadFileWithLoading } from '@/utils/download'
import {decryptWithSM4} from "@/utils/sm";

const IMPORT_URL = process.env.VUE_APP_BASE_API + 'smartPlatform/system/user/importUserBatch';

export default {
  name: 'DataClassManage',
  components: {
    TableModel,
    UserForm,
    Treeselect,
    ImportExcelDialog
  },
  data() {
    return {
      formLabel,
      columnsList,
      listUser,
      title: "",
      isflag: false,
      isAdd: '',
      row: {},
      sendParams:{teamId:decryptWithSM4(this.$route.query.teamId || '')},
      loading: false,
      treeDataList:[],
      maxFileTips: '20MB', // 文件大小限制提示
      importExcelDialogVisible: false, // 导入弹窗显示状态
      importExcelDialogUploadUrl:  IMPORT_URL // 导入接口完整地址
    }
  },

  created() {
    this.initData();

  },

  methods: {
    async initData() {
      await getDeptSelectApi().then(res => {
        this.treeDataList = this.convertToVueTree(res.data);
      });
      const item = this.formLabel.find(item => item.f_model === 'roleId');
      await getRoleSelectApi().then(res => {
        res.data.forEach(item => {
          item.label = item.name;
          item.value = item.id;
        });
        this.$set(item, 'f_selList', res.data)
      });
    },

    /** 新增按钮操作 */
    handleAdd() {
      this.title = "新增";
      this.isAdd = 'add';
      this.isflag = true;
    },
    closeDialog() {
      this.isflag = false;
    },
    showColose() {
      this.isflag = false;
    },
    /** 修改操作 */
    handleUpdate(row) {
      this.title = "修改";
      this.isAdd = 'edit';
      this.row = row;
      this.isflag = true;
    },
    /* 搜索操作 */
    handleQuery() {
      this.$refs.userTableRef.getTableList()
    },
    /** 删除操作 */
    handleDelete(row) {
      this.$modal.confirm(`是否确认删除此数据项？`).then(() => {
        // 显示加载遮罩
        this.$modal.loading("正在删除，请稍候...");
        delUser({ userId: row.userId }).then(res => {
          this.$modal.closeLoading();
          if (res.code === 200) {
            this.$modal.msgSuccess("删除成功");
            this.handleQuery();
          } else {
            this.$modal.msgError(res.msg);
          }
        }).catch(error => {
          this.$modal.closeLoading();
          this.$modal.msgError(error);
        });
      }).catch(() => {
        // 用户取消删除，不需要处理
      });
    },
    // 树数据过滤 - 支持无限层级转换
    convertToVueTree(data, level = 1) {
      if (!data || !Array.isArray(data)) {
        return []
      }

      return data.map(item => {
        const node = {
          id: item.deptId,
          label: item.deptName,
        }

        if (item.children && Array.isArray(item.children) && item.children.length > 0) {
          if (level < 3) {
            const children = this.convertToVueTree(item.children, level + 1)
            if (children.length > 0) node.children = children
          }
        }

        return node
      })
    },
    /** 重置密码按钮操作 */
    handleResetPwd(row) {
      this.$prompt('请输入"' + row.userName + '"的新密码', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        closeOnClickModal: false,
        /* inputPattern:
            /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[^\w\d\s]).{8,20}$/,
        inputErrorMessage:
            '用户密码长度必须介于 8 和 20 之间，且包含大小写字母、数字和特殊字符', */
        /* inputValidator: (value) => {
            if (/<|>|"|'|\||\\/.test(value)) {
                return '不能包含非法字符：< > " \' \\\ |'
            }
        }, */
      })
        .then(({ value }) => {
          resetUserPwd(row.userId, value).then((response) => {
            this.$modal.msgSuccess('修改成功，新密码是：' + value)
          })
        })
        .catch(() => {})
    },

    handleModelExport() {
      downloadFileWithLoading(
        'smartPlatform/commonDownload/downLoadUserModel', // 模板下载接口路径
        '用户导入模板.xlsx', // 下载的文件名
        '正在下载模板，请稍候...', // 加载提示文字
      )
    },

    // 打开导入弹窗
    handleBatchImport() {
      this.importExcelDialogVisible = true;
    },

    // 导入成功回调
    handleImportSuccess() {
      this.$modal.msgSuccess("导入成功");
      this.handleQuery(); // 刷新列表
    },

    // 导入弹窗关闭回调
    handleImportClose() {
      this.importExcelDialogVisible = false;
      this.handleQuery(); // 刷新列表
    }
  },
}
</script>
