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

.wd120 {
  width: 120px;
}

.wd150 {
  width: 150px;
}
</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">
        <el-input
            v-model="state.formQuery.mobilePhone"
            placeholder="用户手机号"
            clearable
            @blur="loadData(true)"
            class="wd150 mr10">
        </el-input>
        <el-select
            v-model="state.formQuery.type"
            placeholder="交易类型"
            clearable
            class="wd120 mr10"
            @change="loadData(true)">
          <el-option label="全部" :value="undefined" />
          <el-option label="充值" :value="1" />
          <el-option label="退款" :value="2" />
          <el-option label="消费" :value="3" />
        </el-select>
        <el-select
            v-model="state.formQuery.status"
            placeholder="状态"
            clearable
            class="wd120 mr10"
            @change="loadData(true)">
          <el-option label="全部" :value="undefined" />
          <el-option label="待确认" :value="0" />
          <el-option label="已确认" :value="1" />
          <el-option label="已取消" :value="2" />
        </el-select>
        <el-date-picker
            v-model="state.formQuery.startDate"
            type="date"
            placeholder="开始日期"
            value-format="YYYY-MM-DD"
            class="wd150 mr10"
            @change="loadData(true)">
        </el-date-picker>
        <el-date-picker
            v-model="state.formQuery.endDate"
            type="date"
            placeholder="结束日期"
            value-format="YYYY-MM-DD"
            class="wd150 mr10"
            @change="loadData(true)">
        </el-date-picker>

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

      <el-table
          border
          stripe="stripe"
          :height="state.tableData.height"
          highlight-current-row
          current-row-key="id"
          row-key="id"
          :data="state.tableData.data"
          v-loading="state.tableData.loading"
          @selection-change="handleTableSelectionChange"
          @sort-change="handleTableSortChange">
        <template #empty>
          <el-empty description="暂无资金流水记录"></el-empty>
        </template>
        <el-table-column
            v-for="field in state.tableData.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==='type'">
              <el-tag :type="getTypeTag(row.type).type" size="small" effect="plain">
                {{ getTypeTag(row.type).text }}
              </el-tag>
            </template>
            <template v-else-if="field.prop==='status'">
              <el-tag :type="getStatusTag(row.status).type" size="small" effect="plain">
                {{ getStatusTag(row.status).text }}
              </el-tag>
            </template>
            <template v-else-if="['amount','grantsAmount','commission','beforeBalance','afterBalance','beforeGrantsBalance','afterGrantsBalance'].includes(field.prop)">
              {{ u.fmt.fmtMoney(row[field.prop]) }}
            </template>
            <template v-else-if="field.prop==='orderNo'">
              <el-button v-if="row.orderNo" link type="primary" @click="handleOrderNoClick(row)">
                {{ row.orderNo }}
              </el-button>
              <span v-else>-</span>
            </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>

    <!-- 详情弹窗 (按类型展示) -->
    <el-dialog
        v-model="orderDialog.visible"
        :title="orderDialog.title"
        width="680px"
        destroy-on-close
        :close-on-click-modal="false"
        align-center>
      <!-- 消费订单详情 -->
      <el-descriptions v-if="orderDialog.type === 3" v-loading="orderDialog.loading" :column="2" border size="default">
        <el-descriptions-item label="订单号" :span="2">{{ orderDialog.data.orderId }}</el-descriptions-item>
        <el-descriptions-item label="设备编号">{{ orderDialog.data.shortId }}</el-descriptions-item>
        <el-descriptions-item label="消费站点">{{ orderDialog.data.stationName }}</el-descriptions-item>
        <el-descriptions-item label="消费金额">{{ u.fmt.fmtMoney(orderDialog.data.amount) }}</el-descriptions-item>
        <el-descriptions-item label="实收金额">{{ u.fmt.fmtMoney(orderDialog.data.amountReceived) }}</el-descriptions-item>
        <el-descriptions-item label="优惠金额">{{ u.fmt.fmtMoney(orderDialog.data.discountAmount) }}</el-descriptions-item>
        <el-descriptions-item label="优惠方式">
          <ext-d-label v-if="orderDialog.data.discountType" type="Activity.discountType" :model-value="orderDialog.data.discountType" />
        </el-descriptions-item>
        <el-descriptions-item label="充值款支付">{{ u.fmt.fmtMoney(orderDialog.data.rechargePayment) }}</el-descriptions-item>
        <el-descriptions-item label="赠款支付">{{ u.fmt.fmtMoney(orderDialog.data.grantsPayment) }}</el-descriptions-item>
        <el-descriptions-item label="订单状态">
          <ext-d-label v-if="orderDialog.data.orderStatus != null" type="Order.status" :model-value="orderDialog.data.orderStatus" />
        </el-descriptions-item>
        <el-descriptions-item label="支付状态">
          <ext-d-label v-if="orderDialog.data.payStatus != null" type="Order.pay" :model-value="orderDialog.data.payStatus" />
        </el-descriptions-item>
        <el-descriptions-item label="开始时间">{{ orderDialog.data.startTime }}</el-descriptions-item>
        <el-descriptions-item label="结束时间">{{ orderDialog.data.endTime }}</el-descriptions-item>
        <el-descriptions-item label="关机方式" :span="2">
          <ext-d-label v-if="orderDialog.data.closeType" type="Order.closeType" :model-value="orderDialog.data.closeType" />
        </el-descriptions-item>
        <el-descriptions-item label="停止原因" :span="2">{{ orderDialog.data.stopReason }}</el-descriptions-item>
      </el-descriptions>
      <!-- 充值记录详情 -->
      <el-descriptions v-else-if="orderDialog.type === 1" v-loading="orderDialog.loading" :column="2" border size="default">
        <el-descriptions-item label="商户订单号" :span="2">{{ orderDialog.data.outTradeNo }}</el-descriptions-item>
        <el-descriptions-item label="微信交易号" :span="2">{{ orderDialog.data.transactionId }}</el-descriptions-item>
        <el-descriptions-item label="支付金额">{{ u.fmt.fmtMoney(orderDialog.data.total) }}</el-descriptions-item>
        <el-descriptions-item label="用户实付">{{ u.fmt.fmtMoney(orderDialog.data.payerTotal) }}</el-descriptions-item>
        <el-descriptions-item label="交易类型">{{ orderDialog.data.tradeType }}</el-descriptions-item>
        <el-descriptions-item label="交易状态">{{ orderDialog.data.tradeState }}</el-descriptions-item>
        <el-descriptions-item label="银行类型">{{ orderDialog.data.bankType }}</el-descriptions-item>
        <el-descriptions-item label="支付完成时间">{{ orderDialog.data.successTime }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ orderDialog.data.createTime }}</el-descriptions-item>
      </el-descriptions>
      <!-- 退款详情 -->
      <el-descriptions v-else-if="orderDialog.type === 2" v-loading="orderDialog.loading" :column="2" border size="default">
        <el-descriptions-item label="商户退款单号" :span="2">{{ orderDialog.data.outRefundNo }}</el-descriptions-item>
        <el-descriptions-item label="商户支付单号" :span="2">{{ orderDialog.data.outTradeNo }}</el-descriptions-item>
        <el-descriptions-item label="微信退款单号" :span="2">{{ orderDialog.data.refundId }}</el-descriptions-item>
        <el-descriptions-item label="原充值金额">{{ u.fmt.fmtMoney(orderDialog.data.total) }}</el-descriptions-item>
        <el-descriptions-item label="退款金额">{{ u.fmt.fmtMoney(orderDialog.data.refund) }}</el-descriptions-item>
        <el-descriptions-item label="不可退优惠">{{ u.fmt.fmtMoney(orderDialog.data.discountAmount) }}</el-descriptions-item>
        <el-descriptions-item label="退款渠道">{{ orderDialog.data.channel }}</el-descriptions-item>
        <el-descriptions-item label="退款状态">
          <ext-d-label v-if="orderDialog.data.status" type="RefundLog.status" :model-value="orderDialog.data.status" />
        </el-descriptions-item>
        <el-descriptions-item label="退款入账账户">{{ orderDialog.data.userReceivedAccount }}</el-descriptions-item>
        <el-descriptions-item label="退款原因" :span="2">{{ orderDialog.data.reason }}</el-descriptions-item>
        <el-descriptions-item label="退款人">{{ orderDialog.data.adminUsername }}</el-descriptions-item>
        <el-descriptions-item label="退款申请时间">{{ orderDialog.data.createTime }}</el-descriptions-item>
        <el-descriptions-item label="退款成功时间">{{ orderDialog.data.successTime }}</el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <el-button @click="orderDialog.visible = false">关 闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

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

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

