<template>
  <div class="app-container h-full flex flex-1 flex-col">
    <!-- 搜索 -->
    <page-search
      ref="searchRef"
      :search-config="searchConfig"
      @query-click="handleQueryClick"
      @reset-click="handleResetClick"
    ></page-search>

    <!-- 列表 -->
    <page-content
      ref="contentRef"
      :content-config="contentConfig"
      @add-click="handleAddClick"
      @export-click="handleExportClick"
      @search-click="handleSearchClick"
      @toolbar-click="handleToolbarClick"
      @operate-click="handleOperateClick"
      @filter-change="handleFilterChange"
      @sort-change="handleSortChange"
    >
      <template #balance="scope">
        <span class="money-text primary">¥ {{ formatMoney(scope.row.balance) }}</span>
      </template>
      <template #totalConsumption="scope">
        <span class="money-text warning">¥ {{ formatMoney(scope.row.totalConsumption) }}</span>
      </template>
    </page-content>

    <!-- 详情 -->
    <page-modal
      ref="editModalRef"
      :modal-config="editModalConfig"
      @submit-click="handleSubmitClick"
    ></page-modal>
  </div>
</template>

<script setup lang="ts">
defineOptions({ name: "UserInfo" });

import UserInfoAPI, { UserInfoForm, UserInfoPageQuery } from "@/api/userManage/user-info-api";
import UserFirmAPI from "@/api/toBManage/user-firm-api";
import type { IObject, IModalConfig, IContentConfig, ISearchConfig } from "@/components/CURD/types";
import usePage from "@/components/CURD/usePage";

// 组合式 CRUD
const {
  searchRef,
  contentRef,
  editModalRef,
  handleQueryClick,
  handleResetClick,
  handleAddClick,
  handleEditClick,
  handleSubmitClick,
  handleExportClick,
  handleSearchClick,
  handleFilterChange,
} = usePage();

// 金额格式化函数
const formatMoney = (value: number | undefined | null): string => {
  if (value === null || value === undefined) return "0.00";
  return Math.abs(value).toLocaleString("zh-CN", {
    minimumFractionDigits: 2,
    maximumFractionDigits: 2,
  });
};

// 搜索配置
const searchConfig: ISearchConfig = reactive({
  permPrefix: "business:user-info",
  formItems: [
    {
      type: "input",
      label: "手机号",
      prop: "phone",
      attrs: {
        placeholder: "手机号",
        clearable: true,
        style: { width: "200px" },
      },
    },
    {
      type: "select",
      label: "所属企业",
      prop: "firmId",
      attrs: {
        placeholder: "请选择企业",
        clearable: true,
        filterable: true,
        style: { width: "200px" },
      },
      options: [],
      async initFn(formItem) {
        try {
          const response = await UserFirmAPI.getFirmList();
          if (Array.isArray(response)) {
            formItem.options = response.map((item: any) => ({
              label: item.name,
              value: item.id,
            }));
          }
        } catch (error) {
          console.error("Failed to fetch firm list:", error);
        }
      },
    },
  ],
});

// 列表配置
const contentConfig: IContentConfig<UserInfoPageQuery> = reactive({
  // 权限前缀
  permPrefix: "business:user-info",
  table: {
    border: true,
    highlightCurrentRow: true,
  },
  // 主键
  pk: "id",
  // 列表查询接口
  indexAction: UserInfoAPI.getPage,
  // 数据解析函数
  parseData(res: any) {
    return {
      total: res.total,
      list: res.list,
    };
  },
  // 分页配置
  pagination: {
    background: true,
    layout: "total, sizes, prev, pager, next, jumper",
    pageSize: 20,
    pageSizes: [10, 20, 30, 50],
  },
  // 工具栏配置
  defaultToolbar: ["refresh", "filter"],
  // 表格列配置
  cols: [
    { type: "selection", width: 50, align: "center" },
    { label: "用户ID", prop: "id", width: 100 },
    { label: "手机号", prop: "phone" },
    { label: "昵称", prop: "nickName" },
    { label: "所属企业", prop: "firmName" },
    {
      label: "当前余额",
      prop: "balance",
      sortable: "custom",
      templet: "custom",
      slotName: "balance",
    },
    {
      label: "累计消费",
      prop: "totalConsumption",
      sortable: "custom",
      templet: "custom",
      slotName: "totalConsumption",
    },
    { label: "创建时间", prop: "createTime" },
    {
      label: "操作",
      prop: "operation",
      width: 100,
      templet: "tool",
      operat: [
        {
          name: "detail",
          text: "详情",
          attrs: {
            type: "primary",
            icon: "view",
            link: true,
            size: "small",
          },
        },
      ],
    },
  ],
});

// 详情配置
const editModalConfig: IModalConfig<UserInfoForm> = reactive({
  permPrefix: "business:user-info",
  component: "drawer",
  drawer: {
    title: "用户详情",
    size: 500,
  },
  pk: "id",
  formItems: [
    {
      type: "input",
      attrs: {
        placeholder: "用户ID",
        disabled: true,
      },
      label: "用户ID",
      prop: "id",
    },
    {
      type: "input",
      attrs: {
        placeholder: "手机号",
        disabled: true,
      },
      label: "手机号",
      prop: "phone",
    },
    {
      type: "input",
      attrs: {
        placeholder: "昵称",
        disabled: true,
      },
      label: "昵称",
      prop: "nickName",
    },
    {
      type: "input",
      attrs: {
        placeholder: "微信openid",
        disabled: true,
      },
      label: "微信openid",
      prop: "openid",
    },
  ],
});

// 处理操作按钮点击
const handleOperateClick = (data: IObject) => {
  if (data.name === "detail") {
    handleEditClick(data.row, async () => {
      return await UserInfoAPI.getFormData(data.row.id);
    });
  }
};

// 处理工具栏按钮点击
const handleToolbarClick = (name: string) => {
  console.log(name);
};

// 排序参数
const sortParams = reactive({
  sortField: "",
  sortOrder: "",
});

// 处理排序变化
const handleSortChange = (data: { prop: string; order: string | null }) => {
  sortParams.sortField = data.prop || "";
  sortParams.sortOrder = data.order || "";
  // 带着排序参数重新查询
  contentRef.value?.fetchPageData({ ...sortParams });
};
</script>

<style scoped>
.money-text {
  font-weight: bold;
  font-size: 13px;
}
.money-text.primary {
  color: #409eff;
}
.money-text.success {
  color: #67c23a;
}
.money-text.danger {
  color: #f56c6c;
}
.money-text.warning {
  color: #e6a23c;
}
</style>
