<template>
  <div class="koi-flex">
    <KoiCard>
      <!-- 搜索条件 -->
      <el-form v-show="showSearch" :inline="true" @submit.native.prevent="handleListPage">
        <el-form-item label="登录名" prop="loginName">
          <el-input
            v-model="searchParams.userName"
            clearable
            placeholder="请输入登录账号"
            style="width: 200px"
          ></el-input>
        </el-form-item>

        <el-form-item>
          <PopoverWrapper>
            <el-form v-show="showSearch" label-width="80px">
              <el-form-item label="归属部门" prop="deptId">
                <el-tree-select
                  v-model="searchParams.deptId"
                  :data="deptOptions"
                  :props="props"
                  :render-after-expand="false"
                  :teleported="false"
                  check-strictly
                  clearable
                  style="width: 320px"
                />
              </el-form-item>
              <el-form-item label="手机号" prop="phonenumber">
                <el-input
                  v-model="searchParams.phonenumber"
                  clearable
                  placeholder="请输入手机号"
                  style="width: 320px"
                ></el-input>
              </el-form-item>
              <el-form-item label="登录时间" prop="loginTime">
                <el-date-picker
                  v-model="dateRange"
                  end-placeholder="结束日期"
                  range-separator="至"
                  start-placeholder="开始日期"
                  type="datetimerange"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  :teleported="false"
                  style="width: 300px"
                />
              </el-form-item>
            </el-form>
          </PopoverWrapper>
          <el-button v-throttle="handleSearch" icon="search" plain type="primary">搜索</el-button>
          <el-button v-throttle="resetSearch" icon="refresh" plain type="danger">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 表格头部按钮 -->
      <el-row :gutter="10">
        <el-col :span="1.5">
          <el-button v-auth="['system:user:add']" icon="plus" plain type="primary" @click="handleAdd()">新增</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button v-auth="['system:user:edit']" :disabled="single" icon="edit" plain type="success"
                     @click="handleUpdate()">修改
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button v-auth="['system:user:remove']" :disabled="multiple" icon="delete" plain type="danger"
                     @click="handleDelete()">删除
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button v-auth="['system:user:export']" icon="download" plain type="warning" @click="handleExport">导出
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button v-auth="['system:user:import']" icon="upload" plain type="info" @click="handleImport">导入</el-button>
        </el-col>
        <KoiToolbar v-model:showSearch="showSearch" @refreshTable="handleListPage"></KoiToolbar>
      </el-row>

      <div class="h-20px"></div>
      <el-table
        v-loading="loading"
        :data="tableList.slice((searchParams.pageNum - 1) * searchParams.pageSize, searchParams.pageNum * searchParams.pageSize)"
        border
        empty-text="暂时没有数据哟"
        @selection-change="handleSelectionChange"
      >
        <el-table-column align="center" type="selection" width="55"/>
        <el-table-column align="center" label="序号" prop="userId" type="index" width="80px"></el-table-column>
        <el-table-column :show-overflow-tooltip="true" align="center" label="昵称" prop="nickName"></el-table-column>
        <el-table-column :show-overflow-tooltip="true" align="center" label="登录名称" prop="userName"></el-table-column>
        <el-table-column :show-overflow-tooltip="true" align="center" label="手机号" prop="phonenumber"
                         width="150px"></el-table-column>
        <el-table-column align="center" label="性别" prop="sex" width="80px">
          <template #default="scope">
            <KoiTag :tagOptions="koiDicts.sys_user_sex" :value="scope.row.sex"></KoiTag>
          </template>
        </el-table-column>
        <el-table-column align="center" label="部门" prop="deptName">
          <template #default="scope">
            <span>{{ scope.row?.dept?.deptName }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="用户状态" prop="status" width="100px">
          <template #default="scope">
            <el-switch
              v-model="scope.row.status"
              :inline-prompt="true"
              active-text="启用"
              active-value="0"
              inactive-text="停用"
              inactive-value="1"
              @change="handleSwitch(scope.row)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column align="center" label="创建时间" prop="createTime" width="180px"></el-table-column>
        <el-table-column :show-overflow-tooltip="true" align="center" label="备注" prop="remark" width="200px"></el-table-column>
        <el-table-column align="center" fixed="right" label="操作" width="150">
          <template #default="{ row }">
            <el-tooltip content="修改" placement="top">
              <el-button
                circle
                icon="Edit"
                plain
                type="primary"
                @click="handleUpdate(row)"
              ></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button
                v-auth="['system:user:remove']"
                circle
                icon="Delete"
                plain
                type="danger"
                @click="handleDelete(row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <div class="h-20px"></div>
      <!-- 分页 -->
      <Pagination :queryParams="searchParams" :total="total" :getList="handleListPage" />

      <!-- 添加 OR 修改 -->
      <KoiDrawer
        ref="koiDrawerRef"
        :loading="confirmLoading"
        :title="title"
        @koiCancel="handleCancel"
        @koiConfirm="handleConfirm"
      >
        <template #content>
          <el-form ref="formRef" :model="form" :rules="rules" label-width="80px" status-icon>
            <el-form-item label="用户姓名" prop="nickName">
              <el-input v-model="form.nickName" clearable placeholder="请输入用户名称"/>
            </el-form-item>
            <el-form-item label="手机号" prop="phonenumber">
              <el-input v-model="form.phonenumber" placeholder="请输入手机号"></el-input>
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="form.email" placeholder="请输入邮箱"></el-input>
            </el-form-item>
            <el-form-item v-if="!form.userId" label="登录名" prop="userName">
              <el-input v-model="form.userName" maxlength="20" placeholder="请输入登录名"/>
            </el-form-item>
            <el-form-item v-if="!form.userId" label="用户密码" prop="password">
              <el-input v-model="form.password" maxlength="20" placeholder="请输入用户密码" show-password type="password"/>
            </el-form-item>
            <el-form-item label="用户性别" prop="sex">
              <el-select v-model="form.sex" placeholder="请选择性别">
                <el-option
                  v-for="dict in koiDicts.sys_user_sex"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="归属部门" prop="deptId">
              <el-tree-select
                v-model="form.deptId"
                :data="deptOptions"
                check-strictly
                :props="props"
                :render-after-expand="false"
              />
            </el-form-item>
            <el-form-item label="所属岗位">
              <el-select v-model="form.postIds" placeholder="请选择岗位">
                <el-option
                  v-for="item in postOptions"
                  :key="item.postId"
                  :disabled="item.status == 1"
                  :label="item.postName"
                  :value="item.postId"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="所属角色" prop="roleIds">
              <el-select v-model="form.roleIds" placeholder="请选择角色">
                <el-option
                  v-for="item in roleOptions"
                  :key="item.roleId"
                  :disabled="item.status == 1"
                  :label="item.roleName"
                  :value="item.roleId"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="用户状态" prop="status">
              <el-select v-model="form.status" clearable placeholder="请选择用户状态">
                <el-option label="启用" value="0"/>
                <el-option label="停用" value="1"/>
              </el-select>
            </el-form-item>
            <el-form-item label="用户备注" prop="remark">
              <el-input v-model="form.remark" :rows="5" placeholder="请输入用户备注" type="textarea"/>
            </el-form-item>
          </el-form>
        </template>
      </KoiDrawer>

      <!-- 上传文件 -->
      <KoiDialog
        ref="koiDialogRef"
        :loading="confirmLoading"
        footerHidden
        title="上传文件"
        @koiCancel="handleCancel"
        @koiConfirm="handleConfirm"
      >
        <template #content>
          <el-upload
            ref="uploadRef"
            :action="url + '?updateSupport=' + updateSupport"
            :headers="{
              Authorization: 'Bearer ' + token
            }"
            :on-success="onSuccess"
            accept=".xlsx, .xls"
            class="upload-demo"
            drag
            limit="1"
          >
            <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" style="display: flex;align-items: center;gap: 5px">
                <el-checkbox/>
                是否更新已经存在的用户数据
              </div>
              <span style="font-size: 12px">仅允许导入xls、xlsx格式文件。</span>
              <el-link :underline="false" style="font-size:12px;vertical-align: baseline;" type="primary" @click="importTemplate">
                下载模板
              </el-link>
            </template>
          </el-upload>
        </template>
      </KoiDialog>
    </KoiCard>
  </div>
