<template>
  <div class="app-container">
    <div class="filter-container" style="margin-bottom: 20px;">
      <el-select v-model="listQuery.payment_type" placeholder="请选择充值类型" clearable class="filter-item" style="width: 200px; margin-right: 10px;">
        <el-option label="微信" value="1" />
        <el-option label="支付宝" value="2" />
        <el-option label="银行卡" value="3" />
      </el-select>
      <el-button type="primary" icon="el-icon-search" @click="handleFilter">搜索</el-button>
      <el-button type="success" icon="el-icon-setting" :disabled="selectedIds.length === 0" @click="handleBatchSetData">批量设置渠道信息</el-button>
    </div>

    <el-table
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;height: calc(100% - 120px);"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column prop="id" label="ID" width="80" align="center" />
      <el-table-column prop="order_no" label="订单号" min-width="220" align="center" />
      <el-table-column prop="member_id" label="会员ID" width="120" align="center" />
      <el-table-column prop="first_name" label="用户名/邮箱" min-width="150" align="center" />
      <el-table-column prop="amount" label="充值金额" width="120" align="center">
        <template slot-scope="{row}">
          <span style="color: #F56C6C; font-weight: bold;">{{ row.amount }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="payment_type" label="充值渠道" width="150" align="center">
        <template slot-scope="{row}">
          {{ patTypeText[row.payment_type] }}
        </template>
      </el-table-column>
      <el-table-column prop="payment_type" label="支付凭证" width="150" align="center">
        <template slot-scope="{row}">
          <el-image
            v-if="row.image"
            style="width: 60px; height: 60px"
            :src="row.image"
            :preview-src-list="[row.image]">
          </el-image>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="140" align="center">
        <template slot-scope="{row}">
          <el-tag :type="row.status === 1 ? 'info' : (row.status === 2 ? 'success' : 'danger')">
            {{ statusMap[row.status] || '未知状态' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="created_at" label="创建时间" width="180" align="center" />

      <el-table-column label="操作" align="center" min-width="220" class-name="small-padding fixed-width">
        <template slot-scope="{row}">
          <el-button v-if="row.status === 0" type="primary" size="mini" @click="handleSetSingleData(row)">设置渠道</el-button>
          <el-button v-if="row.status === 5" type="success" size="mini" @click="handlePass(row)">通过</el-button>
          <template v-if="row.status === 0 || row.status === 5">
            <el-button type="danger" size="mini" @click="handleReject(row)">驳回</el-button>
          </template>
        </template>
      </el-table-column>
    </el-table>

    <div style="margin-top: 20px; text-align: right;">
      <el-pagination
        background
        layout="total, prev, pager, next,sizes"
        :total="total"
        :current-page.sync="listQuery.page"
        :page-size="listQuery.limit"
        :page-sizes="[10, 20, 50, 100]"
        @current-change="getList"
        @size-change="handleSizeChange"
      />
    </div>

    <el-dialog title="设置人工充值配置" :visible.sync="configDialogVisible" width="500px">
      <el-form ref="configForm" :model="configForm" :rules="configRules" label-width="100px">
        <el-form-item label="充值类型" prop="payment_type">
          <el-radio-group v-model="configForm.payment_type" :disabled="isDisabledType">
            <el-radio :label="1">微信</el-radio>
            <el-radio :label="2">支付宝</el-radio>
            <el-radio :label="3">银行卡</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="收款人姓名" prop="payName">
          <el-input v-model="configForm.payName" placeholder="请输入收款人姓名" />
        </el-form-item>
        <el-form-item label="收款账号" prop="payAccount">
          <el-input v-model="configForm.payAccount" placeholder="请输入收款账号（如银行卡号/支付宝账号）" />
        </el-form-item>
        <el-form-item label="收款码链接" prop="payQrCode" v-if="configForm.payment_type !== 3">
          <UploadOneImage v-model="configForm.payQrCode" />
        </el-form-item>
        <el-form-item label="开户行" prop="bankName" v-if="configForm.payment_type === 3">
          <el-input v-model="configForm.bankName" placeholder="请输入开户行名称" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="configDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitConfigData">确认提交</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
// 引入你提供的 API
import { getPaymentOrder, paymentOrderSetPayData, paymentOrderManual‌Audit } from '@/api/data'
import UploadOneImage from '@/components/UploadOneImage'
export default {
  name: 'ManualRechargeList',
  components: {
    UploadOneImage
  },
  data() {
    return {
      batchDisabled: true, // 批量设置按钮禁用状态
      list: [],
      total: 0,
      listLoading: false,
      selectedIds: [], // 选中的订单ID数组
      isDisabledType: false,
      // 列表查询参数
      listQuery: {
        page: 1,
        limit: 20,
        channel: 'rgcz', // 固定传值
        payment_type: ''
      },
      patTypeText: {
        1: '微信',
        2: '支付宝',
        3: '银行卡'
      },

      // 状态映射字典 (根据实际业务情况可自行调整)
      statusMap: {
        0: '待处理',
        1: '处理中',
        2: '成功',
        3: '失败',
        4: '待用户上传凭证',
        5: '待审核',
      },

      // --- 充值配置弹窗数据 ---
      configDialogVisible: false,
      configForm: {
        payment_type: 1,
        payName: '',
        payAccount: '',
        payQrCode: '',
        bankName: ''
      },
      configRules: {
        payment_type: [{ required: true, message: '请选择充值类型', trigger: 'change' }],
        payAccount: [{ required: true, message: '请输入收款账号', trigger: 'blur' }]
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    // 获取列表数据
    getList() {
      this.listLoading = true
      getPaymentOrder(this.listQuery).then(res => {
        // 根据你提供的接口数据结构解析
        if (res.code === 0 && res.data) {
          this.list = res.data.data
          this.total = res.data.total
        } else {
          this.$message.error(res.msg || '获取列表失败')
        }
      }).catch(() => {
        this.$message.error('请求异常')
      }).finally(() => {
        this.listLoading = false
      })
    },

    // 搜索按钮
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },

    // 表格多选变化事件
    handleSelectionChange(val) {
      this.selectedIds = val.map(item => item.id)
    },

    // 打开批量设置配置弹窗
    handleBatchSetData() {
      this.isDisabledType = false;
      if (this.selectedIds.length === 0) {
        this.$message.warning('请先选择要配置的订单')
        return
      }
      // 初始化表单
      this.configForm = {
        payment_type: 1,
        payName: '',
        payAccount: '',
        payQrCode: '',
        bankName: ''
      }
      this.configDialogVisible = true
      this.$nextTick(() => {
        this.$refs.configForm.clearValidate()
      })
    },

    // 提交配置数据
    submitConfigData() {
      this.$refs.configForm.validate(valid => {
        if (valid) {
          // 组装 pay_data 格式为 JSON 字符串
          const payDataObj = {
            payName: this.configForm.payName,
            payAccount: this.configForm.payAccount
          }
          if (this.configForm.payment_type !== 3) payDataObj.payQrCode = this.configForm.payQrCode
          if (this.configForm.payment_type === 3) payDataObj.bankName = this.configForm.bankName

          const params = {
            ids: this.selectedIds,
            payment_type: this.configForm.payment_type,
            pay_data: JSON.stringify(payDataObj)
          }

          paymentOrderSetPayData(params).then(res => {
            if (res.code === 0) {
              this.$message.success('配置设置成功')
              this.configDialogVisible = false
              this.getList()
            } else {
              this.$message.error(res.msg || '操作失败')
            }

            this.getList()
          })
        }
      })
    },

    // 设置单行渠道信息
    handleSetSingleData(row) {
      this.isDisabledType = true;
      // 将当前行ID设为选中，复用批量设置的逻辑
      this.selectedIds = [row.id]

      // 初始化表单
      this.configForm = {
        payment_type: row.payment_type,
        payName: '',
        payAccount: '',
        payQrCode: '',
        bankName: ''
      }
      this.configDialogVisible = true
      this.$nextTick(() => {
        this.$refs.configForm.clearValidate()
      })
    },

    // 直接通过操作
    handlePass(row) {
      this.$confirm('确定要通过该人工充值吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        paymentOrderManual‌Audit({ id: row.id, status: 2, remark: '' }).then(res => {
          if (res.code === 0) {
            this.$message.success('审核已通过')
            this.getList()
          } else {
            this.$message.error(res.msg || '操作失败')
            this.getList()
          }
        })
      }).catch(() => {})
    },

    // 驳回操作（带输入原因）
    handleReject(row) {
      this.$prompt('请输入驳回原因', '提示', {
        confirmButtonText: '确定驳回',
        cancelButtonText: '取消',
        inputType: 'textarea',
        inputPlaceholder: '请输入审核备注（驳回时建议填写原因）'
      }).then(({ value }) => {
        paymentOrderManual‌Audit({ id: row.id, status: 3, remark: value || '' }).then(res => {
          if (res.code === 0) {
            this.$message.success('审核已驳回')
            this.getList()
          } else {
            this.$message.error(res.msg || '操作失败')
            this.getList()
          }
        })
      }).catch(() => {})
    },

    handleSizeChange(e) {
      this.listQuery.page = 1
      this.listQuery.limit = e
      this.getList()
    }
  }
}
</script>

<style scoped>
.app-container{
  padding: 20px;
  margin: 20px;
  background-color: #fff;
  border-radius: 8px;
  width: calc(100% - 40px);
  height: calc(100vh - 86px);
}
.filter-container {
  display: flex;
  align-items: center;
}
</style>
