<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"
    >
      <template #status="scope">
        <!--        1.上线 2.下线-->
        <el-tag :type="scope.row.status === 2 ? 'danger' : 'success'">
          {{ scope.row.status === 2 ? "下线" : "上线" }}
        </el-tag>
      </template>
    </page-content>

    <!-- 新增 -->
    <page-modal
      ref="addModalRef"
      :modal-config="addModalConfig"
      @submit-click="handleSubmitClick"
    ></page-modal>

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

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

import PromotionCouponTemplateAPI, {
  PromotionCouponTemplateForm,
  PromotionCouponTemplatePageQuery,
} from "@/api/operationsManage/promotion-coupon-template-api";
import type { IObject, IModalConfig, IContentConfig, ISearchConfig } from "@/components/CURD/types";
import usePage from "@/components/CURD/usePage";

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

// 搜索配置
const searchConfig: ISearchConfig = reactive({
  permPrefix: "business:coupon-template",
  formItems: [
    {
      type: "input",
      label: "优惠劵名称",
      prop: "name",
      attrs: {
        placeholder: "优惠劵名称",
        clearable: true,
        style: { width: "200px" },
      },
    },
    {
      type: "select",
      label: "上线状态", // 1.上线 2.下线
      prop: "status",
      attrs: {
        placeholder: "上线状态", // 1.上线 2.下线
        clearable: true,
        style: { width: "200px" },
      },
      options: [
        {
          label: "下线",
          value: 2,
        },
        {
          label: "上线",
          value: 1,
        },
      ],
    },
    {
      type: "date-picker",
      label: "创建时间",
      prop: "createTime",
      attrs: {
        type: "daterange",
        "range-separator": "~",
        "start-placeholder": "开始时间",
        "end-placeholder": "截止时间",
        "value-format": "YYYY-MM-DD",
        style: { width: "240px" },
      },
    },
  ],
});

// 列表配置
const contentConfig: IContentConfig<PromotionCouponTemplatePageQuery> = reactive({
  // 权限前缀
  permPrefix: "business:coupon-template",
  table: {
    border: true,
    highlightCurrentRow: true,
  },
  // 主键
  pk: "id",
  // 列表查询接口
  indexAction: (params: any) => {
    // 处理创建时间范围参数
    if ("createTime" in params) {
      const createTime = params.createTime as string[];
      if (createTime?.length > 1) {
        params.startTime = createTime[0] + " 00:00:00";
        params.endTime = createTime[1] + " 23:59:59";
      }
      delete params.createTime;
    }
    return PromotionCouponTemplateAPI.getPage(params);
  },
  // 删除接口
  deleteAction: PromotionCouponTemplateAPI.deleteByIds,
  // 数据解析函数
  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: ["add", "delete"],
  defaultToolbar: ["refresh", "filter"],
  // 表格列配置
  cols: [
    { type: "selection", width: 55, align: "center" },
    { label: "优惠劵名称", prop: "name" },
    { label: "描述", prop: "description" },
    { label: "领取后有效期(天)", prop: "failureTime" },
    {
      label: "上线状态", //（ 0-下线 1-上线）
      prop: "status",
      templet: "custom",
    },
    {
      label: "发放数量", //, -1 - 则表示不限制
      prop: "totalCount",
    },
    {
      label: "发放时间",
      prop: "validTime",
      formatter: (row: any) => {
        // 获取时分和星期几数据（注意：这里是从row对象中获取原始字段）
        const hour = row.validTimeHour || "";
        const weeks = row.validTimeWeeks || "";
        // 如果没有数据，返回空字符串
        if (!hour && !weeks) {
          return "";
        }
        // 解析星期几数据
        let weekText = "";
        if (weeks) {
          const weekArray = weeks.split(",").map((w) => w.trim());
          const weekMap: { [key: string]: string } = {
            "1": "星期一",
            "2": "星期二",
            "3": "星期三",
            "4": "星期四",
            "5": "星期五",
            "6": "星期六",
            "7": "星期日",
          };

          const weekNames = weekArray.map((w) => weekMap[w]).filter((w) => w);
          if (weekNames.length > 0) {
            weekText = `（${weekNames.join("，")}）`;
          }
        }
        // 返回拼接后的格式：17:30（星期二，星期三）
        return `${hour}${weekText}`;
      },
    },
    {
      label: "设置满多少金额可用(元)", //，单位：分
      prop: "usePrice",
    },
    {
      label: "优惠金额(元)", //，单位：分
      prop: "discountPrice",
      // formatter: (row: any) => {
      //   // 转换为元并保留两位小数
      //   return (row.discountPrice / 100).toFixed(2);
      // },
    },
    { label: "创建时间", prop: "createTime" },
    {
      label: "操作",
      prop: "operation",
      width: 220,
      templet: "tool",
      operat: ["edit", "delete"],
    },
  ],
});