</template>

<script lang="ts" name="user" setup>
import {nextTick, onMounted, reactive, ref} from "vue";
import {koiMsgBox, koiMsgError, koiMsgSuccess, koiMsgWarning, koiNoticeError, koiNoticeSuccess} from "@/utils/koi.ts";
import {addUser, changeUserStatus, delUser, getUser, listUser, treeselect, updateUser} from "@/api/system/user/index.ts";
import {useKoiDict} from "@/hooks/dicts/index.ts";
import {download} from "@/utils/request.ts";
import {getToken} from "@/utils/storage.ts";
import useAuthStore from "@/stores/modules/auth.ts";

// 表格加载动画Loading
const loading = ref(false);
// 是否显示搜索表单[默认显示]
const showSearch = ref<boolean>(true); // 默认显示搜索条件
// 表格数据
const tableList = ref<any>([]);
const {koiDicts} = useKoiDict(["sys_user_sex"]);
const url = import.meta.env.VITE_SERVER + "/item/product/importTxt"
const token = getToken()
const props = {
  value: 'id',
  label: 'label',
  children: 'children'
}
// 查询参数
const searchParams = ref({
  pageNum: 1, // 第几页
  pageSize: 15, // 每页显示多少条
  userType: "00",
  deptId: '',
  loginName: "",
  userName: "",
  phonenumber: ""
});
const total = ref<number>(0);
const authStore = useAuthStore()
// 直接使用 computed 绑定 store 值
const userId = authStore.loginUser.userId
const role = authStore.roleList