const typeTagMap: Record<number, { text: string; type: string }> = {
  1: { text: "充值", type: "success" },
  2: { text: "退款", type: "warning" },
  3: { text: "消费", type: "danger" }
};

const statusTagMap: Record<number, { text: string; type: string }> = {
  0: { text: "待确认", type: "info" },
  1: { text: "已确认", type: "success" },
  2: { text: "已取消", type: "danger" }
};

const getTypeTag = (type: number) => {
  return typeTagMap[type] || { text: "未知", type: "info" };
};

const getStatusTag = (status: number) => {
  return statusTagMap[status] || { text: "未知", type: "info" };
};

//定义引用
const queryRef = ref();

//定义变量
const state = reactive({
  formQuery: {
    mobilePhone: "",
    type: undefined as number | undefined,
    status: undefined as number | undefined,
    startDate: "",
    endDate: ""
  },
  pageQuery: {
    pageNum: 1,
    pageSize: 10,
    total: 0
  },
  tableData: {
    height: 500,
    data: [] as Array<any>,
    loading: false,
    columns: [
      {label: '用户ID', prop: 'userId', width: 120, resizable: true, fixed: 'left'},
      {label: '用户手机号', prop: 'mobilePhone', width: 140, resizable: true, fixed: 'left'},
      {label: '交易类型', prop: 'type', width: 100, resizable: true},
      {label: '订单号', prop: 'orderNo', width: 240, resizable: true},
      {label: '金额', prop: 'amount', width: 110, resizable: true},
      {label: '赠款金额', prop: 'grantsAmount', width: 110, resizable: true},
      {label: '手续费', prop: 'commission', width: 100, resizable: true},
      {label: '交易前余额', prop: 'beforeBalance', width: 120, resizable: true},
      {label: '交易后余额', prop: 'afterBalance', width: 120, resizable: true},
      {label: '交易前赠款', prop: 'beforeGrantsBalance', width: 120, resizable: true},
      {label: '交易后赠款', prop: 'afterGrantsBalance', width: 120, resizable: true},
      {label: '交易时间', prop: 'transactionTime', width: 170, resizable: true, fixed: 'right'},
      {label: '状态', prop: 'status', width: 100, resizable: true},
      {label: '备注', prop: 'remark', width: 100, resizable: true},
    ],
  },
})

