<script lang="ts">
export default { name: 'stakingConfig' };
</script>

<script setup lang="ts">
import { computed, onMounted, reactive, ref, toRefs, watch } from 'vue';
import { ElForm, ElMessage } from 'element-plus';
import { Plus } from '@element-plus/icons-vue';
import { addStakingConfig, listStakingConfigs, updateStakingConfig } from '@/api/staking/index';
import { getTopCoinNames } from '@/api/system/coin';
import { StakingConfigItem } from '@/types/api/staking/index';

const dataFormRef = ref(ElForm);

const RELEASE_TYPE_MAP: Record<number, string> = { 0: '到期一次性', 1: '分批释放' };
function ratioToPercentDisplay(ratio: number | string | undefined | null): string {
  const r = Number(ratio);
  if (!r || Number.isNaN(r)) return '0';
  const pct = r * 100;
  return String(Math.round(pct * 10000) / 10000);
}

function percentToRatio(percent: number | string | undefined | null): number {
  const p = Number(percent);
  if (!p || Number.isNaN(p)) return 0;
  return p / 100;
}

/** 100 ÷ 分批周期（%），保留 4 位小数向上取整 */
function calcReleasePercentDisplay(period: number | string | undefined | null): string {
  const p = Number(period);
  if (!p || p <= 0 || Number.isNaN(p)) return '0';
  const pct = Math.ceil((100 / p) * 10000) / 10000;
  return String(pct);
}

/** 库内释放比例小数 */
function calcStorageReleaseRate(period: number | string | undefined | null): number {
  return Number(calcReleasePercentDisplay(period)) / 100;
}

function formatBatchPercent(row: StakingConfigItem): string {
  if (row.releaseType !== 1) return '-';
  return `${calcReleasePercentDisplay(row.releasePeriod)}%`;
}

const state = reactive({
  loading: false,
  list: [] as StakingConfigItem[],
  coinOptions: [] as { name: string; unit: string }[],
  dialog: { title: '', visible: false, loading: false },
  isCreate: true,
  formData: {
    productName: '',
    coinUnit: '',
    minAmount: '',
    maxAmount: '0',
    lockDays: 30,
    releaseType: 0,
    releasePeriod: 1,
    releaseRate: '0',
    description: '',
    status: 1,
    autoAirdropEnabled: 0,
    airdropDistributeType: 0,
    airdropFixedAmount: '',
    airdropRatioPercent: '0'
  } as StakingConfigItem & { airdropRatioPercent?: string },
  rules: {
    productName: [{ required: true, message: '请输入产品名称', trigger: 'blur' }],
    coinUnit: [{ required: true, message: '请选择质押币种', trigger: 'change' }],
    minAmount: [{ required: true, message: '请输入最小质押额', trigger: 'blur' }],
    lockDays: [{ required: true, message: '请输入锁定天数', trigger: 'blur' }],
    releasePeriod: [
      {
        validator: (_rule: unknown, value: unknown, callback: (err?: Error) => void) => {
          if (Number(state.formData.releaseType) !== 1) {
            callback();
            return;
          }
          const p = Number(value);
          if (!value || Number.isNaN(p) || p < 1) {
            callback(new Error('分批释放时分批周期必填且须大于0'));
            return;
          }
          callback();
        },
        trigger: ['blur', 'change']
      }
    ],
    airdropFixedAmount: [
      {
        validator: (_rule: unknown, value: unknown, callback: (err?: Error) => void) => {
          if (Number(state.formData.autoAirdropEnabled) !== 1) {
            callback();
            return;
          }
          if (Number(state.formData.airdropDistributeType) !== 0) {
            callback();
            return;
          }
          const v = Number(value);
          if (!value || Number.isNaN(v) || v <= 0) {
            callback(new Error('固定发放时空投金额须大于0'));
            return;
          }
          callback();
        },
        trigger: 'blur'
      }
    ],
    airdropRatioPercent: [
      {
        validator: (_rule: unknown, value: unknown, callback: (err?: Error) => void) => {
          if (Number(state.formData.autoAirdropEnabled) !== 1) {
            callback();
            return;
          }
          if (Number(state.formData.airdropDistributeType) !== 1) {
            callback();
            return;
          }
          const v = Number(value);
          if (!value || Number.isNaN(v) || v <= 0) {
            callback(new Error('按比例发放时请填写大于0的比例(%)'));
            return;
          }
          callback();
        },
        trigger: 'blur'
      }
    ]
  }
});

const { loading, list, coinOptions, dialog, formData, rules, isCreate } = toRefs(state);

const formRules = computed(() => rules.value);

function syncAutoReleaseRate() {
  if (Number(state.formData.releaseType) !== 1) {
    state.formData.releaseRate = '0';
    return;
  }
  state.formData.releaseRate = calcReleasePercentDisplay(state.formData.releasePeriod);
}

