<script setup lang="ts">
import { reactive, onMounted, ref, nextTick } from "vue";
import { getStationAccount, applyWithdrawn, getStationList } from "@/api/station";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import { ElMessage, ElMessageBox } from "element-plus";

defineOptions({
  name: "AdminStationAccount"
});

const queryRef = ref();
const tableRef = ref();

const state = reactive({
  formQuery: {
    stationId: ""
  },
  pageQuery: {
    pageNum: 1,
    pageSize: 10,
    total: 0
  },
  tableData: {
    height: 500,
    data: [] as Array<any>,
    loading: false,
    columns: [
      { label: "站点名称", prop: "stationName", width: 200 },
      { label: "可提现金额（元）", prop: "availableBalance", width: 180 },
      { label: "已提现金额（元）", prop: "withdrawnAmount", width: 180 },
      { label: "提现中金额（元）", prop: "withdrawnFrozenAmount", width: 180 },
      { label: "创建时间", prop: "createTime", width: 180 },
      { label: "更新时间", prop: "updateTime", width: 180 }
    ]
  },
  stationOptions: [] as Array<{ stationId: string; stationName: string }>
});

onMounted(() => {
  loadStationOptions();
  loadData();
  nextTick(() => {
    const bodyHeight = document.body.clientHeight;
    const queryHeight = queryRef.value?.$el?.clientHeight || 0;
    state.tableData.height = bodyHeight - queryHeight - 230;
  });
});

const loadStationOptions = () => {
  getStationList({ pageSize: 1000 }).then((res: any) => {
    const { list } = res || {};
    state.stationOptions = list || [];
  });
};

const loadData = (refresh: boolean = false) => {
  if (refresh) {
    state.pageQuery.pageNum = 1;
  }
  state.tableData.loading = true;
  getStationAccount({ ...state.formQuery, ...state.pageQuery })
    .then((res: any) => {
      const { list, count } = res || {};
      state.tableData.data = list || [];
      state.pageQuery.total = count || 0;
    })
    .catch(() => {
      state.tableData.data = [];
      ElMessage.error("加载账户列表失败");
    })
    .finally(() => {
      state.tableData.loading = false;
    });
};

const withdrawLoading = ref(false);

const handleWithdrawApply = (row: any) => {
  ElMessageBox.prompt(
    `站点「${row.stationName}」可提现 ${formatMoney(row.availableBalance)} 元`,
    "提现申请",
    {
      confirmButtonText: "确认提现",
      cancelButtonText: "取消",
      inputPattern: /^[0-9]+(\.[0-9]{1,2})?$/,
      inputErrorMessage: "请输入有效的金额",
      inputPlaceholder: "请输入提现金额（元）"
    }
  ).then(({ value }) => {
    const amount = Number(value) * 100;
    withdrawLoading.value = true;
    applyWithdrawn({ stationId: row.stationId, amount })
      .then(() => {
        ElMessage.success("提现已发起");
        loadData(true);
      })
      .catch(() => {
        ElMessage.error("提现申请失败，请稍后重试");
      })
      .finally(() => {
        withdrawLoading.value = false;
      });
  });
};

const handleSizeChange = (size: number) => {
  state.pageQuery.pageSize = size;
  loadData(true);
};

const handleCurrentChange = (page: number) => {
  state.pageQuery.pageNum = page;
  loadData();
};

const handleSearch = () => {
  loadData(true);
};

const handleReset = () => {
  state.formQuery = {
    stationId: ""
  };
  loadData(true);
};

const formatMoney = (value: number) => {
  if (value === null || value === undefined) return "¥0.00";
  return `¥${(value / 100).toFixed(2)}`;
};
</script>

<template>
  <div class="page-container">
    <el-card shadow="hover">
      <template #header>
        <span class="card-header">站点账户</span>
      </template>
      <el-form
        ref="queryRef"
        :model="state.formQuery"
        inline
        class="search-form"
      >
        <el-form-item label="站点">
          <el-select
            v-model="state.formQuery.stationId"
            placeholder="请选择站点"
            clearable
            filterable
            @change="handleSearch"
          >
            <el-option
              v-for="item in state.stationOptions"
              :key="item.stationId"
              :label="item.stationName"
              :value="item.stationId"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            :icon="useRenderIcon('ri/search-line')"
            @click="handleSearch"
          >
            查询
          </el-button>
          <el-button
            :icon="useRenderIcon('ri/refresh-line')"
            @click="handleReset"
          >
            重置
          </el-button>
        </el-form-item>
      </el-form>

      <el-table
        ref="tableRef"
        v-loading="state.tableData.loading"
        :data="state.tableData.data"
        :height="state.tableData.height"
        border
        stripe
      >
        <template #empty>
          <el-empty description="暂无账户数据，请选择站点后查询" />
        </template>
        <el-table-column
          v-for="col in state.tableData.columns"
          :key="col.prop"
          :prop="col.prop"
          :label="col.label"
          :width="col.width"
          show-overflow-tooltip
        >
          <template #default="{ row }">
            <template
              v-if="['availableBalance', 'withdrawnAmount', 'withdrawnFrozenAmount'].includes(col.prop)"
            >
              {{ formatMoney(row[col.prop]) }}
            </template>
            <template v-else>
              {{ row[col.prop] }}
            </template>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link size="small" @click="handleWithdrawApply(row)">
              提现申请
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="state.pageQuery.pageNum"
          v-model:page-size="state.pageQuery.pageSize"
          :total="state.pageQuery.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<style scoped lang="scss">
.page-container {
  padding: 20px;
}

.search-form {
  margin-bottom: 16px;
}

.card-header {
  font-size: 16px;
  font-weight: 600;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}
</style>
