<template>
  <div class="app-container">
    <!-- 检索区 -->
    <el-card shadow="never" class="search-card">
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="80px">
        <el-form-item label="店铺名称" prop="shopName">
          <el-input
            v-model="queryParams.shopName"
            placeholder="请输入店铺名称"
            clearable
            style="width: 220px"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </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.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>

      <el-table border v-loading="loading" :data="shopList" :empty-text="emptyTableText">
        <el-table-column label="店铺名称" align="left" min-width="180" :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" width="130">
          <template slot-scope="scope">
            <span>{{ formatMoney(scope.row.withdrawnAmount) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="待审核金额" align="center" width="130">
          <template slot-scope="scope">
            <span :class="{ 'amount-pending': Number(scope.row.pendingAuditAmount) > 0 }">
              {{ formatMoney(scope.row.pendingAuditAmount) }}
            </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="openDetails(scope.row)" v-hasPermi="['agri:finance:withdrawSummary:detail']">查看提现明细</el-button>
          </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>

    <!-- 提现明细抽屉 -->
    <el-drawer
      :title="detailDrawerTitle"
      :visible.sync="detailOpen"
      size="72%"
      append-to-body
      @close="resetDetails"
    >
      <div class="detail-panel">
        <el-form :model="detailQuery" ref="detailQueryForm" size="small" :inline="true" label-width="80px" class="detail-search">
          <el-form-item label="申请时间">
            <el-date-picker
              v-model="detailDateRange"
              type="daterange"
              value-format="yyyy-MM-dd"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              style="width: 240px"
            />
          </el-form-item>
          <el-form-item label="提现状态" prop="withdrawStatus">
            <el-select v-model="detailQuery.withdrawStatus" placeholder="全部" clearable style="width: 140px">
              <el-option v-for="item in withdrawStatusOptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleDetailQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetDetailQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-table border v-loading="detailLoading" :data="detailList" :empty-text="detailEmptyText">
          <el-table-column label="申请时间" align="center" width="160">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.applyTime) || '—' }}</span>
            </template>
          </el-table-column>
          <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" min-width="180" :show-overflow-tooltip="true">
            <template slot-scope="scope">
              <span>{{ accountSummaryText(scope.row) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="提现金额" align="center" width="110">
            <template slot-scope="scope">
              <span>{{ formatMoney(scope.row.withdrawAmount) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="备注" align="center" min-width="100" :show-overflow-tooltip="true">
            <template slot-scope="scope">
              <span>{{ scope.row.remark || '—' }}</span>
            </template>
          </el-table-column>
          <el-table-column label="提现状态" align="center" width="110">
            <template slot-scope="scope">
              <el-tag size="small" :type="withdrawStatusTag(scope.row.withdrawStatus)">
                {{ scope.row.withdrawStatusText || withdrawStatusLabel(scope.row.withdrawStatus) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="提现处理说明" align="center" min-width="140" :show-overflow-tooltip="true">
            <template slot-scope="scope">
              <span>{{ processRemarkText(scope.row) }}</span>
            </template>
          </el-table-column>
        </el-table>

        <pagination v-show="detailTotal > 0" :total="detailTotal" :page.sync="detailQuery.pageNum" :limit.sync="detailQuery.pageSize" @pagination="getDetailList" />
      </div>
    </el-drawer>
  </div>
</template>

<script>
import {
  listPlatformWithdrawSummaryShops,
  listPlatformWithdrawSummaryDetails
} from "@/api/agri/finance/withdrawSummary"

const WITHDRAW_STATUS_MAP = {
  "1": "待审核",
  "2": "审核不通过",
  "3": "提现完成"
}

const ACCOUNT_TYPE_MAP = {
  "1": "银行卡",
  "2": "支付宝",
  "3": "微信"
}

export default {
  name: "AgriFinanceWithdrawSummary",
  data() {
    return {
      loading: false,
      detailLoading: false,
      showSearch: true,
      total: 0,
      detailTotal: 0,
      shopList: [],
      detailList: [],
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        shopName: undefined
      },
      detailOpen: false,
      currentShop: null,
      detailQuery: {
        pageNum: 1,
        pageSize: 10,
        shopId: undefined,
        withdrawStatus: undefined,
        beginApplyTime: undefined,
        endApplyTime: undefined
      },
      detailDateRange: [],
      withdrawStatusOptions: [
        { value: "1", label: "待审核" },
        { value: "2", label: "审核不通过" },
        { value: "3", label: "提现完成" }
      ]
    }
  },
  computed: {
    emptyTableText() {
      return this.queryParams.shopName ? "未找到符合条件的店铺" : "暂无店铺数据"
    },
    detailDrawerTitle() {
      if (this.currentShop && this.currentShop.shopName) {
        return `提现明细 · ${this.currentShop.shopName}`
      }
      return "提现明细"
    },
    detailEmptyText() {
      const hasFilter = !!(this.detailQuery.withdrawStatus || (this.detailDateRange && this.detailDateRange.length))
      return hasFilter ? "未找到符合条件的提现记录" : "暂无提现记录"
    }
  },
  created() {
    this.getList()
  },
  methods: {
    /** 查询汇总列表 */
    getList() {
      this.loading = true
      listPlatformWithdrawSummaryShops(this.queryParams).then(response => {
        this.shopList = response.rows || []
        this.total = response.total || 0
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    resetQuery() {
      this.resetForm("queryForm")
      this.queryParams.pageNum = 1
      this.queryParams.shopName = undefined
      this.getList()
    },
    /** 打开提现明细抽屉 */
    openDetails(row) {
      this.currentShop = row
      this.detailQuery = {
        pageNum: 1,
        pageSize: 10,
        shopId: row.shopId,
        withdrawStatus: undefined,
        beginApplyTime: undefined,
        endApplyTime: undefined
      }
      this.detailDateRange = []
      this.detailOpen = true
      this.getDetailList()
    },
    /** 构建明细查询参数 */
    buildDetailQueryParams() {
      const params = { ...this.detailQuery }
      if (this.detailDateRange && this.detailDateRange.length === 2) {
        params.beginApplyTime = this.detailDateRange[0]
        params.endApplyTime = this.detailDateRange[1]
      } else {
        params.beginApplyTime = undefined
        params.endApplyTime = undefined
      }
      return params
    },
    /** 查询提现明细 */
    getDetailList() {
      if (!this.detailQuery.shopId) {
        return
      }
      this.detailLoading = true
      listPlatformWithdrawSummaryDetails(this.buildDetailQueryParams()).then(response => {
        this.detailList = response.rows || []
        this.detailTotal = response.total || 0
        this.detailLoading = false
      }).catch(() => {
        this.detailLoading = false
      })
    },
    handleDetailQuery() {
      this.detailQuery.pageNum = 1
      this.getDetailList()
    },
    /** 重置明细检索 */
    resetDetailQuery() {
      this.detailDateRange = []
      this.detailQuery.withdrawStatus = undefined
      this.detailQuery.pageNum = 1
      this.detailQuery.beginApplyTime = undefined
      this.detailQuery.endApplyTime = undefined
      if (this.$refs.detailQueryForm) {
        this.resetForm("detailQueryForm")
      }
      this.getDetailList()
    },
    resetDetails() {
      this.currentShop = null
      this.detailList = []
      this.detailTotal = 0
      this.detailDateRange = []
      this.detailQuery = {
        pageNum: 1,
        pageSize: 10,
        shopId: undefined,
        withdrawStatus: undefined,
        beginApplyTime: undefined,
        endApplyTime: undefined
      }
      this.detailLoading = 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 "¥0.00"
      }
      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(".")
    },
    accountSummaryText(row) {
      if (row.accountSummary) {
        return row.accountSummary
      }
      const type = row.accountTypeText || ACCOUNT_TYPE_MAP[row.accountType] || ""
      const mask = row.accountNoMask || ""
      const name = row.accountRealName || ""
      const text = [type, mask, name].filter(Boolean).join(" ")
      return text || "—"
    },
    processRemarkText(row) {
      if (row.withdrawStatus === "1") {
        return "—"
      }
      return row.processRemark || "—"
    },
    withdrawStatusLabel(status) {
      return WITHDRAW_STATUS_MAP[status] || "—"
    },
    withdrawStatusTag(status) {
      const map = { "1": "warning", "2": "danger", "3": "success" }
      return map[status] || "info"
    }
  }
}
</script>

<style scoped lang="scss">
.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.card-title {
  font-weight: 600;
  font-size: 15px;
}
.mb8 {
  margin-bottom: 8px;
}
.shop-cell {
  display: flex;
  align-items: center;
  gap: 8px;
}
.shop-name {
  flex: 1;
  min-width: 0;
  line-height: 1.4;
}
.amount-pending {
  color: #e6a23c;
  font-weight: 500;
}
.detail-panel {
  padding: 0 8px 16px;
}
.detail-search {
  margin-bottom: 12px;
}
</style>
