<template>
  <div v-loading="pageLoading" class="app-container" :element-loading-text="loadingText">
    <PageSearch
      ref="searchRef"
      :search-config="searchConfig"
      @query-click="handleQueryClick"
      @reset-click="handleResetClick"
    />

    <PageContent ref="contentRef" :content-config="contentConfig">
      <template #toolbar="{ toolbarRight, onToolbar, removeIds, cols }">
        <CrudToolbarLeft
          :remove-ids="removeIds"
          :perm-create="['module_payment:rule:create']"
          @add="handleOpenDialog('create')"
        />
        <div class="data-table__toolbar--right">
          <CrudToolbarRight :buttons="toolbarRight" :cols="cols" :on-toolbar="onToolbar" />
        </div>
      </template>

      <template #table="{ data, loading, tableRef, onSelectionChange }">
        <div class="data-table__content">
          <el-table
            :ref="tableRef as any"
            v-loading="loading"
            :data="data"
            height="100%"
            border
            @selection-change="onSelectionChange"
          >
            <template #empty>
              <el-empty :image-size="80" description="暂无数据" />
            </template>
            <el-table-column
              v-if="contentCols.find((col) => col.prop === 'selection')?.show"
              type="selection"
              min-width="55"
              align="center"
            />
            <el-table-column
              v-if="contentCols.find((col) => col.prop === 'rule_id')?.show"
              key="rule_id"
              label="规则ID"
              prop="rule_id"
              min-width="150"
              show-overflow-tooltip
            />
            <el-table-column
              v-if="contentCols.find((col) => col.prop === 'institution_id')?.show"
              key="institution_id"
              label="制度ID"
              prop="institution_id"
              min-width="150"
              show-overflow-tooltip
            />
            <el-table-column
              v-if="contentCols.find((col) => col.prop === 'name')?.show"
              key="name"
              label="规则名称"
              prop="name"
              min-width="150"
              show-overflow-tooltip
            />
            <el-table-column
              v-if="contentCols.find((col) => col.prop === 'max_amount')?.show"
              key="max_amount"
              label="单笔限额"
              prop="max_amount"
              min-width="100"
              align="right"
            >
              <template #default="scope">
                {{ scope.row.max_amount ? `¥${scope.row.max_amount.toFixed(2)}` : "-" }}
              </template>
            </el-table-column>
            <el-table-column
              v-if="contentCols.find((col) => col.prop === 'max_day_amount')?.show"
              key="max_day_amount"
              label="日限额"
              prop="max_day_amount"
              min-width="100"
              align="right"
            >
              <template #default="scope">
                {{ scope.row.max_day_amount ? `¥${scope.row.max_day_amount.toFixed(2)}` : "-" }}
              </template>
            </el-table-column>
            <el-table-column
              v-if="contentCols.find((col) => col.prop === 'max_month_amount')?.show"
              key="max_month_amount"
              label="月限额"
              prop="max_month_amount"
              min-width="100"
              align="right"
            >
              <template #default="scope">
                {{ scope.row.max_month_amount ? `¥${scope.row.max_month_amount.toFixed(2)}` : "-" }}
              </template>
            </el-table-column>
            <el-table-column
              v-if="contentCols.find((col) => col.prop === 'created_time')?.show"
              key="created_time"
              label="创建时间"
              prop="created_time"
              min-width="160"
              sortable
            />
            <el-table-column
              v-if="contentCols.find((col) => col.prop === 'operation')?.show"
              fixed="right"
              label="操作"
              align="center"
              min-width="160"
            >
              <template #default="scope">
                <el-button
                  v-hasPerm="['module_payment:rule:detail']"
                  type="info"
                  size="small"
                  link
                  icon="View"
                  @click="handleOpenDialog('detail', scope.row.rule_id)"
                >
                  详情
                </el-button>
                <el-button
                  v-hasPerm="['module_payment:rule:update']"
                  type="primary"
                  size="small"
                  link
                  icon="edit"
                  @click="handleOpenDialog('update', scope.row.rule_id)"
                >
                  编辑
                </el-button>
                <el-button
                  v-hasPerm="['module_payment:rule:delete']"
                  type="danger"
                  size="small"
                  link
                  icon="delete"
                  @click="handleDelete(scope.row.rule_id)"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </template>
    </PageContent>

    <EnhancedDialog
      v-model="dialogVisible.visible"
      :title="dialogVisible.title"
      @close="handleCloseDialog"
    >
      <template v-if="dialogVisible.type === 'detail'">
        <RuleDetail :rule-id="currentRuleId" />
      </template>
      <template v-else>
        <RuleForm
          ref="formRef"
          :type="dialogVisible.type"
          :rule-id="currentRuleId"
          :institution-id="institutionIdFromUrl"
          @success="handleFormSuccess"
        />
      </template>

      <template #footer>
        <div class="dialog-footer">
          <el-button v-if="dialogVisible.type !== 'detail'" type="primary" @click="handleSubmit">
            确定
          </el-button>
          <el-button v-else type="primary" @click="handleCloseDialog">确定</el-button>
          <el-button @click="handleCloseDialog">取消</el-button>
        </div>
      </template>
    </EnhancedDialog>
  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: "Rule",
  inheritAttrs: false,
});

