<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import { getConfigList, updateConfig } from "@/api/distribution";
import type { DistributorConfig } from "../utils/types";
import { message } from "@/utils/message";

defineOptions({
  name: "DistributionConfig"
});

const loading = ref(false);
const saving = ref(false);

const configList = ref<DistributorConfig[]>([]);

const form = reactive({
  fixedCommissionAmount: 0,
  firstOrderRate: 0,
  validUserRule: "FIRST_ORDER",
  minConsumeAmount: 0,
  validTimeWindow: 0,
  minWithdrawAmount: 0
});

const validUserRuleOptions = [
  { label: "首单完成", value: "FIRST_ORDER" },
  { label: "最低消费金额", value: "MIN_AMOUNT" },
  { label: "首单且最低金额", value: "BOTH" }
];

// configKey 与 form 字段的映射
const configKeyMap: Record<string, string> = {
  FIXED_COMMISSION_AMOUNT: "fixedCommissionAmount",
  FIRST_ORDER_RATE: "firstOrderRate",
  VALID_USER_RULE: "validUserRule",
  MIN_CONSUME_AMOUNT: "minConsumeAmount",
  VALID_TIME_WINDOW: "validTimeWindow",
  MIN_WITHDRAW_AMOUNT: "minWithdrawAmount"
};

// form 字段与 configKey 的反向映射
const formKeyToConfigKey: Record<string, string> = {};
for (const [key, val] of Object.entries(configKeyMap)) {
  formKeyToConfigKey[val] = key;
}

async function fetchConfigList() {
  loading.value = true;
  try {
    const { data } = await getConfigList();
    if (data) {
      configList.value = Array.isArray(data) ? data : data.list || [];
      // 将配置列表映射到表单字段
      for (const config of configList.value) {
        const formKey = configKeyMap[config.configKey];
        if (formKey) {
          if (config.configKey === "VALID_USER_RULE") {
            (form as any)[formKey] = config.configValue;
          } else {
            (form as any)[formKey] = Number(config.configValue) || 0;
          }
        }
      }
    }
  } catch (error) {
    console.error("获取分销配置失败:", error);
  } finally {
    loading.value = false;
  }
}

async function handleSave() {
  saving.value = true;
  try {
    // 遍历所有配置项，逐个更新
    for (const config of configList.value) {
      const formKey = configKeyMap[config.configKey];
      if (formKey) {
        const newValue = String((form as any)[formKey]);
        // 仅更新有变化的配置
        if (newValue !== config.configValue) {
          await updateConfig({
            id: config.id,
            configKey: config.configKey,
            configValue: newValue
          });
        }
      }
    }
    message("配置保存成功", { type: "success" });
    // 重新加载配置以获取最新数据
    await fetchConfigList();
  } catch (error) {
    console.error("保存分销配置失败:", error);
    message("配置保存失败", { type: "error" });
  } finally {
    saving.value = false;
  }
}

onMounted(() => {
  fetchConfigList();
});
</script>

<template>
  <div class="main">
    <el-card v-loading="loading">
      <template #header>
        <span class="font-semibold">分销配置</span>
      </template>

      <el-form
        label-position="left"
        label-width="180px"
        style="max-width: 600px"
      >
        <el-form-item label="固定佣金金额 (元/人)">
          <el-input-number
            v-model="form.fixedCommissionAmount"
            :min="0"
            :precision="2"
            controls-position="right"
          />
        </el-form-item>

        <el-form-item label="首单佣金比例 (%)">
          <el-input-number
            v-model="form.firstOrderRate"
            :min="0"
            :max="100"
            :precision="2"
            controls-position="right"
          />
        </el-form-item>

        <el-form-item label="有效用户判定规则">
          <el-select v-model="form.validUserRule" style="width: 100%">
            <el-option
              v-for="item in validUserRuleOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="最低消费金额 (元)">
          <el-input-number
            v-model="form.minConsumeAmount"
            :min="0"
            :precision="2"
            controls-position="right"
          />
        </el-form-item>

        <el-form-item label="有效时间窗口 (天，0表示不限)">
          <el-input-number
            v-model="form.validTimeWindow"
            :min="0"
            controls-position="right"
          />
        </el-form-item>

        <el-form-item label="最低提现金额 (元)">
          <el-input-number
            v-model="form.minWithdrawAmount"
            :min="0"
            :precision="2"
            controls-position="right"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" :loading="saving" @click="handleSave">
            保存配置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<style lang="scss" scoped></style>