function buildSubmitPayload(form: StakingConfigItem & { airdropRatioPercent?: string }): StakingConfigItem {
  const payload: StakingConfigItem = JSON.parse(JSON.stringify(form));
  if (Number(payload.releaseType) === 1) {
    payload.releaseRate = calcStorageReleaseRate(payload.releasePeriod);
  } else {
    payload.releaseRate = 0;
  }
  if (Number(payload.autoAirdropEnabled) !== 1) {
    payload.autoAirdropEnabled = 0;
    payload.airdropDistributeType = 0;
    payload.airdropFixedAmount = 0;
    payload.airdropRatio = 0;
  } else if (Number(payload.airdropDistributeType) === 1) {
    payload.airdropRatio = percentToRatio(form.airdropRatioPercent);
    payload.airdropFixedAmount = 0;
  } else {
    payload.airdropRatio = 0;
  }
  delete (payload as { airdropRatioPercent?: string }).airdropRatioPercent;
  return payload;
}

function formatAutoAirdrop(row: StakingConfigItem): string {
  if (Number(row.autoAirdropEnabled) !== 1) return '否';
  if (Number(row.airdropDistributeType) === 1) {
    return `自动 / ${ratioToPercentDisplay(row.airdropRatio)}%`;
  }
  return `自动 / 固定 ${row.airdropFixedAmount ?? 0}`;
}

watch(
  () => [state.formData.releaseType, state.formData.releasePeriod],
  () => syncAutoReleaseRate()
);

function fetchCoinOptions() {
  getTopCoinNames().then((res: any) => {
    const list = Array.isArray(res?.data) ? res.data : [];
    state.coinOptions = list.filter((item: { unit?: string }) => item?.unit);
  });
}

function handleQuery() {
  state.loading = true;
  listStakingConfigs()
    .then(({ data }: any) => {
      state.list = data || [];
    })
    .finally(() => {
      state.loading = false;
    });
}

function handleAdd() {
  state.isCreate = true;
  state.dialog = { title: '新增质押配置', visible: true, loading: false };
  fetchCoinOptions();
  state.formData = {
    productName: '',
    coinUnit: '',
    minAmount: '',
    maxAmount: '0',
    lockDays: 30,
    releaseType: 0,
    releasePeriod: 1,
    releaseRate: '0',
    description: '',
    status: 1,
    autoAirdropEnabled: 0,
    airdropDistributeType: 0,
    airdropFixedAmount: '',
    airdropRatioPercent: '0'
  };
  syncAutoReleaseRate();
}

function handleEdit(row: StakingConfigItem) {
  state.isCreate = false;
  state.dialog = { title: '修改质押配置', visible: true, loading: false };
  state.formData = {
    ...row,
    airdropRatioPercent: ratioToPercentDisplay(row.airdropRatio)
  };
  syncAutoReleaseRate();
  fetchCoinOptions();
}

function submitFormData() {
  syncAutoReleaseRate();
  dataFormRef.value.validate((valid: boolean) => {
    if (!valid) return;
    state.dialog.loading = true;
    const api = state.isCreate ? addStakingConfig : updateStakingConfig;
    api(buildSubmitPayload(state.formData))
      .then(() => {
        ElMessage.success(state.isCreate ? '添加成功' : '修改成功');
        state.dialog.visible = false;
        handleQuery();
      })
      .finally(() => {
        state.dialog.loading = false;
      });
  });
}

onMounted(() => {
  handleQuery();
  fetchCoinOptions();
});
</script>

