<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 #orJump="scope">
        <el-tag :type="scope.row.orJump == 1 ? 'success' : 'warning'">
          {{ scope.row.orJump == 1 ? "跳转" : "不跳转" }}
        </el-tag>
      </template>
      <template #location="scope">
        <el-tag :type="scope.row.location == 1 ? 'primary' : 'danger'">
          {{ scope.row.location == 1 ? "首页" : "我的" }}
        </el-tag>
      </template>
      <template #status="scope">
        <el-tag :type="scope.row.status == 1 ? 'success' : 'warning'">
          {{ scope.row.status == 1 ? "启用" : "禁用" }}
        </el-tag>
      </template>
    </page-content>

    <!-- 新增 -->
    <page-modal ref="addModalRef" :modal-config="addModalConfig" @submit-click="handleSubmitClick">
      <template #picture="{ formData }">
        <SingleImageUpload v-model="formData.picture" />
      </template>
      <template #orJump="{ formData }">
        <el-radio-group
          v-model="formData.orJump"
          @change="handleOrJumpChange(addModalConfig.formItems, formData.orJump)"
        >
          <el-radio :value="0">不跳转</el-radio>
          <el-radio :value="1">跳转</el-radio>
        </el-radio-group>
      </template>
    </page-modal>

    <!-- 编辑 -->
    <page-modal
      ref="editModalRef"
      :modal-config="editModalConfig"
      @submit-click="handleSubmitClick"
    >
      <template #picture="{ formData }">
        <SingleImageUpload v-model="formData.picture" />
      </template>
      <template #orJump="{ formData }">
        <el-radio-group
          v-model="formData.orJump"
          @change="handleOrJumpChange(editModalConfig.formItems, formData.orJump)"
        >
          <el-radio :value="0">不跳转</el-radio>
          <el-radio :value="1">跳转</el-radio>
        </el-radio-group>
      </template>
    </page-modal>
  </div>
</template>

<script setup lang="ts">
import SingleImageUpload from "@/components/Upload/SingleImageUpload.vue";
defineOptions({ name: "BannerInfo" });

import BannerInfoAPI, {
  BannerInfoForm,
  BannerInfoPageQuery,
} from "@/api/operationsManage/banner-info-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:banner-info",
  formItems: [
    {
      type: "select",
      label: "状态",
      prop: "status",
      attrs: {
        placeholder: "请选择状态",
        clearable: true,
        style: { width: "200px" },
      },
      options: [
        { label: "禁用", value: 0 },
        { label: "启用", value: 1 },
        { label: "其他", value: 2 },
      ],
    },
  ],
});

// 列表配置
const contentConfig: IContentConfig<BannerInfoPageQuery> = reactive({
  // 权限前缀
  permPrefix: "business:banner-info",
  table: {
    border: true,
    highlightCurrentRow: true,
  },
  // 主键
  pk: "id",
  // 列表查询接口
  indexAction: BannerInfoAPI.getPage,
  // 删除接口
  deleteAction: BannerInfoAPI.deleteByIds,
  // 数据解析函数
  parseData(res: any) {
    // console.log("列表数据", res);
    // console.log("IMAGE_BASE_URL:", IMAGE_BASE_URL);
    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: "picture",
      width: 120,
      templet: "image",
      imageWidth: 80,
      imageHeight: 60,
    },
    {
      label: "是否跳转",
      prop: "orJump",
      width: 100,
      align: "center",
      templet: "custom",
    },
    {
      label: "展示位置",
      prop: "location",
      width: 100,
      align: "center",
      templet: "custom",
    },
    {
      label: "跳转小程序appid",
      prop: "jumpAppid",
      minWidth: 150,
      templet: "format",
      formatter: (value: string) => {
        return value.jumpAppid || '无';
      },
    },
    {
      label: "跳转页面",
      prop: "jumpPage",
      minWidth: 200,
      templet: "format",
      formatter: (value: string) => {
        return value.jumpPage || '无';
      },
    },
    {
      label: "排序",
      prop: "sort",
      width: 80,
      align: "center",
    },
    {
      label: "状态",
      prop: "status",
      width: 100,
      align: "center",
      templet: "custom",
    },
    {
      label: "创建时间",
      prop: "createTime",
      width: 160,
    },
    {
      label: "更新时间",
      prop: "updateTime",
      width: 160,
    },
    {
      label: "操作",
      prop: "operation",
      width: 150,
      fixed: "right",
      templet: "tool",
      operat: ["edit", "delete"],
    },
  ],
});

