<script setup>
import { getToken } from "@/utils/auth";
import {
  changeUserStatus,
  listUser,
  resetUserPwd,
  delUser,
  getUser,
  updateUser,
  addUser,
  deptTreeSelect,
} from "../../../views/system/user/api";
import { baseModelOptions, baseFilterOptions } from "./options";
const table = ref();
const deptName = ref("");
const { proxy } = getCurrentInstance();
const router = useRouter();
const state = reactive({
  baseModelOptions: baseModelOptions(),
  baseFilterOptions: baseFilterOptions(),
  columnCount: 2,
  title: "用户管理",
  baseModelName: "用户",
  // addBtnName: '添加UserNew',
  editBtnName: "",
  delBtnName: "",
  primaryKey: "userId",
  deleteKey: "userIds",
  getTableFn: listUser,
  addFn: addUser,
  editFn: updateUser,
  deleteFn: delUser,
  hideRightToolbar: true,
  detailFn: getUser,
  showEditBtn: true,
  showDeleteBtn: true,
  showFilter: true,
  // rowControl: {
  //   showEditBtn: false,
  //   showDelBtn: false
  // },
  permission: {
    //菜单管理中添加权限
    add: "system:user:add",
    edit: "system:user:edit",
    delete: "system:user:remove",
    detail: "system:user:query",
  },
  showLoading: false,
  pageInfo: { total: 0, base: { limit: 8, current: 1 } },
  deptOptions: [],
  baseQuery: {},
  showPassword: false,
  pasData: [],
  pswTitle: "",
  columns: [
    { key: 1, label: '用户编号', visible: true },
    { key: 2, label: '用户名称', visible: true },
    { key: 3, label: '用户昵称', visible: true },
    { key: 4, label: '部门', visible: true },
    { key: 5, label: '手机号', visible: true },
    { key: 6, label: '状态', visible: true },
    { key: 7, label: '创建时间', visible: true },
  ],
  beforeShowEdit: (row, res) => {
    return {
      ...row,
      postIds: res.postIds,
      roleIds: res.roleIds,
    };
  },
});
/*** 用户导入参数 */
const upload = reactive({
  // 是否显示弹出层（用户导入）
  open: false,
  // 弹出层标题（用户导入）
  title: "",
  // 是否禁用上传
  isUploading: false,
  // 是否更新已经存在的用户数据
  updateSupport: 0,
  // 设置上传的请求头部
  headers: { Authorization: "Bearer " + getToken() },
  // 上传的地址
  url: import.meta.env.VITE_APP_BASE_API + "/system/user/importData",
});
// 归属部门
deptTreeSelect().then((res) => {
  state.baseModelOptions = proxy.$util.setOptions({
    relation: {
      key: "value", //options的key
      name: "label", //options的name
      resKey: "id", //对应返回结果的key
      resName: "label", //对应返回结果的name
    },
    data: state.baseModelOptions, //待赋值数据源
    key: "deptId", //配置项的key
    hasChildren: true,
    attrName: "data", //配置项attribute中 options的属性key
    res, //返回结果
    path: "res.data", //返回结果取值路径
  });
});
getUser().then((res) => {
  // 岗位
  state.baseModelOptions = proxy.$util.setOptions({
    relation: {
      key: "value", //options的key
      name: "label", //options的name
      resKey: "postId", //对应返回结果的key
      resName: "postName", //对应返回结果的name
    },
    data: state.baseModelOptions, //待赋值数据源
    key: "postIds", //配置项的key
    hasChildren: true,
    attrName: "options", //配置项attribute中 options的属性key
    res, //返回结果
    path: "res.posts", //返回结果取值路径
  });
  // 角色
  state.baseModelOptions = proxy.$util.setOptions({
    relation: {
      key: "value", //options的key
      name: "label", //options的name
      resKey: "roleId", //对应返回结果的key
      resName: "roleName", //对应返回结果的name
    },
    data: state.baseModelOptions, //待赋值数据源
    key: "roleIds", //配置项的key
    hasChildren: true,
    attrName: "options", //配置项attribute中 options的属性key
    res, //返回结果
    path: "res.roles", //返回结果取值路径
  });
});

/** 通过条件过滤节点  */
const filterNode = (value, data) => {
  if (!value) return true;
  return data.label.indexOf(value) !== -1;
};
/** 根据名称筛选部门树 */
watch(deptName, (val) => {
  proxy.$refs["deptTreeRef"].filter(val);
});
const getDeptTree = () => {
  deptTreeSelect().then((res) => {
    state.deptOptions = res.data;
  });
};
const handleStatusChange = (row) => {
  changeUserStatus(row.userId, row.status).then((res) => {
    if (res.code == 200) {
      proxy.$modal.msgSuccess("修改成功");
    } else {
      proxy.$modal.msgError(res.msg);
    }
  });
};
//修改密码
const handleResetPwd = (row) => {
  proxy
    .$prompt('请输入"' + row.userName + '"的新密码', "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      closeOnClickModal: false,
      inputPattern: /^.{5,20}$/,
      inputErrorMessage: "用户密码长度必须介于 5 和 20 之间",
    })
    .then(({ value }) => {
      resetUserPwd(row.userId, value).then((response) => {
        proxy.$modal.msgSuccess("修改成功，新密码是：" + value);
      });
    })
    .catch(() => { });
};
const handleAuthRole = (row) => {
  router.push("/system/user-auth/role/" + userId);
};
const channel = () => {
  upload.title = "用户导入";
  upload.open = true;
};
/** 导入按钮操作 */
const handleImport = () => {
  upload.title = "用户导入";
  upload.open = true;
};
/** 下载模板操作 */
const importTemplate = () => {
  proxy.download(
    "system/user/importTemplate",
    {},
    `user_template_${new Date().getTime()}.xlsx`
  );
};
/**文件上传中处理 */
const handleFileUploadProgress = (event, file, fileList) => {
  upload.isUploading = true;
};
/** 文件上传成功处理 */
const handleFileSuccess = (response, file, fileList) => {
  upload.open = false;
  upload.isUploading = false;
  proxy.$refs["uploadRef"].handleRemove(file);
  proxy.$alert(
    "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
    response.msg +
    "</div>",
    "导入结果",
    { dangerouslyUseHTMLString: true }
  );
  getList();
};
/** 提交上传文件 */
const submitFileForm = () => {
  proxy.$refs["uploadRef"].submit();
};
const handleExport = () => {
  // let params = table.value.filterRef.getFilterParams()
  // proxy.download("system/user/export", params,`user_${new Date().getTime()}.xlsx`);
};
const handleNodeClick = (row) => {
  state.baseQuery = {
    deptId: row.id,
  };
  const { getTableData } = table.value;
  getTableData();
};
onMounted(() => {
  getDeptTree();
});
</script>