import RuleAPI, { RulePageQuery } from "@/api/module_payment/rule";
import CrudToolbarLeft from "@/components/CURD/CrudToolbarLeft.vue";
import CrudToolbarRight from "@/components/CURD/CrudToolbarRight.vue";
import PageSearch from "@/components/CURD/PageSearch.vue";
import PageContent from "@/components/CURD/PageContent.vue";
import EnhancedDialog from "@/components/CURD/EnhancedDialog.vue";
import RuleForm from "./components/RuleForm.vue";
import RuleDetail from "./components/RuleDetail.vue";
import type { ISearchConfig, IContentConfig } from "@/components/CURD/types";
import { useCrudList } from "@/components/CURD/useCrudList";
import { useLoadingAction } from "@/composables/useLoadingAction";
import { useRoute } from "vue-router";
import { ElMessage } from "element-plus";
import { ref, reactive, computed } from "vue";

const route = useRoute();

const { searchRef, contentRef, handleQueryClick, handleResetClick, refreshList } =
  useCrudList();
const formRef = ref();

const { pageLoading, loadingText, execute: loadingExecute } = useLoadingAction();

const institutionIdFromUrl = computed(() => route.query.institution_id as string | undefined);

const searchConfig = reactive<ISearchConfig>({
  permPrefix: "module_payment:rule",
  colon: true,
  isExpandable: true,
  showNumber: 2,
  form: { labelWidth: "auto" },
  formItems: [
    {
      prop: "institution_id",
      label: "制度ID",
      type: "input",
      attrs: { placeholder: "请输入制度ID", clearable: true },
    },
    {
      prop: "name",
      label: "规则名称",
      type: "input",
      attrs: { placeholder: "请输入规则名称", clearable: true },
    },
  ],
});

const contentCols = reactive<
  Array<{
    prop?: string;
    label?: string;
    show?: boolean;
  }>
>([
  { prop: "selection", label: "选择框", show: false },
  { prop: "index", label: "序号", show: true },
  { prop: "rule_id", label: "规则ID", show: true },
  { prop: "institution_id", label: "制度ID", show: true },
  { prop: "name", label: "规则名称", show: true },
  { prop: "max_amount", label: "单笔限额", show: true },
  { prop: "max_day_amount", label: "日限额", show: true },
  { prop: "max_month_amount", label: "月限额", show: true },
  { prop: "created_time", label: "创建时间", show: true },
  { prop: "operation", label: "操作", show: true },
]);

const contentConfig = reactive<IContentConfig<RulePageQuery>>({
  permPrefix: "module_payment:rule",
  pk: "rule_id",
  cols: contentCols as IContentConfig["cols"],
  hideColumnFilter: false,
  toolbar: [],
  defaultToolbar: ["refresh", "filter"],
  pagination: true,
  request: { page_no: "page_no", page_size: "page_size" },
  initialParams: computed(() => ({
    institution_id: institutionIdFromUrl.value,
  })) as Record<string, unknown>,
  indexAction: async (params) => {
    const query: RulePageQuery = {
      page_no: params.page_no,
      page_size: params.page_size,
    };
    if (params.institution_id) query.institution_id = params.institution_id;
    if (params.name) query.name = params.name;
    const res = await RuleAPI.listRule(query);
    return {
      list: res.data.data?.items || res.data.data?.list || [],
      total: res.data.data?.total || 0,
    };
  },
});

const dialogVisible = reactive({
  title: "",
  visible: false,
  type: "create" as "create" | "update" | "detail",
});

const currentRuleId = ref<string>();

function handleOpenDialog(type: "create" | "update" | "detail", ruleId?: string) {
  dialogVisible.type = type;
  currentRuleId.value = ruleId;
  if (type === "create") {
    dialogVisible.title = "创建使用规则";
  } else if (type === "update") {
    dialogVisible.title = "编辑使用规则";
  } else {
    dialogVisible.title = "使用规则详情";
  }
  dialogVisible.visible = true;
}

async function handleCloseDialog() {
  dialogVisible.visible = false;
}

function handleSubmit() {
  formRef.value?.submitForm();
}

function handleFormSuccess() {
  dialogVisible.visible = false;
  refreshList();
}

async function handleDelete(ruleId?: string) {
  if (!ruleId) return;
  await loadingExecute({
    confirmMessage: "确认删除该使用规则?",
    confirmTitle: "警告",
    confirmType: "warning",
    loadingText: "正在删除...",
    action: () => RuleAPI.deleteRule(ruleId),
    onSuccess: () => {
      ElMessage.success("删除成功");
      refreshList();
    },
  });
}
</script>