<template>
  <div class="app-container">
    <el-form :inline="true">
      <el-form-item>
        <el-button type="success" :icon="Plus" @click="handleAdd">新增配置</el-button>
      </el-form-item>
    </el-form>

    <el-table v-loading="loading" :data="list" border highlight-current-row height="520">
      <el-table-column label="ID" prop="id" width="70" align="center" />
      <el-table-column label="产品名称" prop="productName" min-width="140" show-overflow-tooltip />
      <el-table-column label="币种" prop="coinUnit" width="100" align="center" />
      <el-table-column label="最小金额" prop="minAmount" min-width="120" align="center" />
      <el-table-column label="最大金额" prop="maxAmount" min-width="120" align="center">
        <template #default="{ row }">{{ row.maxAmount == 0 ? '不限' : row.maxAmount }}</template>
      </el-table-column>
      <el-table-column label="锁定天数" prop="lockDays" width="100" align="center" />
      <el-table-column label="释放类型" prop="releaseType" width="110" align="center">
        <template #default="{ row }">{{ RELEASE_TYPE_MAP[row.releaseType] ?? row.releaseType }}</template>
      </el-table-column>
      <el-table-column label="分批周期(天)" prop="releasePeriod" width="110" align="center">
        <template #default="{ row }">
          {{ row.releaseType === 1 ? row.releasePeriod : '-' }}
        </template>
      </el-table-column>
      <el-table-column label="分批比例(%)" width="110" align="center">
        <template #default="{ row }">{{ formatBatchPercent(row) }}</template>
      </el-table-column>
      <el-table-column label="描述" prop="description" min-width="160" show-overflow-tooltip />
      <el-table-column label="自动空投" min-width="140" align="center">
        <template #default="{ row }">{{ formatAutoAirdrop(row) }}</template>
      </el-table-column>
      <el-table-column label="状态" prop="status" width="80" align="center">
        <template #default="{ row }">
          <el-tag :type="row.status === 1 ? 'success' : 'info'" size="small">
            {{ row.status === 1 ? '启用' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" prop="createTime" min-width="160" align="center" />
      <el-table-column label="更新时间" prop="updateTime" min-width="160" align="center" />
      <el-table-column label="操作" width="90" align="center" fixed="right">
        <template #default="{ row }">
          <el-link @click="handleEdit(row)">修改</el-link>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog v-model="dialog.visible" :title="dialog.title" width="560px" destroy-on-close>
      <el-form ref="dataFormRef" :model="formData" :rules="formRules" label-width="130px">
        <el-form-item label="产品名称" prop="productName">
          <el-input v-model="formData.productName" placeholder="如 IBIT 30天质押" maxlength="100" show-word-limit />
        </el-form-item>
        <el-form-item label="质押币种" prop="coinUnit">
          <el-select
            v-model="formData.coinUnit"
            placeholder="请选择质押币种"
            filterable
            clearable
            :disabled="!isCreate"
            style="width: 100%"
          >
            <el-option
              v-for="item in coinOptions"
              :key="item.unit"
              :label="`${item.name} (${item.unit})`"
              :value="item.unit"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="最小质押额" prop="minAmount">
          <el-input v-model="formData.minAmount" />
        </el-form-item>
        <el-form-item label="最大质押额">
          <el-input v-model="formData.maxAmount" placeholder="0 表示不限" />
        </el-form-item>
        <el-form-item label="锁定天数" prop="lockDays">
          <el-input-number v-model="formData.lockDays" :min="1" />
        </el-form-item>
        <el-form-item label="释放类型">
          <el-radio-group v-model="formData.releaseType">
            <el-radio :label="0">到期一次性</el-radio>
            <el-radio :label="1">分批释放</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          v-if="formData.releaseType === 1"
          label="分批周期(天)"
          prop="releasePeriod"
          required
        >
          <el-input-number v-model="formData.releasePeriod" :min="1" />
        </el-form-item>
        <el-form-item v-if="formData.releaseType === 1" label="每批释放比例(%)">
          <el-input v-model="formData.releaseRate" disabled>
            <template #append>%</template>
          </el-input>
          <div class="form-tip">自动计算：100 ÷ 分批周期，保留 4 位小数向上取整</div>
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="formData.description" type="textarea" />
        </el-form-item>
        <el-form-item label="自动发放空投">
          <el-radio-group v-model="formData.autoAirdropEnabled">
            <el-radio :label="0">否</el-radio>
            <el-radio :label="1">是</el-radio>
          </el-radio-group>
          <div class="form-tip">开启后每日定时任务向质押中且当日未发放的订单创建待领取记录</div>
        </el-form-item>
        <template v-if="formData.autoAirdropEnabled === 1">
          <el-form-item label="空投发放方式">
            <el-radio-group v-model="formData.airdropDistributeType">
              <el-radio :label="0">固定金额</el-radio>
              <el-radio :label="1">按质押金额比例</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item
            v-if="formData.airdropDistributeType === 0"
            label="固定发放金额"
            prop="airdropFixedAmount"
          >
            <el-input v-model="formData.airdropFixedAmount" placeholder="每日每单发放数量" />
          </el-form-item>
          <el-form-item
            v-else
            label="空投比例(%)"
            prop="airdropRatioPercent"
          >
            <el-input v-model="formData.airdropRatioPercent" placeholder="如 1 表示质押金额的 1%">
            <template #append>%</template>
            </el-input>
            <div class="form-tip">按订单质押总金额 × 比例计算，保留 8 位小数向下取整</div>
          </el-form-item>
        </template>
        <el-form-item label="状态">
          <el-radio-group v-model="formData.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialog.visible = false">取消</el-button>
        <el-button type="primary" :loading="dialog.loading" @click="submitFormData">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.form-tip {
  margin-top: 4px;
  font-size: 12px;
  color: #909399;
  line-height: 1.4;
}
</style>