<template>
  <div class="app-container" >
    <el-row :gutter="20">
      <el-col :span="4" :xs="24">
        <div class="head-container">
          <el-input v-model="deptName" placeholder="请输入部门名称" clearable prefix-icon="Search"
            style="margin-bottom: 20px" />
        </div>
        <div class="head-container">
          <el-tree :data="state.deptOptions" :props="{ label: 'label', children: 'children' }"
            :expand-on-click-node="false" :filter-node-method="filterNode" ref="deptTreeRef" highlight-current
            default-expand-all @node-click="handleNodeClick" />
        </div>
      </el-col>
      <!-- 列表 -->
      <el-col :span="20" :xs="24">
        <!-- 用户导入对话框 -->
        <el-dialog :title="upload.title" v-model="upload.open" width="400px" append-to-body>
          <el-upload ref="uploadRef" :limit="1" accept=".xlsx, .xls" :headers="upload.headers"
            :action="upload.url + '?updateSupport=' + upload.updateSupport" :disabled="upload.isUploading"
            :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false" drag>
            <el-icon class="el-icon--upload">
              <upload-filled />
            </el-icon>
            <div class="el-upload__text">
              将文件拖到此处，或<em>点击上传</em>
            </div>
            <template #tip>
              <div class="el-upload__tip text-center">
                <div class="el-upload__tip">
                  <el-checkbox v-model="upload.updateSupport" />是否更新已经存在的用户数据
                </div>
                <span>仅允许导入xls、xlsx格式文件。</span>
                <el-link type="primary" :underline="false" style="font-size: 12px; vertical-align: baseline"
                  @click="importTemplate">下载模板</el-link>
              </div>
            </template>
          </el-upload>
          <template #footer>
            <div class="dialog-footer">
              <el-button type="primary" @click="submitFileForm">确 定</el-button>
              <el-button @click="upload.open = false">取 消</el-button>
            </div>
          </template>
        </el-dialog>
        <BaseTablePage :tableOptions="state" ref="table" @import="channel" @export="handleExport">
          <template v-slot:column>
            <el-table-column v-if="state.columns[0].visible" label="用户编号" align="center" key="userId" prop="userId" />
            <el-table-column v-if="state.columns[1].visible" label="用户名称" align="center" key="userName" prop="userName" />
            <el-table-column v-if="state.columns[2].visible" label="用户昵称" align="center" key="nickName" prop="nickName" />
            <el-table-column v-if="state.columns[3].visible" label="部门" align="center" key="deptName" prop="dept.deptName" />
            <el-table-column v-if="state.columns[4].visible" label="手机号码" align="center" key="phonenumber" prop="phonenumber" width="120" />
            <el-table-column v-if="state.columns[5].visible" label="状态" align="center" key="status">
              <template #default="scope">
                <el-switch v-model="scope.row.status" active-value="0" inactive-value="1"
                  @change="handleStatusChange(scope.row)"></el-switch>
              </template>
            </el-table-column>
            <el-table-column v-if="state.columns[6].visible" label="创建时间" align="center" prop="createTime" width="160">
              <template #default="scope">
                <span>{{ parseTime(scope.row.createTime) }}</span>
              </template>
            </el-table-column>
          </template>
          <template #control="baseScope" >
            <el-table-column label="操作" width="300" >
              <template #default="scope">
                <el-button type="text" v-if="scope.row.userId !== 1" icon="Edit"
                  @click="baseScope.handleEdit(scope.$index, scope.row)" v-hasPermi="['system:user:edit']">
                  修改
                </el-button>
                <el-button type="text" v-if="scope.row.userId !== 1" icon="Delete"
                  @click="baseScope.deleteTableData(scope.$index, scope.row)"
                  v-hasPermi="['system:user:remove']">删除</el-button>
                <el-button v-if="scope.row.userId !== 1" type="text" icon="Key" @click="handleResetPwd(scope.row)"
                  v-hasPermi="['system:user:resetPwd']">重置密码</el-button>
                <!-- <el-tooltip
                  content="分配角色"
                  placement="top"
                  v-if="scope.row.userId !== 1"
                >
                  <el-button
                    type="text"
                    icon="CircleCheck"
                    @click="handleAuthRole(scope.row)"
                    v-hasPermi="['system:user:edit']"
                  ></el-button>
                </el-tooltip> -->
              </template>
            </el-table-column>
          </template>
        </BaseTablePage>
      </el-col>
    </el-row>
  </div>
</template>

<style scoped></style>
