<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="90px">
        <el-form-item label="申请时间">
          <el-date-picker
            v-model="dateRange"
            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="queryParams.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="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">
      <el-tabs v-model="statusTab" @tab-click="handleTabClick">
        <el-tab-pane label="全部" name="all" />
        <el-tab-pane name="1">
          <span slot="label">待审核<el-badge v-if="pendingCount > 0" :value="pendingCount" class="tab-badge" /></span>
        </el-tab-pane>
        <el-tab-pane label="审核不通过" name="2" />
        <el-tab-pane label="提现完成" name="3" />
      </el-tabs>

      <el-row :gutter="10" class="mb8">
        <right-toolbar :showSearch.sync="showSearch" @queryTable="refreshList"></right-toolbar>
      </el-row>

      <el-table border v-loading="loading" :data="withdrawList" :empty-text="emptyTableText">
        <el-table-column label="提现编号" align="center" prop="withdrawNo" min-width="170" :show-overflow-tooltip="true">
          <template slot-scope="scope">
            <span>{{ scope.row.withdrawNo || '—' }}</span>
          </template>
        </el-table-column>
        <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-column label="操作" align="center" width="90" fixed="right">
          <template slot-scope="scope">
            <el-button
              v-if="scope.row.withdrawStatus === '1'"
              size="mini"
              type="text"
              icon="el-icon-edit-outline"
              @click="openAudit(scope.row)"
              v-hasPermi="['agri:finance:withdrawAudit:audit']"
            >审核</el-button>
            <span v-else>—</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>

    <!-- 审核弹窗 -->
    <el-dialog title="提现审核" :visible.sync="auditOpen" width="560px" append-to-body @close="cancelAudit">
      <div v-if="currentRow" class="audit-brief">
        <el-descriptions :column="1" border size="small">
          <el-descriptions-item label="提现编号">{{ currentRow.withdrawNo || '—' }}</el-descriptions-item>
          <el-descriptions-item label="店铺名称">{{ currentRow.shopName || '—' }}</el-descriptions-item>
          <el-descriptions-item label="提现账号">{{ accountSummaryText(currentRow) }}</el-descriptions-item>
          <el-descriptions-item label="提现金额">{{ formatMoney(currentRow.withdrawAmount) }}</el-descriptions-item>
          <el-descriptions-item label="商家备注">{{ currentRow.remark || '—' }}</el-descriptions-item>
        </el-descriptions>
      </div>
      <el-form ref="auditForm" :model="auditForm" :rules="auditRules" label-width="110px" size="small" class="audit-form">
        <el-form-item label="审核结果" prop="auditResult">
          <el-radio-group v-model="auditForm.auditResult">
            <el-radio label="approve">审核通过（提现完成）</el-radio>
            <el-radio label="reject">审核驳回</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="提现处理说明" prop="processRemark">
          <el-input
            v-model="auditForm.processRemark"
            type="textarea"
            :rows="4"
            placeholder="请输入处理说明"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" :loading="auditSubmitting" @click="submitAudit">确 定</el-button>
        <el-button @click="cancelAudit">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listPlatformWithdrawAudits,
  getPlatformWithdrawAuditPendingCount,
  approvePlatformWithdrawAudit,
  rejectPlatformWithdrawAudit
} from "@/api/agri/finance/withdrawAudit"

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

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

