<style scoped lang="scss">
.system-container {

  :deep(.el-card__body) {
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    flex: 1;
    overflow: auto;

    .el-table {
      flex: 1;
    }

  }
}

.page-content {
  margin-bottom: 20px;
}

.page-pager {
  background-color: var(--el-color-white);
  height: 24px;
}
</style>
<template>
  <div class="system-container layout-padding">
    <el-card shadow="hover" class="layout-padding-auto">
      <el-form
          :model="state.formQuery"
          ref="queryRef"
          size="default" label-width="0px" class="mt5 mb5">
        <ext-select
            v-model="state.formQuery.stationId"
            placeholder="站点"
            url="washStation/list"
            url-method="post"
            label-key="stationName"
            value-key="stationId"
            data-key="list"
            clearable
            class="wd200 ml10"/>

        <el-input
            v-model="state.formQuery.settlementPeriod"
            placeholder="结算周期 如 2026-05"
            clearable
            class="wd200 ml10"/>

        <el-select
            v-model="state.formQuery.status"
            placeholder="状态"
            clearable
            class="wd150 ml10">
          <el-option label="全部" value=""/>
          <el-option label="待结算" value="0"/>
          <el-option label="已结算" value="1"/>
          <el-option label="异常结算" value="2"/>
        </el-select>

        <el-button class="ml10" plain size="default" type="success" @click="loadData(true)">
          <SvgIcon name="ele-Search"/>
          查询
        </el-button>

        <el-button class="ml10" plain size="default" type="warning" @click="handleTriggerSettlement">
          <SvgIcon name="ele-Money"/>
          手动触发结算
        </el-button>
      </el-form>

      <el-table
          border
          stripe="stripe"
          :height="state.tableData.height"
          :data="state.tableData.data"
          v-loading="state.tableData.loading">
        <template #empty>
          <el-empty></el-empty>
        </template>
        <el-table-column
            v-for="field in state.columns"
            :key="field.prop"
            :label="field.label"
            :column-key="field.prop"
            :width="field.width"
            :min-width="field.minWidth"
            :fixed="field.fixed"
            :sortable="field.sortable"
            :show-overflow-tooltip="!field.fixed&&field.width>150">

          <template #default="{row}">
            <template v-if="field.prop==='status'">
              <el-tag :type="getStatusType(row.status)" size="small">
                {{ getStatusLabel(row.status) }}
              </el-tag>
            </template>
            <template v-else-if="['openingPendingBalance','totalRecharge','totalRefund','totalCrossIncome','totalCrossExpend','platformFeeBase','platformFee','settlementAmount','closingPendingBalance'].includes(field.prop)">
              {{ u.fmt.fmtMoney(row[field.prop]) }}
            </template>
            <template v-else-if="['createTime','updateTime'].includes(field.prop)">
              {{ u.fmt.fmtDateTime(row[field.prop]) }}
            </template>
            <template v-else>
              <div>{{ row[field.prop] }}</div>
            </template>
          </template>
        </el-table-column>
      </el-table>

      <ext-page class="page-pager" v-model:value="state.pageQuery" @change="loadData(false)"/>
    </el-card>
  </div>
</template>

<script setup lang="ts" name="adminFinanceSettlement">
import {reactive, onMounted, ref, nextTick} from 'vue';
import {$body} from "/@/utils/request";
import u from '/@/utils/u'
import {Msg} from "/@/utils/message";

import ExtPage from '/@/components/form/ExtPage.vue'
import ExtSelect from "/@/components/form/ExtSelect.vue";

const queryRef = ref();

const state = reactive({
  formQuery: {
    stationId: '',
    settlementPeriod: '',
    status: ''
  },
  pageQuery: {
    pageNum: 1,
    pageSize: 10,
    total: 0
  },
  tableData: {
    height: 500,
    data: [] as Array<any>,
    loading: false
  },
  columns: [
    {label: '站点名称', width: 180, prop: 'stationName', resizable: true},
    {label: '结算周期', width: 120, prop: 'settlementPeriod', resizable: true},
    {label: '期初余额（元）', width: 150, prop: 'openingPendingBalance', resizable: true},
    {label: '总充值（元）', width: 140, prop: 'totalRecharge', resizable: true},
    {label: '总退款（元）', width: 140, prop: 'totalRefund', resizable: true},
    {label: '跨店收入（元）', width: 140, prop: 'totalCrossIncome', resizable: true},
    {label: '跨店支出（元）', width: 140, prop: 'totalCrossExpend', resizable: true},
    {label: '平台费基数（元）', width: 150, prop: 'platformFeeBase', resizable: true},
    {label: '平台费（元）', width: 130, prop: 'platformFee', resizable: true},
    {label: '结算金额（元）', width: 150, prop: 'settlementAmount', resizable: true},
    {label: '期末余额（元）', width: 150, prop: 'closingPendingBalance', resizable: true},
    {label: '状态', width: 100, prop: 'status', resizable: true},
    {label: '备注', width: 180, prop: 'remark', resizable: true},
    {label: '创建时间', width: 180, prop: 'createTime', resizable: true},
  ],
})

onMounted(() => {
  loadData();

  nextTick(() => {
    let bodyHeight = document.body.clientHeight;
    let queryHeight = queryRef.value.$el.clientHeight;
    state.tableData.height = bodyHeight - queryHeight - 320
  })
});

const loadData = (refresh: boolean = false) => {
  if (refresh) {
    state.pageQuery.pageNum = 1;
  }
  state.tableData.loading = true;
  $body(`/finance/settlementRecords`, {...state.formQuery, ...state.pageQuery}).then((res: any) => {
    let {list, total} = res;
    state.tableData.data = list || [];
    state.pageQuery.total = total || 0;
    state.tableData.loading = false;
  }).catch(e => {
    console.error(e)
    state.tableData.loading = false;
  })
};

const handleTriggerSettlement = () => {
  Msg.confirm(`确认手动触发本月结算吗？`, '手动结算').then(() => {
    Msg.showLoading(`结算执行中...`);
    $body(`finance/triggerSettlement`, {}).then(() => {
      Msg.message("结算已完成");
      Msg.hideLoading();
      loadData(true);
    }).catch(e => {
      Msg.hideLoading();
    })
  })
};

const getStatusLabel = (status: number) => {
  const map: Record<number, string> = {
    0: '待结算',
    1: '已结算',
    2: '异常结算'
  };
  return map[status] || String(status);
};

const getStatusType = (status: number): any => {
  const map: Record<number, string> = {
    0: 'info',
    1: 'success',
    2: 'danger'
  };
  return map[status] || 'info';
};
</script>
