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

<script setup lang="ts">
import { computed, onMounted, reactive, ref, toRefs } from 'vue';
import { ElForm, ElMessage, ElMessageBox } from 'element-plus';
import { Refresh, Search } from '@element-plus/icons-vue';
import {
  batchDistributeAirdropForOrders,
  distributeAirdropForOrder,
  listStakingOrders
} from '@/api/staking/index';
import { StakingOrderItem } from '@/types/api/staking/index';

const queryFormRef = ref(ElForm);
const dataFormRef = ref(ElForm);
const batchFormRef = ref(ElForm);

const ORDER_STATUS: Record<number, { label: string; type: string }> = {
  0: { label: '质押中', type: 'warning' },
  1: { label: '解冻释放中', type: '' },
  2: { label: '已完成', type: 'success' }
};

const state = reactive({
  loading: false,
  queryParams: {
    pageNo: 1,
    pageSize: 15,
    status: '' as number | '',
    memberId: '',
    coinUnit: '',
    pendingAirdropToday: false
  },
  list: [] as StakingOrderItem[],
  total: 0,
  selectedRows: [] as StakingOrderItem[],
  dialog: { visible: false, loading: false },
  batchDialog: { visible: false, loading: false },
  currentOrder: null as StakingOrderItem | null,
  distributeForm: { amount: '' },
  batchForm: { amount: '' },
  distributeRules: {
    amount: [{ required: true, message: '请输入发放金额', trigger: 'blur' }]
  },
  batchRules: {
    amount: [{ required: true, message: '请输入发放金额', trigger: 'blur' }]
  }
});

const {
  loading, queryParams, list, total, selectedRows,
  dialog, batchDialog, currentOrder, distributeForm, batchForm,
  distributeRules, batchRules
} = toRefs(state);

const selectableCount = computed(() =>
  state.selectedRows.filter((r) => r.canDistributeAirdropToday).length
);

function airdropStatusLabel(row: StakingOrderItem) {
  if (row.status !== 0) return '不可发放';
  if (row.todayAirdropDistributed) return '已发放';
  return '未发放';
}

function airdropStatusType(row: StakingOrderItem) {
  if (row.status !== 0) return 'info';
  if (row.todayAirdropDistributed) return 'success';
  return 'warning';
}

function rowSelectable(row: StakingOrderItem) {
  return !!row.canDistributeAirdropToday;
}

function handleQuery() {
  state.loading = true;
  const params: Record<string, unknown> = {
    pageNo: state.queryParams.pageNo,
    pageSize: state.queryParams.pageSize
  };
  if (state.queryParams.status !== '') params.status = state.queryParams.status;
  if (state.queryParams.memberId !== '') params.memberId = state.queryParams.memberId;
  if (state.queryParams.coinUnit) params.coinUnit = state.queryParams.coinUnit;
  if (state.queryParams.pendingAirdropToday) params.pendingAirdropToday = true;

  listStakingOrders(params as any)
    .then(({ data }: any) => {
      state.list = data.content;
      state.total = data.totalElements;
    })
    .finally(() => {
      state.loading = false;
    });
}

function resetQuery() {
  queryFormRef.value?.resetFields();
  state.queryParams.pageNo = 1;
  state.queryParams.status = '';
  state.queryParams.memberId = '';
  state.queryParams.coinUnit = '';
  state.queryParams.pendingAirdropToday = false;
  handleQuery();
}

function handleSelectionChange(rows: StakingOrderItem[]) {
  state.selectedRows = rows;
}

function handleDistribute(row: StakingOrderItem) {
  state.currentOrder = row;
  state.distributeForm.amount = '';
  state.dialog.visible = true;
}

function handleBatchDistribute() {
  const eligible = state.selectedRows.filter((r) => r.canDistributeAirdropToday);
  if (!eligible.length) {
    ElMessage.warning('请勾选今日可发放的质押中订单');
    return;
  }
  state.batchForm.amount = '';
  state.batchDialog.visible = true;
}

function submitDistribute() {
  if (!state.currentOrder) return;
  dataFormRef.value.validate((valid: boolean) => {
    if (!valid) return;
    state.dialog.loading = true;
    distributeAirdropForOrder({
      memberId: state.currentOrder!.memberId,
      coinUnit: state.currentOrder!.coinUnit,
      amount: state.distributeForm.amount,
      stakingOrderId: state.currentOrder!.id
    })
      .then(() => {
        ElMessage.success('空投发放成功');
        state.dialog.visible = false;
        handleQuery();
      })
      .finally(() => {
        state.dialog.loading = false;
      });
  });
}

function submitBatchDistribute() {
  batchFormRef.value.validate((valid: boolean) => {
    if (!valid) return;
    const eligible = state.selectedRows.filter((r) => r.canDistributeAirdropToday);
    ElMessageBox.confirm(
      `确认为选中的 ${eligible.length} 笔订单各发放 ${state.batchForm.amount} 吗？`,
      '批量发放空投',
      { type: 'warning' }
    ).then(() => {
      state.batchDialog.loading = true;
      batchDistributeAirdropForOrders({
        stakingOrderIds: eligible.map((r) => r.id),
        amount: state.batchForm.amount
      })
        .then((res: any) => {
          const data = res.data;
          if (data?.failCount > 0) {
            ElMessage.warning(res.message || `成功 ${data.successCount} 笔，失败 ${data.failCount} 笔`);
          } else {
            ElMessage.success(res.message || '批量发放成功');
          }
          state.batchDialog.visible = false;
          handleQuery();
        })
        .finally(() => {
          state.batchDialog.loading = false;
        });
    }).catch(() => {});
  });
}