/** 重置搜索参数 */
const resetSearchParams = () => {
  searchParams.value = {
    pageNum: 1,
    pageSize: 15,
    userType: "00",
    loginName: "",
    deptId: '',
    userName: "",
    phonenumber: ""
  };
  dateRange.value = [];
};

/** 搜索 */
const handleSearch = () => {
  console.log("搜索");
  searchParams.value.pageNum = 1;
  handleListPage();
};

/** 重置 */
const resetSearch = () => {
  console.log("重置搜索");
  resetSearchParams();
  handleListPage();
};

// 时间
const dateRange = ref();

/** @current-change：点击分页组件页码发生变化：例如：切换第2、3页 OR 上一页 AND 下一页 OR 跳转某一页 */
/** @size-change：点击分页组件下拉选择条数发生变化：例如：选择10条/页、20条/页等 */
// 分页查询，@current-change AND @size-change都会触发分页，调用后端分页接口
/** 数据表格 */
const handleListPage = async () => {
  try {
    loading.value = true;
    tableList.value = []; // 重置表格数据
    const res: any = await listUser(searchParams.value)
    if(role[0] === 'admin') {
      tableList.value = res.rows
    } else {
      tableList.value = res.rows?.filter((v: { userId?: number }) => v.userId !== userId) || [];
    }
    total.value = res.total;
    loading.value = false;
  } catch (error) {
    koiNoticeError("数据查询失败，请刷新重试");
  }
};

const postOptions = ref()
const roleOptions = ref()
const deptOptions = ref()

// 获取部门角色
const getUserRoles = async () => {
  try {
    const response = await getUser('');
    if (!response) {
      throw new Error("返回了 null 或 undefined");
    }
    const {posts, roles} = response; // 设置默认值，避免解构报错
    postOptions.value = posts;
    roleOptions.value = roles;
  } catch (error) {
    console.error("获取用户角色失败:", error);
  }
}

