import {
  QyUserDTO,
  QyUserQuery,
  getQyUserListApi,
  updateQyUserApi
} from "@/api/qy/qyUser";
import { ElMessage } from "element-plus";
import { type PaginationProps } from "@pureadmin/table";
import { reactive, ref, onMounted, toRaw, h, onBeforeUnmount } from "vue";
import { CommonUtils } from "@/utils/common";
import { handleTree, setDisabledForTreeOptions } from "@/utils/tree";
import { getQyDeptListApi } from "@/api/system/dept";
import { getPostListApi } from "@/api/system/post";
import { getRoleListApi } from "@/api/system/role";
import { useWxStore } from "@/store/modules/wx";
import { useMultiTagsStoreHook } from "@/store/modules/multiTags";
import { useRouter } from "vue-router";

/**
 * 企业用户管理页面的组合式函数
 * 提供用户列表查询、分页、部门/岗位/角色数据获取、余额修改等功能
 */
export function useHook() {
  const wxStore = useWxStore(); // 微信相关状态管理
  const router = useRouter();

  // 搜索表单参数
  const searchFormParams = reactive<QyUserQuery>({
    /** 姓名（导出列：姓名） */
    name: undefined,
    /** 手机号（导出列：联系方式） */
    mobile: undefined,
    corpid: wxStore.corpid, // 企业ID
    mainDepartment: undefined, // 主部门
  });

  const timeRange = ref<[string, string]>(); // 时间范围选择

  // 列表相关状态
  const dataList = ref<QyUserDTO[]>([]); // 用户列表数据
  const pageLoading = ref(true); // 加载状态
  const pagination = reactive<PaginationProps>({ // 分页配置
    total: 0,
    pageSize: 8,
    currentPage: 1,
    background: true
  });

  // 余额修改相关状态
  const BalanceEditModal = ref(null); // 余额编辑模态框引用
  const balanceVisible = ref(false); // 余额弹窗可见性
  const currentBalance = ref(0); // 当前编辑的余额值
  const selectedUserId = ref<number>(); // 当前选中的用户ID
  const selectedUser = ref<QyUserDTO>(); // 当前选中的用户对象

  // 下拉选项数据
  const deptTreeList = ref([]); // 部门树形数据
  const postOptions = ref([]); // 岗位选项
  const roleOptions = ref([]); // 角色选项

  /**
   * 执行搜索操作
   * 重置分页后重新获取列表数据
   */
  async function onSearch() {
    pagination.currentPage = 1;
    getList();
  }

  /**
   * 获取用户列表数据
   * 处理分页参数和时间范围参数后调用API
   */
  async function getList() {
    CommonUtils.fillPaginationParams(searchFormParams, pagination);
    CommonUtils.fillTimeRangeParams(searchFormParams, timeRange.value);

    pageLoading.value = true;
    const { data } = await getQyUserListApi(toRaw(searchFormParams)).finally(
      () => {
        pageLoading.value = false;
      }
    );

    dataList.value = data.rows;
    pagination.total = data.total;
  }

  /**
   * 重置搜索表单
   * @param formEl 表单元素引用
   */
  const resetForm = formEl => {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  };

  // 组件挂载时执行
  onMounted(async () => {
    onSearch(); // 初始加载列表数据

    // 获取部门树形数据
    const deptResponse = await getQyDeptListApi(wxStore.corpid);
    deptTreeList.value = await setDisabledForTreeOptions(
      handleTree(deptResponse.data),
      "status"
    );

    // 获取岗位选项
    const postResponse = await getPostListApi({});
    postOptions.value = postResponse.data.rows;

    // 获取角色选项
    const roleResponse = await getRoleListApi({});
    roleOptions.value = roleResponse.data.rows;
  });

  /**
   * 查看用户详情
   * @param row 用户数据行
   */
  const handleViewDetail = (row: QyUserDTO) => {
    // 保存信息到标签页
    useMultiTagsStoreHook().handleTags("push", {
      path: `/user/qy/detail`,
      name: "qyDetail",
      query: { id: row.id },
      meta: {
        title: `${row.name}`,
        dynamicLevel: 3
      }
    });
    router.push({
      path: '/user/qy/detail',
      query: {
        id: row.id
      }
    });
  };

  /**
   * 打开修改余额弹窗
   * @param row 用户数据行
   */
  const handleModifyBalance = (row: QyUserDTO) => {
    selectedUserId.value = row.id;
    currentBalance.value = row.balance || 0;
    selectedUser.value = row;
    balanceVisible.value = true;
  };


  // 暴露给模板使用的属性和方法
  return {
    BalanceEditModal,
    searchFormParams,
    pageLoading,
    dataList,
    pagination,
    onSearch,
    resetForm,
    getList,
    handleViewDetail,
    handleModifyBalance,
    balanceVisible,
    selectedUser
  };
}