// 新增配置
const addModalConfig: IModalConfig<PromotionCouponTemplateForm> = reactive({
  // 权限前缀
  permPrefix: "business:coupon-template",
  // 主键
  pk: "id",
  // 弹窗配置
  dialog: {
    title: "新增",
    width: 800,
    draggable: true,
  },
  form: {
    labelWidth: 160,
  },
  // 表单项配置
  formItems: [
    {
      type: "input",
      attrs: {
        placeholder: "优惠劵名称",
      },
      rules: [{ required: true, message: "优惠劵名称不能为空", trigger: "blur" }],
      label: "优惠劵名称",
      prop: "name",
    },
    {
      type: "input",
      attrs: {
        placeholder: "描述",
      },
      rules: [{ required: true, message: "描述不能为空", trigger: "blur" }],
      label: "描述",
      prop: "description",
    },
    {
      type: "input",
      attrs: {
        placeholder: "领取后有效期",
      },
      rules: [{ required: true, message: "领取后有效期", trigger: "blur" }],
      label: "领取后有效期(天)",
      prop: "failureTime",
    },
    {
      type: "switch",
      attrs: {
        activeText: "启用",
        inactiveText: "禁用",
        activeValue: 1,
        inactiveValue: 2,
      },
      initialValue: 1,
      label: "上线状态", // （ 0-下线 1-上线）
      prop: "status",
    },
    {
      type: "input",
      attrs: {
        placeholder: "发放数量", //, -1 - 则表示不限制
      },
      rules: [{ required: true, message: "发放数量", trigger: "blur" }],
      label: "发放数量",
      prop: "totalCount",
    },
    {
      type: "input-tag",
      label: "领取时间-星期",
      prop: "validTimeWeeks",
      attrs: {
        placeholder: "请选择星期几（可多选）",
        config: {
          buttonAttrs: { btnText: "输入数字，如:周一输入1" },
        },
      },
      rules: [{ required: true, message: "日期不能为空", trigger: "blur" }],
    },
    {
      type: "time-select",
      attrs: {
        placeholder: "请选择时分",
        clearable: true,
        format: "HH:mm",
        valueFormat: "HH:mm",
      },
      rules: [{ required: true, message: "时间不能为空", trigger: "blur" }],
      label: "领取时间-时分",
      prop: "validTimeHour",
    },
    {
      type: "input-number",
      attrs: {
        placeholder: "设置满多少金额可用", //，单位：分
      },
      rules: [{ required: true, message: "设置满多少金额可用不能为空", trigger: "blur" }],
      label: "设置满多少金额可用",
      prop: "usePrice",
    },
    {
      type: "input-number",
      attrs: {
        placeholder: "优惠金额",
      },
      rules: [{ required: true, message: "优惠金额不能为空", trigger: "blur" }],
      label: "优惠金额",
      prop: "discountPrice",
    },
  ],
  // 提交函数
  beforeSubmit: (data: PromotionCouponTemplateForm) => {
    // 将星期数组转换为逗号分隔的字符串
    if (Array.isArray(data.validTimeWeeks)) {
      data.validTimeWeeks = data.validTimeWeeks.join(",");
    }

    // 删除金额转换为分的逻辑
    return data;
  },
  formAction(data: any) {
    if (data.id) {
      // 编辑
      return PromotionCouponTemplateAPI.update(data.id as string, data);
    } else {
      // 新增
      return PromotionCouponTemplateAPI.create(data);
    }
  },
});

// 编辑配置
const editModalConfig: IModalConfig<PromotionCouponTemplateForm> = reactive({
  permPrefix: "business:coupon-template",
  component: "drawer",
  drawer: {
    title: "编辑",
    size: 500,
  },
  pk: "id",
  beforeSubmit: (data: PromotionCouponTemplateForm) => {
    // 将星期数组转换为逗号分隔的字符串
    if (Array.isArray(data.validTimeWeeks)) {
      data.validTimeWeeks = data.validTimeWeeks.join(",");
    }

    // 删除金额转换为分的逻辑
    return data;
  },
  formAction(data: any) {
    return PromotionCouponTemplateAPI.update(data.id as string, data);
  },
  form: {
    labelWidth: 160,
  },
  formItems: addModalConfig.formItems, // 复用新增的表单项
});

// 处理操作按钮点击
const handleOperateClick = (data: IObject) => {
  if (data.name === "edit") {
    handleEditClick(data.row, async () => {
      const formData = await PromotionCouponTemplateAPI.getFormData(data.row.id);
      // 将逗号分隔的星期字符串转换为数组格式以适应input-tag组件
      if (formData.validTimeWeeks && typeof formData.validTimeWeeks === "string") {
        formData.validTimeWeeks = formData.validTimeWeeks.split(",");
      } else if (!formData.validTimeWeeks) {
        formData.validTimeWeeks = [];
      }
      return formData;
    });
  }
};

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