const getDeptOptions = async () => {
  const res = await treeselect();
  deptOptions.value = res.data
}

onMounted(() => {
  // 获取表格数据
  handleListPage();
  getUserRoles()
  getDeptOptions()
});

const ids = ref([]); // 选择数组
const single = ref<boolean>(true); // 非单个禁用
const multiple = ref<boolean>(true); // 非多个禁用

/** 是否多选 */
const handleSelectionChange = (selection: any) => {
  ids.value = selection.map((item: any) => item.userId);
  single.value = selection.length != 1; // 单选
  multiple.value = !selection.length; // 多选
};

/** 添加 */
const handleAdd = () => {
  // 打开对话框
  koiDrawerRef.value.koiOpen();
  koiMsgSuccess("添加");
  // 重置表单
  resetForm();
  // 标题
  title.value = "用户添加";
  form.value.status = "0";
};

/** 修改 */
const handleUpdate = async (row?: any) => {
  // 打开对话框
  koiDrawerRef.value.koiOpen();
  koiMsgSuccess("修改");
  // 重置表单
  resetForm();
  // 标题
  title.value = "用户修改";
  getUser(row.userId).then(res => {
    const {data, postIds, roleIds} = res
    form.value.userId = data.userId;
    form.value.nickName = data.nickName;
    form.value.userName = data.userName;
    form.value.deptId = data.deptId;
    form.value.userType = data.userType;
    form.value.status = data.status;
    form.value.avatar = data.avatar;
    form.value.password = data.password;
    form.value.phonenumber = data.phonenumber;
    form.value.email = data.email;
    form.value.remark = data.remark;
    form.value.sex = data.sex;
    form.value.roleIds = roleIds.length ? roleIds[0] : ''
    form.value.postIds = postIds.length ? postIds[0] : ''
  })
};

// 添加 OR 修改抽屉Ref
const koiDrawerRef = ref();
// 标题
const title = ref("用户类型管理");
// form表单Ref
const formRef = ref<any>();

// form表单
let form = ref<any>({
  userId: '',
  nickName: "",
  userName: "",
  deptId: "",
  userType: "",
  status: "",
  avatar: "",
  password: "",
  phonenumber: "",
  email: "",
  remark: "",
  sex: "",
  roleIds: "",
  postIds: ""
});

/** 清空表单数据 */
const resetForm = () => {
  // 等待 DOM 更新完成
  nextTick(() => {
    if (formRef.value) {
      // 重置该表单项，将其值重置为初始值，并移除校验结果
      formRef.value.resetFields();
    }
  });
  Object.assign(form.value, {
    userId: '',
    nickName: "",
    userName: "",
    deptId: "",
    userType: "",
    status: "",
    avatar: "",
    password: "",
    phonenumber: "",
    email: "",
    remark: "",
    sex: "",
    roleIds: "",
    postIds: ""
  })
};

/** 表单规则 */
const rules = reactive({
  nickName: [{required: true, message: "请输入用户名字", trigger: "blur"}],
  userName: [{required: true, message: "请输入登录名字", trigger: "blur"}],
  phonenumber: [{required: true, message: "请输入手机号码", trigger: "blur"}],
  password: [
    {required: true, message: "用户密码不能为空", trigger: "blur"},
    {min: 5, max: 20, message: '用户密码长度必须介于 5 和 20 之间', trigger: 'blur'}
  ],
  userType: [{required: true, message: "请输入用户类型", trigger: "blur"}],
  status: [{required: true, message: "请输入选择用户状态", trigger: "blur"}],
  deptId: [{required: true, message: "请选择部门", trigger: "blur"}],
  roleIds: [{required: true, message: "请选择角色", trigger: "blur"}],
  sex: [{required: true, message: "请选择性别", trigger: "blur"}]
});

// 确定按钮是否显示Loading
const confirmLoading = ref(false);
const parseIds = (ids: any) => (ids ? String(ids).split(",") : []);

