<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.totalBalance) }}</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.pendingSettleTotal) }}</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.frozenTotal) }}</div>
            <div class="stat-label">冻结总额</div>
            <div class="stat-tip">提现审核中临时冻结金额合计</div>
          </div>
        </el-col>
      </el-row>
    </el-card>

    <br/>

    <!-- 店铺余额排行 -->
    <el-card shadow="never" class="table-card">
      <div slot="header" class="card-header">
        <span class="card-title">店铺余额排行</span>
      </div>

      <el-row :gutter="10" class="mb8">
        <right-toolbar :showSearch="false" @queryTable="refreshRank"></right-toolbar>
      </el-row>

      <el-table
        ref="rankTable"
        border
        v-loading="rankLoading"
        :data="shopList"
        :empty-text="rankEmptyText"
        :default-sort="defaultSort"
        @sort-change="handleSortChange"
      >
        <el-table-column label="店铺名称" align="left" min-width="160" :show-overflow-tooltip="true">
          <template slot-scope="scope">
            <div class="shop-cell">
              <image-preview v-if="scope.row.shopAvatar" :src="scope.row.shopAvatar" :width="44" :height="44" />
              <span class="shop-name">{{ scope.row.shopName || '—' }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="店铺状态" align="center" width="100">
          <template slot-scope="scope">
            <el-tag size="small" :type="shopStatusTag(scope.row)">
              {{ shopStatusText(scope.row) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="店铺余额" align="center" prop="availableBalance" width="130" sortable="custom">
          <template slot-scope="scope">
            <span>{{ formatMoney(scope.row.availableBalance) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="待结算金额" align="center" prop="pendingSettleAmount" width="130" sortable="custom">
          <template slot-scope="scope">
            <span>{{ formatMoney(scope.row.pendingSettleAmount) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="冻结金额" align="center" prop="frozenAmount" width="120" sortable="custom">
          <template slot-scope="scope">
            <span>{{ formatMoney(scope.row.frozenAmount) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="开店时间" align="center" width="160">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.openTime) || '—' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="120" fixed="right">
          <template slot-scope="scope">
            <el-button size="mini" type="text" @click="openLogs(scope.row)" v-hasPermi="['agri:finance:fundOverview:log']">查看资金日志</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="rankTotal > 0" :total="rankTotal" :page.sync="rankQuery.pageNum" :limit.sync="rankQuery.pageSize" @pagination="getShopList" />
    </el-card>

    <!-- 资金日志抽屉 -->
    <el-drawer
      :title="logsDrawerTitle"
      :visible.sync="logsOpen"
      size="72%"
      append-to-body
      @close="resetLogs"
    >
      <div class="logs-panel">
        <el-form :model="logQuery" ref="logQueryForm" size="small" :inline="true" label-width="80px" class="logs-search">
          <el-form-item label="店铺名称" prop="shopName">
            <el-input
              v-model="logQuery.shopName"
              placeholder="模糊检索"
              clearable
              style="width: 180px"
              @keyup.enter.native="handleLogQuery"
            />
          </el-form-item>
          <el-form-item label="变动时间">
            <el-date-picker
              v-model="logDateRange"
              type="daterange"
              value-format="yyyy-MM-dd"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              style="width: 240px"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleLogQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetLogQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-table border v-loading="logsLoading" :data="logList" :empty-text="logsEmptyText">
          <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="logTotal > 0" :total="logTotal" :page.sync="logQuery.pageNum" :limit.sync="logQuery.pageSize" @pagination="getLogList" />
      </div>
    </el-drawer>
  </div>
</template>

<script>
import {
  getPlatformFundOverviewSummary,
  listPlatformFundOverviewShops,
  listPlatformFundOverviewLogs
} from "@/api/agri/finance/fundOverview"

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

export default {
  name: "AgriFinanceFundOverview",
  data() {
    return {
      summaryLoading: false,
      rankLoading: false,
      logsLoading: false,
      summary: {},
      shopList: [],
      logList: [],
      rankTotal: 0,
      logTotal: 0,
      rankQuery: {
        pageNum: 1,
        pageSize: 10,
        orderByColumn: "availableBalance",
        isAsc: "desc"
      },
      defaultSort: {
        prop: "availableBalance",
        order: "descending"
      },
      logsOpen: false,
      currentShop: null,
      logQuery: {
        pageNum: 1,
        pageSize: 10,
        shopId: undefined,
        shopName: undefined,
        beginChangeTime: undefined,
        endChangeTime: undefined
      },
      logDateRange: [],
      defaultLogShopId: undefined
    }
  },
  computed: {
    rankEmptyText() {
      return "暂无店铺资金数据"
    },
    logsDrawerTitle() {
      if (this.currentShop && this.currentShop.shopName) {
        return `资金日志 · ${this.currentShop.shopName}`
      }
      return "资金日志"
    },
    logsEmptyText() {
      const hasFilter = !!(this.logQuery.shopName || (this.logDateRange && this.logDateRange.length))
      return hasFilter ? "未找到符合条件的资金变动记录" : "暂无资金变动记录"
    }
  },
  created() {
    this.loadSummary()
    this.getShopList()
  },
  methods: {
    /** 刷新总览与排行 */
    refreshRank() {
      this.loadSummary()
      this.getShopList()
    },
    /** 查询全平台总览 */
    loadSummary() {
      this.summaryLoading = true
      getPlatformFundOverviewSummary().then(response => {
        this.summary = response.data || {}
        this.summaryLoading = false
      }).catch(() => {
        this.summaryLoading = false
      })
    },
    /** 查询店铺排行 */
    getShopList() {
      this.rankLoading = true
      listPlatformFundOverviewShops(this.rankQuery).then(response => {
        this.shopList = response.rows || []
        this.rankTotal = response.total || 0
        this.rankLoading = false
      }).catch(() => {
        this.rankLoading = false
      })
    },
    /** 排行列排序 */
    handleSortChange(column) {
      if (!column.prop || !column.order) {
        this.rankQuery.orderByColumn = "availableBalance"
        this.rankQuery.isAsc = "desc"
      } else {
        this.rankQuery.orderByColumn = column.prop
        this.rankQuery.isAsc = column.order === "ascending" ? "asc" : "desc"
      }
      this.rankQuery.pageNum = 1
      this.getShopList()
    },
    /** 打开资金日志抽屉 */
    openLogs(row) {
      this.currentShop = row
      this.defaultLogShopId = row.shopId
      this.logQuery = {
        pageNum: 1,
        pageSize: 10,
        shopId: row.shopId,
        shopName: undefined,
        beginChangeTime: undefined,
        endChangeTime: undefined
      }
      this.logDateRange = []
      this.logsOpen = true
      this.getLogList()
    },
    /** 构建日志查询参数 */
    buildLogQueryParams() {
      const params = { ...this.logQuery }
      if (this.logDateRange && this.logDateRange.length === 2) {
        params.beginChangeTime = this.logDateRange[0]
        params.endChangeTime = this.logDateRange[1]
      } else {
        params.beginChangeTime = undefined
        params.endChangeTime = undefined
      }
      if (params.shopName && String(params.shopName).trim()) {
        params.shopId = undefined
      } else if (this.defaultLogShopId != null && !params.shopName) {
        params.shopId = this.defaultLogShopId
      }
      return params
    },
    /** 查询资金日志 */
    getLogList() {
      this.logsLoading = true
      listPlatformFundOverviewLogs(this.buildLogQueryParams()).then(response => {
        this.logList = response.rows || []
        this.logTotal = response.total || 0
        this.logsLoading = false
      }).catch(() => {
        this.logsLoading = false
      })
    },
    handleLogQuery() {
      this.logQuery.pageNum = 1
      this.getLogList()
    },
    /** 重置日志检索：恢复默认店铺范围 */
    resetLogQuery() {
      this.logDateRange = []
      this.logQuery.shopName = undefined
      this.logQuery.shopId = this.defaultLogShopId
      this.logQuery.pageNum = 1
      this.logQuery.beginChangeTime = undefined
      this.logQuery.endChangeTime = undefined
      if (this.$refs.logQueryForm) {
        this.resetForm("logQueryForm")
      }
      this.getLogList()
    },
    resetLogs() {
      this.currentShop = null
      this.defaultLogShopId = undefined
      this.logList = []
      this.logTotal = 0
      this.logDateRange = []
      this.logQuery = {
        pageNum: 1,
        pageSize: 10,
        shopId: undefined,
        shopName: undefined,
        beginChangeTime: undefined,
        endChangeTime: undefined
      }
      this.logsLoading = false
    },
    /** 店铺状态文案 */
    shopStatusText(row) {
      if (row.deleted) {
        return "已删除"
      }
      return row.shopStatusText || (row.shopStatus === "0" ? "开业" : row.shopStatus === "1" ? "停业" : "—")
    },
    shopStatusTag(row) {
      if (row.deleted) {
        return "info"
      }
      return row.shopStatus === "0" ? "success" : "info"
    },
    /** 金额格式化 */
    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: 4px;
}
.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;
}
.mb8 {
  margin-bottom: 8px;
}
.shop-cell {
  display: flex;
  align-items: center;
  gap: 8px;
}
.shop-name {
  flex: 1;
  min-width: 0;
  line-height: 1.4;
}
.logs-panel {
  padding: 0 8px 16px;
}
.logs-search {
  margin-bottom: 12px;
}
.change-in {
  color: #67c23a;
}
.change-out {
  color: #f56c6c;
}
</style>