// 新增配置
const addModalConfig: IModalConfig<BannerInfoForm> = reactive({
  // 权限前缀
  permPrefix: "business:banner-info",
  // 主键
  pk: "id",
  // 弹窗配置
  dialog: {
    title: "新增",
    width: 800,
    draggable: true,
  },
  form: {
    labelWidth: 100,
  },
  // 表单项配置
  formItems: [
    {
      type: "custom",
      label: "图片",
      prop: "picture",
      slotName: "picture",
      rules: [{ required: true, message: "请上传图片", trigger: "change" }],
    },
    {
      type: "custom",
      label: "是否跳转",
      prop: "orJump",
      slotName: "orJump",
      initialValue: 0,
      rules: [{ required: true, message: "请选择是否跳转", trigger: "change" }],
    },
    {
      type: "select",
      label: "banner位置",
      prop: "location",
      attrs: {
        placeholder: "请选择banner位置",
        clearable: true,
        style: { width: "200px" },
      },
      rlules: [{ required: true, message: "请选择是否跳转", trigger: "change" }],
      options: [
        { label: "首页", value: 1 },
        { label: "我的", value: 2 },
      ],
    },
    {
      type: "input",
      attrs: {
        placeholder: "请输入跳转小程序appid",
        clearable: true,
      },
      label: "跳转小程序appid",
      prop: "jumpAppid",
      hidden: true,
    },
    {
      type: "input",
      attrs: {
        placeholder: "请输入跳转页面路径",
        clearable: true,
      },
      label: "跳转页面",
      prop: "jumpPage",
      hidden: true,
    },
    {
      type: "input-number",
      attrs: {
        placeholder: "请输入排序值",
        min: 0,
        max: 9999,
        controlsPosition: "right",
        style: { width: "100%" },
      },
      label: "排序",
      prop: "sort",
      initialValue: 0,
      tips: "数值越大越靠前",
      rules: [{ required: true, message: "请输入排序值", trigger: "blur" }],
    },
    {
      type: "switch",
      attrs: {
        activeText: "生效",
        inactiveText: "无效",
        activeValue: 1,
        inactiveValue: 0,
      },
      initialValue: 1,
      label: "状态",
      prop: "status",
    },
  ],
  // 提交函数
  formAction: (data: BannerInfoForm) => {
    if (data.id) {
      // 编辑
      return BannerInfoAPI.update(data.id as string, data);
    } else {
      // 新增
      return BannerInfoAPI.create(data);
    }
  },
});

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

// 处理操作按钮点击
const handleOperateClick = (data: IObject) => {
  if (data.name === "edit") {
    handleEditClick(data.row, async () => {
      const formData = await BannerInfoAPI.getFormData(data.row.id);
      // 编辑时根据 orJump 的值设置显示/隐藏
      nextTick(() => {
        handleOrJumpChange(editModalConfig.formItems, formData.orJump);
      });
      return formData;
    });
  }
};

// 处理是否跳转变化
const handleOrJumpChange = (formItems: any[], value: number) => {
  const jumpAppidItem = formItems.find((item) => item.prop === "jumpAppid");
  const jumpPageItem = formItems.find((item) => item.prop === "jumpPage");

  if (jumpAppidItem && jumpPageItem) {
    // 当选择“跳转”（value === 1）时显示，否则隐藏
    jumpAppidItem.hidden = value !== 1;
    jumpPageItem.hidden = value !== 1;
  }
};

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