<template>
  <div class="app-container">
    <!-- 账户概览 -->
    <el-card shadow="never" class="overview-card" v-loading="summaryLoading">
      <div slot="header" class="card-header">
        <span class="card-title">账户概览</span>
      </div>
      <el-row :gutter="24" class="stats-row">
        <el-col :xs="24" :sm="8">
          <div class="stat-block stat-block-primary">
            <div class="stat-value">{{ formatMoney(summary.availableBalance) }}</div>
            <div class="stat-label">可用店铺余额</div>
            <div class="stat-tip">订单结算完成、可发起提现的金额</div>
          </div>
        </el-col>
        <el-col :xs="24" :sm="8">
          <div class="stat-block">
            <div class="stat-value">{{ formatMoney(summary.pendingSettleAmount) }}</div>
            <div class="stat-label">待结算金额</div>
            <div class="stat-tip">已支付未完成订单实付合计，确认收货后转入余额</div>
          </div>
        </el-col>
        <el-col :xs="24" :sm="8">
          <div class="stat-block">
            <div class="stat-value">{{ formatMoney(summary.frozenAmount) }}</div>
            <div class="stat-label">冻结金额</div>
            <div class="stat-tip">提现审核中临时冻结的金额</div>
          </div>
        </el-col>
      </el-row>
      <el-descriptions :column="2" border size="medium" class="account-info">
        <el-descriptions-item label="用户名">{{ displayText(summary.username) }}</el-descriptions-item>
        <el-descriptions-item label="银行卡数量">
          {{ summary.bankAccountCount != null ? summary.bankAccountCount : '—' }}
        </el-descriptions-item>
      </el-descriptions>
    </el-card>

    <br/>

    <!-- 收支概况 -->
    <el-card shadow="never" class="table-card">
      <div slot="header" class="card-header">
        <span class="card-title">收支概况</span>
      </div>

      <el-table border v-loading="loading" :data="logList" :empty-text="emptyTableText">
        <el-table-column label="店铺名称" align="center" prop="shopName" min-width="120" :show-overflow-tooltip="true">
          <template slot-scope="scope">
            <span>{{ scope.row.shopName || '—' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="变动时间" align="center" width="160">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.changeTime) || '—' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="业务编号" align="center" prop="bizNo" min-width="160" :show-overflow-tooltip="true">
          <template slot-scope="scope">
            <span>{{ scope.row.bizNo || '—' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="变动余额资金" align="center" min-width="180">
          <template slot-scope="scope">
            <span :class="changeClass(scope.row.balanceChange)">
              {{ formatFundChange(scope.row.balanceChange, scope.row.balanceAfter, '余额') }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="变动冻结资金" align="center" min-width="180">
          <template slot-scope="scope">
            <span :class="changeClass(scope.row.frozenChange)">
              {{ formatFundChange(scope.row.frozenChange, scope.row.frozenAfter, '冻结') }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="变动原因" align="center" width="110">
          <template slot-scope="scope">
            <span>{{ scope.row.changeReasonText || changeReasonLabel(scope.row.changeReason) }}</span>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />
    </el-card>
  </div>
</template>

<script>
import {
  getSellerFundOverviewSummary,
  listSellerFundOverviewLogs
} from "@/api/agri/seller/finance/overview"
import { getSellerContext } from "@/api/agri/seller/context"
import { setSellerShopContext } from "@/utils/sellerShop"

const CHANGE_REASON_MAP = {
  "1": "订单收支",
  "2": "余额提现",
  "3": "提现驳回",
  "4": "提现完成"
}

export default {
  name: "AgriSellerFinanceOverview",
  data() {
    return {
      summaryLoading: false,
      loading: false,
      total: 0,
      summary: {},
      logList: [],
      queryParams: {
        pageNum: 1,
        pageSize: 10
      }
    }
  },
  computed: {
    emptyTableText() {
      return "暂无收支记录"
    }
  },
  created() {
    this.initPage()
  },
  methods: {
    /** 初始化：加载店铺上下文后拉概览与流水 */
    initPage() {
      this.loadShopContext().then(() => {
        this.loadSummary()
        this.getList()
      }).catch(() => {
        this.loadSummary()
        this.getList()
      })
    },
    /** 加载商家端当前店铺上下文 */
    loadShopContext() {
      return getSellerContext().then(response => {
        const data = response.data || {}
        if (data.shopId != null) {
          setSellerShopContext(data.shopId, data.shopName)
        }
      })
    },
    /** 查询账户概览 */
    loadSummary() {
      this.summaryLoading = true
      getSellerFundOverviewSummary().then(response => {
        this.summary = response.data || {}
        this.summaryLoading = false
      }).catch(() => {
        this.summaryLoading = false
      })
    },
    /** 查询收支流水列表 */
    getList() {
      this.loading = true
      listSellerFundOverviewLogs(this.queryParams).then(response => {
        this.logList = response.rows || []
        this.total = response.total || 0
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    /** 空值展示占位 */
    displayText(value) {
      if (value === null || value === undefined || String(value).trim() === "") {
        return "—"
      }
      return value
    },
    /** 金额格式化：¥ + 两位小数 + 千分位 */
    formatMoney(val) {
      if (val == null || val === "") {
        return "—"
      }
      const num = Number(val)
      if (isNaN(num)) {
        return "—"
      }
      const fixed = num.toFixed(2)
      const parts = fixed.split(".")
      parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",")
      return "¥" + parts.join(".")
    },
    /** 变动后金额（不带货币符号，带千分位） */
    formatAfterAmount(val) {
      if (val == null || val === "") {
        return "—"
      }
      const num = Number(val)
      if (isNaN(num)) {
        return "—"
      }
      const fixed = num.toFixed(2)
      const parts = fixed.split(".")
      parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",")
      return parts.join(".")
    },
    /** 变动值（带 +/- 符号） */
    formatChangeValue(change) {
      if (change == null || change === "") {
        return "0"
      }
      const num = Number(change)
      if (isNaN(num) || num === 0) {
        return "0"
      }
      const sign = num > 0 ? "+" : ""
      return sign + num.toFixed(2)
    },
    /** 变动列展示：变更值 + 变更后 */
    formatFundChange(change, after, label) {
      const changeStr = this.formatChangeValue(change)
      const afterStr = this.formatAfterAmount(after)
      return `${changeStr}（${label}：${afterStr}）`
    },
    /** 正负变动样式 */
    changeClass(change) {
      if (change == null || change === "" || Number(change) === 0) {
        return ""
      }
      return Number(change) > 0 ? "change-in" : "change-out"
    },
    /** 变动原因文案兜底 */
    changeReasonLabel(reason) {
      return CHANGE_REASON_MAP[reason] || "—"
    }
  }
}
</script>

<style scoped lang="scss">
.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.card-title {
  font-weight: 600;
  font-size: 15px;
}
.stats-row {
  margin-bottom: 16px;
}
.stat-block {
  padding: 16px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  min-height: 120px;
  background: #fafafa;
  margin-bottom: 12px;
}
.stat-block-primary {
  background: #f0f9eb;
  border-color: #e1f3d8;
}
.stat-value {
  font-size: 28px;
  font-weight: 600;
  color: #303133;
  line-height: 1.2;
  margin-bottom: 8px;
}
.stat-label {
  font-size: 14px;
  color: #606266;
  margin-bottom: 4px;
}
.stat-tip {
  font-size: 12px;
  color: #909399;
  line-height: 1.5;
}
.account-info {
  margin-top: 4px;
}
.change-in {
  color: #67c23a;
}
.change-out {
  color: #f56c6c;
}
</style>
