<template>
  <div class="layout-padding">
    <div class="layout-padding-auto layout-padding-view">

      <el-row>
        <div class="mb8" style="width: 100%">
          <el-button
            icon="folder-add"
            type="primary"
            class="ml10"
            @click="formDialogRef.openDialog()"
            v-auth="'purchase_purchasingruleconfig_add'"
          >
            新增规则
          </el-button>
          <el-button
            plain
            :disabled="multiple"
            icon="Delete"
            type="primary"
            v-auth="'purchase_purchasingruleconfig_del'"
            @click="handleDelete(selectObjs)"
          >
            删除
          </el-button>
          <right-toolbar
            v-model:showSearch="showSearch"
            class="ml10 mr20"
            style="float: right;"
            @queryTable="getDataList"
          />
        </div>
      </el-row>

      <el-alert type="warning" :closable="false">既定规则请不要随意修改，否则会出错</el-alert>
      <el-table
        :data="state.dataList"
        v-loading="state.loading"
        border
        :cell-style="tableStyle.cellStyle"
        :header-cell-style="tableStyle.headerCellStyle"
        @selection-change="selectionChangHandle"
      >
        <el-table-column type="selection" width="40" align="center" />
        <el-table-column type="index" label="#" width="50" />
        <el-table-column prop="ruleCode" label="规则编码" width="180" show-overflow-tooltip />
        <el-table-column prop="ruleName" label="规则名称" min-width="200" show-overflow-tooltip />
        <el-table-column prop="ruleTypeName" label="规则类型" width="120" />
        <el-table-column label="金额区间" width="180">
          <template #default="scope">
            <span v-if="scope.row.amountMin || scope.row.amountMax">
              {{ formatAmount(scope.row.amountMin) }} ~ {{ formatAmount(scope.row.amountMax) }}
            </span>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column label="附加条件" width="150">
          <template #default="scope">
            <span v-if="scope.row.conditionField">
              {{ getConditionLabel(scope.row.conditionField) }} = {{ scope.row.conditionValue }}
            </span>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column prop="actionTypeName" label="动作类型" width="100" />
        <el-table-column prop="description" label="规则描述" min-width="250" show-overflow-tooltip />
        <el-table-column prop="sortOrder" label="优先级" width="80" align="center" />
        <el-table-column label="状态" width="80" align="center">
          <template #default="scope">
            <el-tag :type="scope.row.isEnabled === '1' ? 'success' : 'danger'" size="small">
              {{ scope.row.isEnabled === '1' ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="scope">
            <el-button
              icon="edit-pen"
              text
              type="primary"
              v-auth="'purchase_purchasingruleconfig_edit'"
              @click="formDialogRef.openDialog(scope.row.id)"
            >
              编辑
            </el-button>
            <el-button
              icon="delete"
              text
              type="primary"
              v-auth="'purchase_purchasingruleconfig_del'"
              @click="handleDelete([scope.row.id])"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        @size-change="sizeChangeHandle"
        @current-change="currentChangeHandle"
        v-bind="state.pagination"
      />
    </div>

    <form-dialog ref="formDialogRef" @refresh="getDataList(false)" />
  </div>
</template>

<script setup lang="ts" name="purchasingRuleConfig">
import { BasicTableProps, useTable } from "/@/hooks/table";
import { fetchList, delObjs } from "/@/api/purchase/purchasingRuleConfig";
import { useMessage, useMessageBox } from "/@/hooks/message";

const FormDialog = defineAsyncComponent(() => import('./form.vue'));

const formDialogRef = ref();
const queryRef = ref();
const showSearch = ref(true);
const selectObjs = ref([]) as any;
const multiple = ref(true);

const state: BasicTableProps = reactive<BasicTableProps>({
  queryForm: {},
  pageList: fetchList
});

const {
  getDataList,
  currentChangeHandle,
  sizeChangeHandle,
  tableStyle
} = useTable(state);

const selectionChangHandle = (objs: { id: string }[]) => {
  selectObjs.value = objs.map(({ id }) => id);
  multiple.value = !objs.length;
};

const handleDelete = async (ids: string[]) => {
  try {
    await useMessageBox().confirm('此操作将永久删除该规则，是否继续？');
  } catch {
    return;
  }

  try {
    await delObjs(ids);
    getDataList();
    useMessage().success('删除成功');
  } catch (err: any) {
    useMessage().error(err.msg || '删除失败');
  }
};

const formatAmount = (amount: number | null) => {
  if (amount === null || amount === undefined) return '不限';
  return (amount / 10000).toFixed(0) + '万';
};

const getConditionLabel = (field: string) => {
  const map: Record<string, string> = {
    isCentralized: '是否集采',
    isSpecial: '是否特殊',
    hasSupplier: '是否有推荐供应商',
    projectType: '项目类别'
  };
  return map[field] || field;
};
</script>