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

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

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

import UserExchangeIntegralRuleAPI, {
  UserExchangeIntegralRuleForm,
  UserExchangeIntegralRulePageQuery,
} from "@/api/operationsManage/user-exchange-integral-rule-api";
import type { IObject, IModalConfig, IContentConfig, ISearchConfig } from "@/components/CURD/types";
import usePage from "@/components/CURD/usePage";
import { ElMessageBox, ElMessage } from "element-plus";

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

// 搜索配置
const searchConfig: ISearchConfig = reactive({
  permPrefix: "business:user-exchange-integral-rule",
  formItems: [
    {
      type: "select",
      label: "是否启用", //（0-停用 1-启用）
      prop: "status",
      attrs: {
        placeholder: "是否启用", //（0-停用 1-启用）
        clearable: true,
        style: { width: "200px" },
      },
      options: [
        { label: "停用", value: 0 },
        { label: "启用", value: 1 },
      ],
    },
  ],
});

// 列表配置
const contentConfig: IContentConfig<UserExchangeIntegralRulePageQuery> = reactive({
  // 权限前缀
  permPrefix: "business:user-exchange-integral-rule",
  table: {
    border: true,
    highlightCurrentRow: true,
  },
  // 主键
  pk: "id",
  // 列表查询接口
  indexAction: UserExchangeIntegralRuleAPI.getPage,
  // 删除接口
  deleteAction: UserExchangeIntegralRuleAPI.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: "degree" },
    { label: "1度电获得的积分", prop: "gainIntegral" },
    {
      label: "是否启用", //（0-停用 1-启用）
      prop: "status",
      templet: "custom",
    },
    { label: "创建时间", prop: "createTime" },
    { label: "更新时间", prop: "updateTime" },
    {
      label: "操作",
      prop: "operation",
      width: 220,
      templet: "tool",
      operat: [
        {
          name: "switchs",
          text: (row: any) => (row.status === 1 ? "停用" : "启用"),
          attrs: (row: any) => ({
            type: row.status === 1 ? "danger" : "success",
            link: true,
            size: "small",
            icon: "open",
          }),
        },
        "edit",
        "delete",
      ],
    },
  ],
});

// 新增配置
const addModalConfig: IModalConfig<UserExchangeIntegralRuleForm> = reactive({
  // 权限前缀
  permPrefix: "business:user-exchange-integral-rule",
  // 主键
  pk: "id",
  // 弹窗配置
  dialog: {
    title: "新增",
    width: 800,
    draggable: true,
  },
  form: {
    labelWidth: 100,
  },
  // 表单项配置
  formItems: [
    {
      type: "input",
      attrs: {
        placeholder: "兑换度数基数", //（按照多少度进行兑换）
      },
      label: "兑换度数基数", //（按照多少度进行兑换）
      prop: "degree",
    },
    {
      type: "input",
      attrs: {
        placeholder: "1度电获得的积分", //（如1度1积分）
      },
      label: "1度电获得的积分", //（如1度1积分）
      prop: "gainIntegral",
    },
    {
      type: "switch",
      attrs: {
        activeText: "启用",
        inactiveText: "禁用",
        activeValue: 1,
        inactiveValue: 0,
      },
      initialValue: 1,
      label: "是否启用", //（0-停用 1-启用）
      prop: "status",
    },
  ],
  // 提交函数
  formAction: (data: UserExchangeIntegralRuleForm) => {
    if (data.id) {
      // 编辑
      return UserExchangeIntegralRuleAPI.update(data.id as string, data);
    } else {
      // 新增
      return UserExchangeIntegralRuleAPI.create(data);
    }
  },
});

// 编辑配置
const editModalConfig: IModalConfig<UserExchangeIntegralRuleForm> = reactive({
  permPrefix: "business:user-exchange-integral-rule",
  component: "drawer",
  drawer: {
    title: "编辑",
    size: 500,
  },
  pk: "id",
  formAction(data: any) {
    return UserExchangeIntegralRuleAPI.update(data.id as string, data);
  },
  formItems: [
    {
      type: "switch",
      attrs: {
        activeText: "启用",
        inactiveText: "禁用",
        activeValue: 1,
        inactiveValue: 0,
      },
      initialValue: 1,
      label: "是否启用", //（0-停用 1-启用）
      prop: "status",
    },
  ], // 复用新增的表单项
});

// 处理操作按钮点击
const handleOperateClick = (data: IObject) => {
  if (data.name === "edit") {
    handleEditClick(data.row, async () => {
      return await UserExchangeIntegralRuleAPI.getFormData(data.row.id);
    });
  }
  if (data.name === "switchs") {
    ElMessageBox.confirm(
      `只能启用一条规则，确认要${data.row.status === 1 ? "停用" : "启用"}该兑换规则吗？`,
      "提示",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }
    )
      .then(() => {
        UserExchangeIntegralRuleAPI.enable(data.row.id).then(() => {
          ElMessage.success(`${data.row.status === 1 ? "停用" : "启用"}成功`);
          contentRef.value?.handleRefresh();
        });
      })
      .catch(() => {
        // ElMessage.info(err);
      });
  }
};

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