<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"
    >
      <template #orderStatus="scope">
        <Dict v-model="scope.formData[scope.prop]" code="order_status" v-bind="scope.attrs" />
      </template>
    </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"
    >
      <template #orderStatus="scope">
        <DictLabel v-model="scope.row[scope.prop]" code="order_status" />
      </template>
      <template #orderType="scope">
        <DictLabel v-model="scope.row[scope.prop]" code="order_type" />
      </template>
    </page-content>

    <!-- 新增 -->
    <page-modal ref="addModalRef" :modal-config="addModalConfig" @submit-click="handleSubmitClick">
      <template #orderStatus="scope">
        <Dict v-model="scope.formData[scope.prop]" code="order_status" v-bind="scope.attrs" />
      </template>
      <template #orderType="scope">
        <Dict v-model="scope.formData[scope.prop]" code="order_type" v-bind="scope.attrs" />
      </template>
    </page-modal>

    <!-- 编辑 -->
    <page-modal
      ref="editModalRef"
      :modal-config="editModalConfig"
      @submit-click="handleSubmitClick"
    >
      <template #orderStatus="scope">
        <Dict v-model="scope.formData[scope.prop]" code="order_status" v-bind="scope.attrs" />
      </template>
      <template #orderType="scope">
        <Dict v-model="scope.formData[scope.prop]" code="order_type" v-bind="scope.attrs" />
      </template>
    </page-modal>
  </div>
</template>

<script setup lang="ts">
defineOptions({ name: "UserOrderInfo" });
import UserOrderInfoAPI, {
  UserOrderInfoForm,
  UserOrderInfoPageQuery,
} from "@/api/orderManage/user-order-info-api";
import type { IObject, IModalConfig, IContentConfig, ISearchConfig } from "@/components/CURD/types";
import usePage from "@/components/CURD/usePage";

// 处理时间范围参数的通用函数
const processTimeParams = (params: any) => {
  const processedParams = { ...params };
  // 处理创建时间
  if ("createTime" in processedParams) {
    const createTime = processedParams.createTime as string[];
    if (createTime?.length > 1) {
      processedParams.startTime = createTime[0] + " 00:00:00";
      processedParams.endTime = createTime[1] + " 23:59:59";
    }
    delete processedParams.createTime;
  }
  // 处理退款时间
  if ("refundTime" in processedParams) {
    const refundTime = processedParams.refundTime as string[];
    if (refundTime?.length > 1) {
      processedParams.refundStartTime = refundTime[0] + " 00:00:00";
      processedParams.refundEndTime = refundTime[1] + " 23:59:59";
    }
    delete processedParams.refundTime;
  }
  return processedParams;
};

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

// 重写导出函数，处理时间参数
const handleExportClick = () => {
  const queryParams = searchRef.value?.getQueryParams();
  if (queryParams) {
    const processedParams = processTimeParams(queryParams);
    // 过滤空值参数
    const filteredParams: any = {};
    for (const key in processedParams) {
      const value = processedParams[key];
      if (value !== "" && value !== null && value !== undefined) {
        if (Array.isArray(value)) {
          if (value.length > 0) {
            filteredParams[key] = value;
          }
        } else {
          filteredParams[key] = value;
        }
      }
    }
    contentRef.value?.exportPageData(filteredParams);
  }
};

// 搜索配置
const searchConfig: ISearchConfig = reactive({
  permPrefix: "business:user-order-info",
  formItems: [
    {
      type: "custom",
      slotName: "orderStatus",
      label: "订单状态", // 1 待支付  2 已支付 3 已取消 4 已退款
      prop: "orderStatus",
      attrs: {
        placeholder: "选择订单状态",
        clearable: true,
        style: { width: "200px" },
      },
    },
    {
      type: "input",
      label: "订单编号",
      prop: "orderNo",
      attrs: {
        placeholder: "请输入订单编号",
        clearable: true,
        style: { width: "200px" },
      },
    },
    {
      type: "input",
      label: "手机号",
      prop: "phone",
      attrs: {
        placeholder: "请输入手机号",
        clearable: true,
        style: { width: "200px" },
      },
    },
    {
      type: "date-picker",
      label: "创建时间",
      prop: "createTime",
      attrs: {
        type: "daterange",
        "range-separator": "~",
        "start-placeholder": "开始时间",
        "end-placeholder": "截止时间",
        "value-format": "YYYY-MM-DD",
        style: { width: "240px" },
      },
    },
    {
      type: "date-picker",
      label: "退款时间",
      prop: "refundTime",
      attrs: {
        type: "daterange",
        "range-separator": "~",
        "start-placeholder": "开始时间",
        "end-placeholder": "截止时间",
        "value-format": "YYYY-MM-DD",
        style: { width: "240px" },
      },
    },
  ],
});