onMounted(() => {
  loadData();

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

const buildParams = () => {
  const params: any = { ...state.formQuery, ...state.pageQuery };
  if (params.type === undefined || params.type === null) delete params.type;
  if (params.status === undefined || params.status === null) delete params.status;
  if (!params.startDate) delete params.startDate;
  if (!params.endDate) delete params.endDate;
  return params;
};

const typeTitles: Record<number, string> = { 1: '充值详情', 2: '退款详情', 3: '订单详情' };

const orderDialog = reactive({
  visible: false,
  loading: false,
  type: 0,
  title: '',
  data: {} as any,
});

const handleOrderNoClick = (row: any) => {
  const type = row.type as number;
  orderDialog.type = type;
  orderDialog.title = typeTitles[type] || '交易详情';
  orderDialog.visible = true;
  orderDialog.loading = true;
  orderDialog.data = {};

  let url = '';
  if (type === 1) {
    // 充值：orderNo 对应 pay_log 的 outTradeNo
    url = `/custom/payLog/byOutTradeNo/${row.orderNo}`;
  } else if (type === 2) {
    // 退款：orderNo 对应 refund_log 的 outRefundNo
    url = `/finance/refundLog/detail/${row.orderNo}`;
  } else {
    // 消费：orderNo 是 wash_order 的 orderId
    url = `/washOrder/detail/${row.orderNo}`;
  }

  $get(url).then((res: any) => {
    orderDialog.data = res;
  }).catch(() => {
    orderDialog.data = {};
  }).finally(() => {
    orderDialog.loading = false;
  });
};

// 初始化表格数据
const loadData = (refresh: boolean = false) => {
  if (refresh) {
    state.pageQuery.pageNum = 1;
  }
  state.tableData.loading = true;
  $get(`/finance/walletDetails`, buildParams()).then((res: any) => {
    let {list, total} = res;
    state.tableData.data = list;
    state.pageQuery.total = total;
    state.tableData.loading = false;
  }).catch(e => {
    state.tableData.loading = false;
  })
};

const handleTableSelectionChange = (selection: any) => {
}

const handleTableSortChange = (column: any, prop: string, order: string) => {
}
</script>
