<template>
  <div class="app-container">
    <!-- 搜索区域卡片 -->
    <el-card class="box-card" shadow="never">
      <el-form :model="queryParams" ref="queryForm" @submit.native.prevent :inline="true" v-show="showSearch" label-width="100px">
        <el-form-item prop="orderNo">
          <el-input v-model="queryParams.orderNo" placeholder="请输入订单编号" clearable prefix-icon="el-icon-document" style="width: 240px"
            @keyup.enter.native="handleQuery" />
        </el-form-item>
        <el-form-item prop="phoneNumber">
          <el-input v-model="queryParams.phoneNumber" placeholder="请输入手机号" clearable prefix-icon="el-icon-mobile-phone" style="width: 240px"
            @keyup.enter.native="handleQuery" />
        </el-form-item>
        <el-form-item prop="realName">
          <el-input v-model="queryParams.realName" placeholder="请输入客户姓名" clearable prefix-icon="el-icon-user" style="width: 240px"
            @keyup.enter.native="handleQuery" />
        </el-form-item>
        <el-form-item prop="storeName">
          <el-input v-model="queryParams.storeName" placeholder="请输入门店名称" clearable prefix-icon="el-icon-office-building" style="width: 240px"
            @keyup.enter.native="handleQuery" />
        </el-form-item>
        <el-form-item label="申请时间">
          <el-date-picker v-model="dateRange" type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期"
            value-format="yyyy-MM-dd" style="width: 240px" :picker-options="pickerOptions" @change="handleDateChange">
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 表格区域卡片 -->
    <el-card class="box-card table-card" shadow="never">
      <div slot="header" class="clearfix">
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="warning" plain icon="el-icon-download" @click="handleExport" v-hasPermi="['recharge:order:export']">导出</el-button>
          </el-col>
          <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </div>

      <Page uri="/mapi/recharge/refund/list" :request-params="queryParams" ref="pagination">
        <el-table-column label="订单编号" align="center" prop="orderNo" min-width="130" fixed="left" :show-overflow-tooltip="true" />
        <el-table-column label="储值卡号" align="center" prop="cardNo" min-width="130" :show-overflow-tooltip="true" />
        <el-table-column label="储值门店" align="center" min-width="150" :show-overflow-tooltip="true">
          <template slot-scope="scope">
            {{ scope.row.storeName || '--' }}
          </template>
        </el-table-column>
        <el-table-column label="姓名" align="center" prop="appUserName" min-width="100" :show-overflow-tooltip="true" />
        <el-table-column label="手机号" align="center" prop="appUserPhone" width="120" :show-overflow-tooltip="true" />
        <el-table-column label="退款方式" align="center" prop="refundType" width="100">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.recharge_pay_type" :value="scope.row.refundType" />
          </template>
        </el-table-column>
        <el-table-column label="退款金额" align="center" min-width="180">
          <template slot-scope="scope">
            <div class="amount-info">
              <el-tag size="mini" type="primary" v-if="scope.row.cashRefundAmount > 0">现金：¥{{ formatAmount(scope.row.cashRefundAmount) }}</el-tag>
              <el-tag size="mini" type="primary" v-if="scope.row.wxRefundAmount > 0">微信：¥{{ formatAmount(scope.row.wxRefundAmount) }}</el-tag>
              <el-tag size="mini" type="primary" v-if="scope.row.aliRefundAmount > 0">支付宝：¥{{ formatAmount(scope.row.aliRefundAmount) }}</el-tag>
              <el-tag size="mini" type="primary" v-if="scope.row.refundAmount == 0">¥{{ formatAmount(scope.row.refundAmount) }}</el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="卡内余额" align="center" min-width="180">
          <template slot-scope="scope">
            <div class="amount-info">
              <el-tag size="mini" type="success">现金：¥{{ formatAmount(scope.row.rechargeBalance) }}</el-tag>
              <el-tag size="mini" type="warning">赠送：¥{{ formatAmount(scope.row.giveBalance) }}</el-tag>
              <el-tag size="mini" type="info">福利：¥{{ formatAmount(scope.row.welfareBalance) }}</el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="退卡状态" align="center" prop="refundStatus" width="100">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.recharge_refund_status" :value="scope.row.refundStatus" />
          </template>
        </el-table-column>
        <el-table-column label="退款描述" align="center" prop="refundReason" min-width="150" :show-overflow-tooltip="true" />
        <el-table-column label="退款申请时间" align="center" prop="refundApplyTime" width="160" :show-overflow-tooltip="true">
          <template slot-scope="scope">
            <span>{{ scope.row.refundApplyTime || '--' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="退款时间" align="center" prop="refundTime" width="160" :show-overflow-tooltip="true">
          <template slot-scope="scope">
            <span>{{ scope.row.refundTime || '--' }}</span>
          </template>
        </el-table-column>

        <el-table-column label="操作" align="center" width="150" fixed="right">
          <template slot-scope="scope" v-if="scope.row.refundStatus == '1'">
            <el-button type="text" icon="el-icon-close" @click="handleApprovalNo(scope.row)" v-hasPermi="['recharge:order:edit']">拒绝</el-button>
            <el-button type="text" icon="el-icon-check" @click="handleApprovalYes(scope.row)" v-hasPermi="['recharge:order:edit']">同意</el-button>
          </template>
        </el-table-column>
      </Page>
    </el-card>

    <!-- 退款审核确认对话框 -->
    <el-dialog :title="approvalTitle" :visible.sync="approvalDialogVisible" width="500px" append-to-body destroy-on-close
      :close-on-click-modal="false">
      <el-form ref="approvalForm" :model="approvalForm" :rules="approvalRules" label-width="100px">
        <el-form-item label="退款原因" prop="reason" v-if="approvalType === 'reject'">
          <el-input v-model="approvalForm.reason" type="textarea" :rows="4" placeholder="请输入拒绝退款的原因" maxlength="500" show-word-limit>
          </el-input>
        </el-form-item>
        <div v-else class="approval-info">
          <p>退款信息确认：</p>
          <ul>
            <li>卡内现金余额：<span class="amount">¥{{ formatAmount(currentRecord.rechargeBalance) }}</span></li>
            <li>卡内赠送余额：<span class="amount">¥{{ formatAmount(currentRecord.giveBalance) }}</span></li>
            <li>可退金额：<span class="amount">¥{{ formatAmount(currentRecord.rechargeBalance) }}</span></li>
          </ul>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitApproval" :loading="approvalLoading">确 定</el-button>
        <el-button @click="approvalDialogVisible = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listRefund, refundApprovalNo, refundApprovalYes } from '@/api/recharge/refund'

export default {
  name: 'Refund',
  dicts: ['recharge_use_status', 'recharge_refund_status', 'recharge_pay_type', 'recharge_order_status'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 查询参数
      queryParams: {
        orderNo: null,
        orgId: null,
        storeName: null,
        phoneNumber: null,
        realName: null,
        beginTime: null,
        endTime: null
      },
      // 日期范围
      dateRange: null,
      // 日期选择器快捷选项
      pickerOptions: {
        shortcuts: [
          {
            text: '最近一周',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
              picker.$emit('pick', [start, end])
            }
          }
        ]
      },
      // 审核相关
      approvalDialogVisible: false,
      approvalTitle: '',
      approvalType: '',
      approvalLoading: false,
      currentRecord: {},
      approvalForm: {
        reason: ''
      },
      approvalRules: {
        reason: [
          { required: true, message: '请输入拒绝原因', trigger: 'blur' },
          { min: 2, max: 500, message: '长度在 2 到 500 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    /** 查询列表 */
    getList() {
      this.$nextTick(() => {
        this.$refs.pagination.handleSearch(true)
      })
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = null
      this.queryParams.beginTime = null
      this.queryParams.endTime = null
      this.resetForm('queryForm')
      this.handleQuery()
    },
    /** 日期范围变化 */
    handleDateChange(dates) {
      if (dates) {
        this.queryParams.beginTime = dates[0]
        this.queryParams.endTime = dates[1]
      } else {
        this.queryParams.beginTime = null
        this.queryParams.endTime = null
      }
    },
    /** 拒绝退卡 */
    handleApprovalNo(row) {
      this.currentRecord = row
      this.approvalType = 'reject'
      this.approvalTitle = '拒绝退卡确认'
      this.approvalForm.reason = ''
      this.approvalDialogVisible = true
    },
    /** 同意退卡 */
    handleApprovalYes(row) {
      this.currentRecord = row
      this.approvalType = 'approve'
      this.approvalTitle = '同意退卡确认'
      this.approvalDialogVisible = true
    },
    /** 提交审核 */
    submitApproval() {
      if (this.approvalType === 'reject') {
        this.$refs.approvalForm.validate(valid => {
          if (valid) {
            this.approvalLoading = true
            refundApprovalNo(this.currentRecord.id, this.approvalForm.reason)
              .then(() => {
                this.$modal.msgSuccess('已拒绝退卡申请')
                this.approvalDialogVisible = false
                this.getList()
              })
              .finally(() => {
                this.approvalLoading = false
              })
          }
        })
      } else {
        this.approvalLoading = true
        refundApprovalYes(this.currentRecord.id)
          .then(() => {
            this.$modal.msgSuccess('已同意退卡申请')
            this.approvalDialogVisible = false
            this.getList()
          })
          .finally(() => {
            this.approvalLoading = false
          })
      }
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        'mapi/recharge/refund/export',
        {
          ...this.queryParams
        },
        `refund_${new Date().getTime()}.xlsx`
      )
    },
    /** 格式化金额 */
    formatAmount(amount) {
      if (!amount) return '0.00'
      return parseFloat(amount).toFixed(2)
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
    padding: 20px;
    background-color: #f5f7fa;

    .box-card {
        margin-bottom: 20px;
        transition: all 0.3s ease-in-out;

        &.table-card {
            margin-bottom: 0;
        }

        &:hover {
            box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
        }
    }

    :deep(.el-card__header) {
        padding: 15px 20px;
        border-bottom: 1px solid #ebeef5;
        background-color: #fafafa;
    }

    :deep(.el-card__body) {
        padding: 20px;
    }

    .amount-info {
        .el-tag {
            margin: 0 4px;
            transition: all 0.3s ease;

            &:first-child {
                margin-left: 0;
            }

            &:last-child {
                margin-right: 0;
            }

            &:hover {
                transform: translateY(-1px);
            }
        }
    }

    :deep(.el-table) {
        .el-table__header th {
            background-color: #fafafa;
            color: #606266;
            font-weight: bold;
        }

        .el-table__row {
            transition: all 0.3s ease;

            &:hover {
                background-color: #f5f7fa;
            }
        }
    }

    .approval-info {
        padding: 15px;
        background-color: #f5f7fa;
        border-radius: 4px;

        p {
            margin: 0 0 10px;
            font-weight: bold;
            color: #303133;
        }

        ul {
            margin: 0;
            padding: 0;
            list-style: none;

            li {
                margin-bottom: 8px;
                color: #606266;

                &:last-child {
                    margin-bottom: 0;
                }

                .amount {
                    color: #f56c6c;
                    font-weight: 500;
                }
            }
        }
    }
}
</style>
