<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;
}

.station-name-cell {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 4px;

  .station-name {
    font-weight: 500;
  }

  .station-divider {
    display: block;
    width: 40px;
    height: 1px;
    background: var(--el-border-color-light);
  }

  .station-id {
    color: var(--el-text-color-secondary);
    font-size: 12px;
  }
}

.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==='stationId'">
              <div class="station-name-cell">
                <span class="station-id">{{ row.stationId }}</span>
                <span class="station-divider"></span>
                <span class="station-name">{{ row.stationName }}</span>
              </div>
            </template>
            <template v-else-if="field.prop==='action'">
              <el-button v-if="row.status===0" type="primary" size="small" @click="handleConfirmSettlement(row)">确认结算</el-button>
              <span v-else style="color: #909399; font-size: 12px;">-</span>
            </template>
            <template v-else-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','withdrawalFee','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: 'stationId', 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: 'withdrawalFee', 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},
    {label: '操作', width: 100, prop: 'action', fixed: 'right', 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 handleConfirmSettlement = (row: any) => {
  Msg.confirm(`确认将站点「${row.stationName}」${row.settlementPeriod} 的结算金额 ¥${(row.settlementAmount / 100).toFixed(2)} 转入可提现余额？`, '确认结算').then(() => {
    Msg.showLoading(`确认中...`);
    $body(`finance/confirmSettlement`, { id: row.id }).then(() => {
      Msg.message("结算已确认，金额已转入站点可提现余额");
      Msg.hideLoading();
      loadData(true);
    }).catch(() => {
      Msg.hideLoading();
    })
  }).catch(() => {});
};

const getStatusLabel = (status: number) => u.fmt.fmtDict(status, 'Settlement.status');
const getStatusType = (status: number): any => u.fmt.fmtDictColor(status, 'Settlement.status');
</script>