/** 确定  */
const handleConfirm = () => {
  if (!formRef.value) return;
  confirmLoading.value = true;
  (formRef.value as any).validate(async (valid: any) => {
    if (valid) {
      if (form.value.userId != null && form.value.userId != "") {
        try {
          form.value.postIds = parseIds(form.value.postIds);
          form.value.roleIds = parseIds(form.value.roleIds);
          await updateUser(form.value);
          koiNoticeSuccess("修改成功");
          confirmLoading.value = false;
          koiDrawerRef.value.koiQuickClose();
          resetForm();
          handleListPage();
        } catch (error) {
          console.log(error);
          confirmLoading.value = false;
          koiNoticeError("修改失败，请刷新重试");
        }
      } else {
        try {
          form.value.postIds = parseIds(form.value.postIds);
          form.value.roleIds = parseIds(form.value.roleIds);
          await addUser(form.value);
          koiNoticeSuccess("添加成功");
          confirmLoading.value = false;
          koiDrawerRef.value.koiQuickClose();
          resetForm();
          handleListPage();
        } catch (error) {
          console.log(error);
          confirmLoading.value = false;
          koiNoticeError("添加失败，请刷新重试");
        }
      }
    } else {
      koiMsgError("验证失败，请检查填写内容");
      confirmLoading.value = false;
    }
  });
};

/** 取消 */
const handleCancel = () => {
  koiDrawerRef.value.koiClose();
};

/** 状态开关 */
const handleSwitch = (row: any) => {
  let text = row.status === "0" ? "启用" : "停用";
  koiMsgBox("确认要[" + text + "]-[" + row.userName + "]吗？")
    .then(async () => {
      if (!row.userId || !row.status) {
        koiMsgWarning("请选择需要修改的数据");
        return;
      }
      try {
        await changeUserStatus(row.userId, row.status);
        koiNoticeSuccess("修改成功");
      } catch (error) {
        console.log(error);
        koiNoticeError("修改失败，请刷新重试");
      }
    })
    .catch(() => {
      row.status = row.status === "0" ? "1" : "0";
      koiMsgError("已取消");
    });
};

/** 删除 */
const handleDelete = (row: any) => {
  const id = row.userId || ids.value.join(',')
  if (id == null || id == "") {
    koiMsgWarning("请选择需要删除的数据");
    return;
  }
  koiMsgBox("您确认需要删除用户名称[" + row.nickName + "]么？")
    .then(async () => {
      const res: any = await delUser(id);
      if (res.code === 200) {
        koiNoticeSuccess("删除成功");
        handleListPage();
      } else {
        koiNoticeError("删除失败，请刷新重试");
      }
    })
    .catch(() => {
      koiMsgError("已取消");
    });
};

/** 导入按钮操作 */
const handleImport = () => {
  nextTick(async () => {
    uploadRef.value?.clearFiles();
  })
  koiDialogRef.value.koiOpen();
}
const koiDialogRef = ref()
const uploadRef = ref()
const updateSupport = ref(0)
const onSuccess = (res: any) => {
  if (res.code === 200) {
    koiNoticeSuccess('上传成功')
    handleListPage()
    koiDialogRef.value.koiQuickClose();
  } else {
    koiMsgError(res.msg)
  }
  uploadRef.value?.clearFiles();
}

/** 导入按钮操作 */
const importTemplate = () => {
  download('system/user/importTemplate', {}, `user_template_${new Date().getTime()}.xlsx`)
}

/** 导出按钮操作 */
const handleExport = () => {
  koiMsgBox("您确认导出用户信息么？")
    .then(async () => {
      download('system/user/export', searchParams.value, `user_${new Date().getTime()}.xlsx`)
    })
    .catch(() => {
    });
}
</script>

<style lang="scss" scoped>
// 穿梭框高度调整
:deep(.el-transfer-panel__body) {
  height: 400px;
}
</style>
