<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"
    ></page-content>

    <!-- 新增 -->
    <page-modal ref="addModalRef" :modal-config="addModalConfig" @submit-click="handleSubmitClick">
      <template #picture="{ formData }">
        <SingleImageUpload v-model="formData.picture" />
      </template>
    </page-modal>

    <!-- 编辑 -->
    <page-modal
      ref="editModalRef"
      :modal-config="editModalConfig"
      @submit-click="handleSubmitClick"
    >
      <template #picture="{ formData }">
        <SingleImageUpload v-model="formData.picture" />
      </template>
    </page-modal>
  </div>
</template>

<script setup lang="ts">
import { computed, reactive, defineOptions, onMounted } from "vue";
import SingleImageUpload from "@/components/Upload/SingleImageUpload.vue";
import { useDictStore } from "@/store";

defineOptions({ name: "Advertising" });

import AdvertisingAPI, {
  AdvertisingForm,
  AdvertisingPageQuery,
} from "@/api/operationsManage/advertising-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();

// 获取字典store
const dictStore = useDictStore();

// 广告位置选项
const advertisingPositionOptions = ref<Array<{ label: string; value: string | number }>>([]);

// 加载广告位置字典
const loadAdvertisingPositionDict = async () => {
  await dictStore.loadDictItems("advertising_position");
  advertisingPositionOptions.value = dictStore.getDictItems("advertising_position");
};

// 组件挂载时加载字典
onMounted(() => {
  loadAdvertisingPositionDict();
});

// 搜索配置
const searchConfig: ISearchConfig = reactive({
  permPrefix: "business:advertising",
  formItems: [
    {
      type: "input",
      label: "名称",
      prop: "name",
      attrs: {
        placeholder: "请输入",
        clearable: true,
        style: { width: "200px" },
      },
    },
  ],
});

// 列表配置
const contentConfig: IContentConfig<AdvertisingPageQuery> = reactive({
  // 权限前缀
  permPrefix: "business:advertising",
  table: {
    border: true,
    highlightCurrentRow: true,
  },
  // 主键
  pk: "id",
  // 列表查询接口
  indexAction: AdvertisingAPI.getPage,
  // 删除接口
  deleteAction: AdvertisingAPI.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: "状态", // 1.上线 2.下线
      prop: "status",
      formatter: (value: any) => {
        return value.status === 1 ? "上线" : "下线";
      },
    },
    { label: "排序", prop: "sort" },
    {
      label: "广告位置", //  1.首页弹框
      prop: "position",
      formatter: (row: any) => {
        return "首页弹窗";
      },
    },
    { label: "图片", prop: "picture", templet: "image" },
    {
      label: "跳转路径",
      prop: "skipUrl",
      formatter: (value: any) => {
        return value.skipUrl || "无";
      },
    },
    { label: "创建时间", prop: "createTime" },
    { label: "更新时间", prop: "updateTime" },
    {
      label: "操作",
      prop: "operation",
      width: 220,
      templet: "tool",
      operat: ["edit", "delete"],
    },
  ],
});

// 新增配置
const addModalConfig: IModalConfig<AdvertisingForm> = reactive({
  // 权限前缀
  permPrefix: "business:advertising",
  // 主键
  pk: "id",
  // 弹窗配置
  dialog: {
    title: "新增",
    width: 800,
    draggable: true,
  },
  form: {
    labelWidth: 100,
  },
  // 表单项配置
  formItems: [
    {
      type: "input",
      attrs: {
        placeholder: "名称",
      },
      rules: [{ required: true, message: "名称不能为空", trigger: "blur" }],
      label: "名称",
      prop: "name",
    },
    {
      type: "switch",
      attrs: {
        activeValue: 1,
        inactiveValue: 0,
      },
      initialValue: 1,
      label: "状态",
      prop: "status",
    },
    {
      type: "input",
      attrs: {
        placeholder: "排序",
      },
      rules: [{ required: true, message: "排序不能为空", trigger: "blur" }],
      label: "排序",
      prop: "sort",
    },
    {
      permission: "system:advertising:position",
      type: "select",
      attrs: {
        placeholder: "请选择广告位置",
      },
      label: "广告位置",
      prop: "position",
      options: advertisingPositionOptions,
    },
    {
      type: "custom",
      label: "图片",
      prop: "picture",
      slotName: "picture",
      rules: [{ required: true, message: "请上传图片", trigger: "change" }],
    },
    {
      type: "input",
      attrs: {
        placeholder: "跳转路径",
      },
      label: "跳转路径",
      prop: "skipUrl",
    },
  ],
  // 提交函数
  formAction: (data: AdvertisingForm) => {
    if (data.id) {
      // 编辑
      return AdvertisingAPI.update(data.id as string, data);
    } else {
      // 新增
      return AdvertisingAPI.create(data);
    }
  },
});

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

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

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