onMounted(handleQuery);
</script>

<template>
  <div class="app-container">
    <el-form ref="queryFormRef" :model="queryParams" :inline="true">
      <el-form-item label="订单状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="全部" clearable style="width: 130px">
          <el-option label="质押中" :value="0" />
          <el-option label="解冻释放中" :value="1" />
          <el-option label="已完成" :value="2" />
        </el-select>
      </el-form-item>
      <el-form-item label="用户ID" prop="memberId">
        <el-input v-model="queryParams.memberId" placeholder="用户ID" clearable style="width: 130px" />
      </el-form-item>
      <el-form-item label="币种" prop="coinUnit">
        <el-input v-model="queryParams.coinUnit" placeholder="币种单位" clearable style="width: 120px" />
      </el-form-item>
      <el-form-item label="今日待发放">
        <el-checkbox v-model="queryParams.pendingAirdropToday">
          仅显示今日可发放未发放
        </el-checkbox>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" :icon="Search" @click="handleQuery">搜索</el-button>
        <el-button :icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
      <el-form-item>
        <el-button
          type="success"
          :disabled="selectableCount === 0"
          @click="handleBatchDistribute"
        >
          批量发放空投{{ selectableCount > 0 ? `(${selectableCount})` : '' }}
        </el-button>
      </el-form-item>
    </el-form>

    <el-table
      v-loading="loading"
      :data="list"
      border
      height="480"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="48" align="center" :selectable="rowSelectable" />
      <el-table-column label="订单ID" prop="id" width="90" align="center" />
      <el-table-column label="用户ID" prop="memberId" width="100" align="center" />
      <el-table-column label="配置ID" prop="configId" width="90" align="center" />
      <el-table-column label="币种" prop="coinUnit" width="100" align="center" />
      <el-table-column label="质押金额" prop="amount" min-width="120" align="center" />
      <el-table-column label="已释放" prop="releasedAmount" min-width="120" align="center" />
      <el-table-column label="状态" prop="status" width="100" align="center">
        <template #default="{ row }">
          <el-tag :type="(ORDER_STATUS[row.status]?.type as any)" size="small">
            {{ ORDER_STATUS[row.status]?.label ?? row.status }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="今日空投" width="110" align="center">
        <template #default="{ row }">
          <el-tag :type="airdropStatusType(row) as any" size="small">
            {{ airdropStatusLabel(row) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="质押时间" prop="stakingTime" min-width="155" align="center" />
      <el-table-column label="解冻时间" prop="unlockTime" min-width="155" align="center" />
      <el-table-column label="上次释放" prop="lastReleaseTime" min-width="155" align="center">
        <template #default="{ row }">
          <span v-if="row.lastReleaseTime">{{ row.lastReleaseTime }}</span>
          <span v-else style="color:#999">-</span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" prop="createTime" min-width="155" align="center" />
      <el-table-column label="操作" width="100" align="center" fixed="right">
        <template #default="{ row }">
          <el-link v-if="row.canDistributeAirdropToday" type="primary" @click="handleDistribute(row)">
            发放空投
          </el-link>
          <span v-else style="color:#999">-</span>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-if="total > 0"
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="handleQuery"
    />

    <el-dialog v-model="dialog.visible" title="发放空投" width="480px" destroy-on-close>
      <el-form
        v-if="currentOrder"
        ref="dataFormRef"
        :model="distributeForm"
        :rules="distributeRules"
        label-width="100px"
      >
        <el-form-item label="订单ID"><span>{{ currentOrder.id }}</span></el-form-item>
        <el-form-item label="用户ID"><span>{{ currentOrder.memberId }}</span></el-form-item>
        <el-form-item label="币种"><span>{{ currentOrder.coinUnit }}</span></el-form-item>
        <el-form-item label="发放金额" prop="amount">
          <el-input v-model="distributeForm.amount" placeholder="须大于 0" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialog.visible = false">取消</el-button>
        <el-button type="primary" :loading="dialog.loading" @click="submitDistribute">确定</el-button>
      </template>
    </el-dialog>

    <el-dialog v-model="batchDialog.visible" title="批量发放空投" width="480px" destroy-on-close>
      <p style="margin:0 0 16px;color:#666">
        已选择 <strong>{{ selectableCount }}</strong> 笔可发放订单，将按统一金额逐笔发放。
      </p>
      <el-form ref="batchFormRef" :model="batchForm" :rules="batchRules" label-width="100px">
        <el-form-item label="发放金额" prop="amount">
          <el-input v-model="batchForm.amount" placeholder="每笔订单发放相同金额" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="batchDialog.visible = false">取消</el-button>
        <el-button type="primary" :loading="batchDialog.loading" @click="submitBatchDistribute">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>
