<script setup lang="ts">
import { reactive, onMounted, ref, nextTick } from "vue";
import { getSplitRecordList } from "@/api/finance";
import { getStationList } from "@/api/station";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import { ExtDLabel, ExtDSelect } from "@/components/ExtForm";

defineOptions({
  name: "AdminFinanceSplitRecord"
});

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

const state = reactive({
  formQuery: {
    stationId: "",
    tradeNo: "",
    type: ""
  },
  pageQuery: {
    pageNum: 1,
    pageSize: 10,
    total: 0
  },
  stationOptions: [] as Array<{ stationId: string; stationName: string }>,
  tableData: {
    height: 500,
    data: [] as Array<any>,
    loading: false,
    columns: [
      { label: "入账站点ID/名称", prop: "toStationId", width: 200 },
      { label: "出账站点ID/名称", prop: "fromStationId", width: 200 },
      { label: "分账交易金额（元）", prop: "amount", width: 180 },
      { label: "分账交易流水号", prop: "tradeNo", width: 280 },
      { label: "交易类型", prop: "type", width: 130 },
      { label: "创建时间", prop: "createTime", width: 180 },
      { label: "更新时间", prop: "updateTime", width: 180 }
    ]
  }
});

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

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;
  getSplitRecordList({ ...state.formQuery, ...state.pageQuery })
    .then((res: any) => {
      const { list, total } = res || {};
      state.tableData.data = list || [];
      state.pageQuery.total = total || 0;
    })
    .catch(() => {
      state.tableData.data = [];
    })
    .finally(() => {
      state.tableData.loading = 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: "",
    tradeNo: "",
    type: ""
  };
  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">
      <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 label="交易流水号">
          <el-input
            v-model="state.formQuery.tradeNo"
            placeholder="请输入交易流水号"
            clearable
            @keyup.enter="handleSearch"
          />
        </el-form-item>
        <el-form-item label="分账类型">
          <ExtDSelect
            v-model="state.formQuery.type"
            type="SplitRecord.type"
            placeholder="请选择分账类型"
            @on-change="handleSearch"
          />
        </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="col.prop === 'toStationId'">
              <div class="station-name-cell">
                <div class="station-id">{{ row.toStationId }}</div>
                <el-divider direction="horizontal" />
                <div class="station-name">{{ row.toStationName }}</div>
              </div>
            </template>
            <template v-else-if="col.prop === 'fromStationId'">
              <div class="station-name-cell">
                <div class="station-id">{{ row.fromStationId }}</div>
                <el-divider direction="horizontal" />
                <div class="station-name">{{ row.fromStationName }}</div>
              </div>
            </template>
            <template v-else-if="col.prop === 'amount'">
              <span class="money">¥{{ formatMoney(row.amount) }}</span>
            </template>
            <template v-else-if="col.prop === 'type'">
              <ExtDLabel type="SplitRecord.type" :model-value="row.type" />
            </template>
            <template v-else>
              {{ row[col.prop] }}
            </template>
          </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: 15px;
}

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

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 15px;
}

.station-name-cell {
  text-align: center;
  
  .station-id {
    color: #909399;
    font-size: 12px;
  }
  
  .station-name {
    font-weight: 500;
  }
  
  .el-divider {
    margin: 4px 0;
  }
}

.money {
  font-family: "Helvetica Neue", Helvetica, "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", Arial, sans-serif;
  color: #f56c6c;
  font-weight: 500;
}
</style>