// 列表配置
const contentConfig: IContentConfig<UserOrderInfoPageQuery> = reactive({
  // 权限前缀
  permPrefix: "business:user-order-info",
  table: {
    border: true,
    highlightCurrentRow: true,
  },
  // 主键
  pk: "id",
  // 列表查询接口
  indexAction: (params: any) => {
    const processedParams = processTimeParams(params);
    return UserOrderInfoAPI.getPage(processedParams);
  },
  // 删除接口
  deleteAction: UserOrderInfoAPI.deleteByIds,
  // 导出接口
  exportAction: UserOrderInfoAPI.exportExcel,
  // 数据解析函数
  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],
  },
  // 工具栏配置
  toolbar: ["export"],
  defaultToolbar: ["refresh", "filter"],
  // 表格列配置
  cols: [
    { type: "selection", width: 55, align: "center" },
    { label: "订单编号", prop: "orderNo" },
    { label: "手机号", prop: "phone" },
    { label: "订单金额", prop: "orderMoney" },
    { label: "订单剩余金额", prop: "lastMoney" },
    { label: "支付时间", prop: "payTime" },
    {
      label: "订单状态", // 1 待支付  2 已支付 3 已取消 4 已退款
      prop: "orderStatus",
      templet: "custom",
      slotName: "orderStatus",
    },
    {
      label: "订单类型", //1 微信 2 第三方
      prop: "orderType",
      templet: "custom",
      slotName: "orderType",
    },
    { label: "第三方支付单号", prop: "outTradeNo" },
    { label: "微信支付流水号", prop: "transactionId" },
    { label: "退款金额", prop: "refundMoney" },
    { label: "退款时间", prop: "refundTime" },
    { label: "备注", prop: "remark" },
    { label: "创建时间", prop: "createTime" },
  ],
});

// 新增配置
const addModalConfig: IModalConfig<UserOrderInfoForm> = reactive({
  // 权限前缀
  permPrefix: "business:user-order-info",
  // 主键
  pk: "id",
  // 弹窗配置
  dialog: {
    title: "新增",
    width: 800,
    draggable: true,
  },
  form: {
    labelWidth: 100,
  },
  // 表单项配置
  formItems: [
    {
      type: "input",
      attrs: {
        placeholder: "订单编号",
      },
      label: "订单编号",
      prop: "orderNo",
    },
    {
      type: "input",
      attrs: {
        placeholder: "订单金额",
      },
      label: "订单金额",
      prop: "orderMoney",
    },
    {
      type: "input",
      attrs: {
        placeholder: "订单剩余金额",
      },
      label: "订单剩余金额",
      prop: "lastMoney",
    },
    {
      type: "input",
      attrs: {
        placeholder: "支付时间",
      },
      label: "支付时间",
      prop: "payTime",
    },
    {
      type: "input",
      attrs: {
        placeholder: "第三方支付单号",
      },
      label: "第三方支付单号",
      prop: "outTradeNo",
    },
    {
      type: "custom",
      label: "订单状态", // 1 待支付  2 已支付 3 已取消 4 已退款
      prop: "orderStatus",
      slotName: "orderStatus",
      attrs: {
        placeholder: "订单状态",
        style: { width: "100%" },
      },
    },
    {
      type: "custom",
      label: "订单类型", // 1 微信 2 第三方
      prop: "orderType",
      slotName: "orderType",
      attrs: {
        placeholder: "订单类型",
        style: { width: "100%" },
      },
    },
    {
      type: "input",
      attrs: {
        placeholder: "退款金额",
      },
      label: "退款金额",
      prop: "refundMoney",
    },
    {
      type: "input",
      attrs: {
        placeholder: "退款时间",
      },
      label: "退款时间",
      prop: "refundTime",
    },
    {
      type: "input",
      attrs: {
        placeholder: "备注",
      },
      label: "备注",
      prop: "remark",
    },
    {
      type: "input",
      attrs: {
        placeholder: "创建时间",
      },
      label: "创建时间",
      prop: "createTime",
    },
  ],
  // 提交函数
  formAction: (data: UserOrderInfoForm) => {
    if (data.id) {
      // 编辑
      return UserOrderInfoAPI.update(data.id as string, data);
    } else {
      // 新增
      return UserOrderInfoAPI.create(data);
    }
  },
});

// 编辑配置
const editModalConfig: IModalConfig<UserOrderInfoForm> = reactive({
  permPrefix: "business:user-order-info",
  component: "drawer",
  drawer: {
    title: "编辑",
    size: 500,
  },
  pk: "id",
  formAction(data: any) {
    return UserOrderInfoAPI.update(data.id as string, data);
  },
  formItems: addModalConfig.formItems, // 复用新增的表单项
});

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

// 处理工具栏按钮点击（删除等）
const handleToolbarClick = (name: string) => {
  console.log(name);
};
</script>