export default {
  name: "AgriFinanceWithdrawAudit",
  data() {
    return {
      loading: false,
      showSearch: true,
      total: 0,
      pendingCount: 0,
      withdrawList: [],
      dateRange: [],
      statusTab: "1",
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        withdrawStatus: "1",
        beginApplyTime: undefined,
        endApplyTime: undefined
      },
      withdrawStatusOptions: [
        { value: "1", label: "待审核" },
        { value: "2", label: "审核不通过" },
        { value: "3", label: "提现完成" }
      ],
      auditOpen: false,
      auditSubmitting: false,
      currentRow: null,
      auditForm: {
        auditResult: "approve",
        processRemark: undefined
      },
      auditRules: {
        auditResult: [{ required: true, message: "请选择审核结果", trigger: "change" }],
        processRemark: [{ required: true, message: "请填写提现处理说明", trigger: "blur" }]
      }
    }
  },
  computed: {
    hasSearchFilter() {
      return !!(this.queryParams.withdrawStatus || (this.dateRange && this.dateRange.length))
    },
    emptyTableText() {
      return this.hasSearchFilter ? "未找到符合条件的提现申请" : "暂无提现申请"
    }
  },
  created() {
    this.loadPendingCount()
    this.getList()
  },
  methods: {
    /** 刷新列表与待审数 */
    refreshList() {
      this.loadPendingCount()
      this.getList()
    },
    /** 待审核数量 */
    loadPendingCount() {
      getPlatformWithdrawAuditPendingCount().then(response => {
        this.pendingCount = (response.data && response.data.pendingCount) || 0
      }).catch(() => {})
    },
    /** 构建查询参数 */
    buildQueryParams() {
      const params = { ...this.queryParams }
      if (this.dateRange && this.dateRange.length === 2) {
        params.beginApplyTime = this.dateRange[0]
        params.endApplyTime = this.dateRange[1]
      } else {
        params.beginApplyTime = undefined
        params.endApplyTime = undefined
      }
      return params
    },
    /** 查询列表 */
    getList() {
      this.loading = true
      listPlatformWithdrawAudits(this.buildQueryParams()).then(response => {
        this.withdrawList = response.rows || []
        this.total = response.total || 0
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    handleTabClick() {
      this.queryParams.withdrawStatus = this.statusTab === "all" ? undefined : this.statusTab
      this.queryParams.pageNum = 1
      this.getList()
    },
    handleQuery() {
      this.queryParams.pageNum = 1
      if (this.queryParams.withdrawStatus) {
        this.statusTab = this.queryParams.withdrawStatus
      } else {
        this.statusTab = "all"
      }
      this.getList()
    },
    resetQuery() {
      this.dateRange = []
      this.statusTab = "1"
      this.resetForm("queryForm")
      this.queryParams.pageNum = 1
      this.queryParams.withdrawStatus = "1"
      this.queryParams.beginApplyTime = undefined
      this.queryParams.endApplyTime = undefined
      this.getList()
    },
    /** 打开审核弹窗 */
    openAudit(row) {
      this.currentRow = row
      this.auditForm = {
        auditResult: "approve",
        processRemark: undefined
      }
      this.auditOpen = true
      this.$nextTick(() => {
        if (this.$refs.auditForm) {
          this.$refs.auditForm.clearValidate()
        }
      })
    },
    /** 提交审核 */
    submitAudit() {
      if (!this.currentRow || !this.currentRow.withdrawId) {
        return
      }
      this.$refs.auditForm.validate(valid => {
        if (!valid) {
          return
        }
        const remark = String(this.auditForm.processRemark).trim()
        this.auditSubmitting = true
        const request = this.auditForm.auditResult === "approve"
          ? approvePlatformWithdrawAudit(this.currentRow.withdrawId, { processRemark: remark })
          : rejectPlatformWithdrawAudit({
            withdrawId: this.currentRow.withdrawId,
            processRemark: remark
          })
        request.then(() => {
          this.$modal.msgSuccess("操作成功")
          this.auditOpen = false
          this.auditSubmitting = false
          this.refreshList()
        }).catch(() => {
          this.auditSubmitting = false
        })
      })
    },
    cancelAudit() {
      this.auditOpen = false
      this.currentRow = null
      this.auditSubmitting = false
      this.auditForm = {
        auditResult: "approve",
        processRemark: undefined
      }
      if (this.$refs.auditForm) {
        this.resetForm("auditForm")
      }
    },
    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(".")
    },
    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">
.mb8 {
  margin-bottom: 8px;
}
.tab-badge {
  margin-left: 6px;
}
.audit-brief {
  margin-bottom: 16px;
}
.audit-form {
  margin-top: 8px;
}
</style>
