<template>
  <div class="app-container">
    <!-- 提交提现 -->
    <el-card shadow="never" class="submit-card" v-loading="balanceLoading">
      <div slot="header" class="card-header">
        <span class="card-title">提交提现</span>
        <span class="balance-tip">可用店铺余额：<strong>{{ formatMoney(availableBalance) }}</strong></span>
      </div>

      <el-alert
        v-if="accountOptions.length === 0"
        title="暂无收款账户，请先在「账户管理」中添加银行卡/支付宝/微信账户后再提交提现"
        type="warning"
        :closable="false"
        show-icon
        class="mb12"
      />

      <el-form ref="submitForm" :model="submitForm" :rules="submitRules" label-width="100px" size="small" class="submit-form">
        <el-row :gutter="24">
          <el-col :xs="24" :sm="12" :md="8">
            <el-form-item label="提现账户" prop="accountId">
              <el-select
                v-model="submitForm.accountId"
                placeholder="请选择提现账户"
                filterable
                clearable
                style="width: 100%"
                :disabled="accountOptions.length === 0"
              >
                <el-option
                  v-for="item in accountOptions"
                  :key="item.accountId"
                  :label="item.label || buildAccountLabel(item)"
                  :value="item.accountId"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8">
            <el-form-item label="提现金额" prop="withdrawAmount">
              <el-input-number
                v-model="submitForm.withdrawAmount"
                :min="0.01"
                :precision="2"
                :step="1"
                controls-position="right"
                style="width: 100%"
                placeholder="请输入提现金额"
              />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="8">
            <el-form-item label="备注" prop="remark">
              <el-input
                v-model="submitForm.remark"
                type="textarea"
                :rows="2"
                placeholder="选填"
                maxlength="200"
                show-word-limit
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item>
          <el-button
            type="primary"
            :loading="submitting"
            :disabled="accountOptions.length === 0"
            @click="handleSubmit"
            v-hasPermi="['agri:seller:finance:withdraw:submit']"
          >提交提现</el-button>
          <el-button @click="resetSubmitForm">重 置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <br/>

    <!-- 检索区 -->
    <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">
      <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="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" min-width="200" :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="120" :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="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />
    </el-card>
  </div>
</template>

<script>
import {
  listSellerWithdraws,
  getSellerWithdrawBalance,
  submitSellerWithdraw
} from "@/api/agri/seller/finance/withdraw"
import { listSellerPayAccountOptions } from "@/api/agri/seller/finance/payAccount"
import { getSellerContext } from "@/api/agri/seller/context"
import { setSellerShopContext } from "@/utils/sellerShop"

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

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

export default {
  name: "AgriSellerFinanceWithdraw",
  data() {
    const validateWithdrawAmount = (rule, value, callback) => {
      if (value == null || value === "") {
        callback(new Error("请输入有效的提现金额"))
        return
      }
      const num = Number(value)
      if (isNaN(num) || num <= 0) {
        callback(new Error("请输入有效的提现金额"))
        return
      }
      const balance = Number(this.availableBalance)
      if (!isNaN(balance) && num > balance) {
        callback(new Error("提现金额不能超过可用余额"))
        return
      }
      callback()
    }
    return {
      loading: false,
      balanceLoading: false,
      submitting: false,
      showSearch: true,
      total: 0,
      availableBalance: null,
      accountOptions: [],
      withdrawList: [],
      dateRange: [],
      submitForm: {
        accountId: undefined,
        withdrawAmount: undefined,
        remark: undefined
      },
      submitRules: {
        accountId: [{ required: true, message: "请选择提现账户", trigger: "change" }],
        withdrawAmount: [{ validator: validateWithdrawAmount, trigger: "blur" }]
      },
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        withdrawStatus: undefined,
        beginApplyTime: undefined,
        endApplyTime: undefined
      },
      withdrawStatusOptions: [
        { value: "1", label: "待审核" },
        { value: "2", label: "审核不通过" },
        { value: "3", label: "提现完成" }
      ]
    }
  },
  computed: {
    hasSearchFilter() {
      return !!(this.queryParams.withdrawStatus || (this.dateRange && this.dateRange.length))
    },
    emptyTableText() {
      return this.hasSearchFilter ? "未找到符合条件的提现记录" : "暂无提现记录"
    }
  },
  created() {
    this.initPage()
  },
  methods: {
    /** 初始化：加载店铺上下文后拉数据 */
    initPage() {
      this.loadShopContext().then(() => {
        this.loadBalance()
        this.loadAccountOptions()
        this.getList()
      }).catch(() => {
        this.loadBalance()
        this.loadAccountOptions()
        this.getList()
      })
    },
    /** 加载商家端当前店铺上下文 */
    loadShopContext() {
      return getSellerContext().then(response => {
        const data = response.data || {}
        if (data.shopId != null) {
          setSellerShopContext(data.shopId, data.shopName)
        }
      })
    },
    /** 查询可用余额 */
    loadBalance() {
      this.balanceLoading = true
      getSellerWithdrawBalance().then(response => {
        const data = response.data || {}
        this.availableBalance = data.availableBalance
        this.balanceLoading = false
      }).catch(() => {
        this.balanceLoading = false
      })
    },
    /** 加载提现账户下拉 */
    loadAccountOptions() {
      listSellerPayAccountOptions().then(response => {
        this.accountOptions = response.data || []
      }).catch(() => {
        this.accountOptions = []
      })
    },
    /** 构建查询参数（含申请时间区间） */
    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
      listSellerWithdraws(this.buildQueryParams()).then(response => {
        this.withdrawList = response.rows || []
        this.total = response.total || 0
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    resetQuery() {
      this.dateRange = []
      this.resetForm("queryForm")
      this.queryParams.pageNum = 1
      this.queryParams.beginApplyTime = undefined
      this.queryParams.endApplyTime = undefined
      this.getList()
    },
    /** 提交提现 */
    handleSubmit() {
      this.$refs.submitForm.validate(valid => {
        if (!valid) {
          return
        }
        this.submitting = true
        submitSellerWithdraw({
          accountId: this.submitForm.accountId,
          withdrawAmount: Number(this.submitForm.withdrawAmount),
          remark: this.submitForm.remark ? String(this.submitForm.remark).trim() : undefined
        }).then(() => {
          this.$modal.msgSuccess("提交成功")
          this.resetSubmitForm()
          this.loadBalance()
          this.getList()
          this.submitting = false
        }).catch(() => {
          this.submitting = false
        })
      })
    },
    /** 重置提交表单 */
    resetSubmitForm() {
      this.submitForm = {
        accountId: undefined,
        withdrawAmount: undefined,
        remark: undefined
      }
      if (this.$refs.submitForm) {
        this.resetForm("submitForm")
      }
    },
    /** 金额格式化 */
    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(".")
    },
    /** 账户下拉 label 兜底 */
    buildAccountLabel(item) {
      const type = item.accountTypeText || ACCOUNT_TYPE_MAP[item.accountType] || ""
      const mask = item.accountNoMask || ""
      const name = item.realName || ""
      return [type, mask, name].filter(Boolean).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;
  flex-wrap: wrap;
  gap: 8px;
}
.card-title {
  font-weight: 600;
  font-size: 15px;
}
.balance-tip {
  font-size: 13px;
  color: #606266;
  strong {
    color: #303133;
    font-size: 15px;
  }
}
.submit-form {
  max-width: 1200px;
}
.mb8 {
  margin-bottom: 8px;
}
.mb12 {
  margin-bottom: 12px;
}
</style>
