<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" v-if="userInfoVO.userType == '00'">
          <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="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="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="orderStatus">
          <el-select v-model="queryParams.orderStatus" placeholder="请选择订单状态" clearable style="width: 240px">
            <el-option v-for="dict in dict.type.recharge_order_status" :key="dict.code" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item prop="orgId" v-if="userInfoVO.userType == '00'">
          <el-select v-model="queryParams.orgId" placeholder="请选择门店" filterable clearable style="width: 240px">
            <el-option v-for="store in storeList" :key="store.id + store.sourceType" :label="store.name" :value="store.id"> </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="下单时间">
          <el-date-picker v-model="queryCreateTime" type="daterange" value-format="yyyy-MM-dd" range-separator="至" start-placeholder="开始日期"
            end-placeholder="结束日期" style="width: 240px" :picker-options="datePickerOptions" @change="getCreateTime" />
        </el-form-item>
        <el-form-item label="付款时间">
          <el-date-picker v-model="queryPayTime" type="daterange" value-format="yyyy-MM-dd" range-separator="至" start-placeholder="开始日期"
            end-placeholder="结束日期" style="width: 240px" :picker-options="datePickerOptions" @change="getPayTime" />
        </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']"
              v-if="userInfoVO.userType == '00'">导出</el-button>
          </el-col>
          <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </div>

      <Page uri="/mapi/recharge/order/list" :request-params="queryParams" ref="pagination">
        <el-table-column label="订单编号" align="center" width="180" prop="orderNo" fixed="left" :show-overflow-tooltip="true" />
        <el-table-column label="下单门店" align="center" min-width="150" v-if="userInfoVO.userType == '00'" :show-overflow-tooltip="true">
          <template slot-scope="scope">
            {{ scope.row.storeName || '--' }}
          </template>
        </el-table-column>
        <el-table-column label="客户姓名" align="center" prop="realName" min-width="80" :show-overflow-tooltip="true" />
        <el-table-column label="客户手机号" align="center" prop="phoneNumber" width="110" :show-overflow-tooltip="true" />
        <el-table-column label="支付方式" align="center" prop="payType" width="80">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.recharge_pay_type" :value="scope.row.payType" v-if="scope.row.payType" />
            <el-tag size="mini" type="info" v-else>未支付</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="支付金额" align="center" min-width="120">
          <template slot-scope="scope">
            <div class="amount-info">
              <el-tag size="mini" type="primary" v-if="scope.row.cashPayAmount > 0">现金：¥{{ formatAmount(scope.row.cashPayAmount) }}</el-tag>
              <el-tag size="mini" type="primary" v-if="scope.row.wxPayAmount > 0">微信：¥{{ formatAmount(scope.row.wxPayAmount) }}</el-tag>
              <el-tag size="mini" type="primary" v-if="scope.row.aliPayAmount > 0">支付宝：¥{{ formatAmount(scope.row.aliPayAmount) }}</el-tag>
              <el-tag size="mini" type="primary" v-if="scope.row.aliPayAmount == 0 && scope.row.cashPayAmount == 0 && scope.row.wxPayAmount == 0">门店福利金</el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="充值金额" align="center" min-width="120">
          <template slot-scope="scope">
            <div class="amount-info">
              <el-tag size="mini" type="success">现金：¥{{ formatAmount(scope.row.rechargeAmount) }}</el-tag>
              <el-tag size="mini" type="warning">赠送：¥{{ formatAmount(scope.row.giveAmount) }}</el-tag>
              <el-tag size="mini" type="info">福利：¥{{ formatAmount(scope.row.welfareAmount) }}</el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="赠送积分" align="center" width="80" v-if="userInfoVO.userType == '02'">
          <template slot-scope="scope">
            <span class="points">{{ scope.row.givePointAmount || '0' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="订单状态" align="center" width="90">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.recharge_order_status" :value="scope.row.orderStatus" />
          </template>
        </el-table-column>
        <el-table-column label="支付状态" align="center" width="90">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.pay_status" :value="scope.row.payStatus" />
          </template>
        </el-table-column>
        <el-table-column label="退款状态" align="center" width="90">
          <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" width="150" :show-overflow-tooltip="true">
          <template slot-scope="scope">
            <span>{{ scope.row.createTime || '--' }}</span>
          </template>
        </el-table-column> -->
        <el-table-column label="支付时间" align="center" width="150" :show-overflow-tooltip="true">
          <template slot-scope="scope">
            <span>{{ scope.row.payTime || '--' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="退款时间" align="center" width="150" :show-overflow-tooltip="true">
          <template slot-scope="scope">
            <span>{{ scope.row.refundTime || '--' }}</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="100" fixed="right">
          <template slot-scope="scope">
            <el-button type="text" icon="el-icon-tickets" @click="handleDetail(scope.row)">明细</el-button>
            <el-button type="text" icon="el-icon-delete" @click="refundOrder(scope.row)"
              v-if="userInfoVO.userType == '00' && scope.row.refundStatus == '0' && scope.row.orderStatus == '2'">
              撤单
            </el-button>
          </template>
        </el-table-column>
      </Page>
    </el-card>

    <!-- 订单详情对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body destroy-on-close :close-on-click-modal="false">
      <el-card class="box-card detail-card" shadow="never">
        <div class="detail-header">订单明细</div>
        <br/>
        <el-descriptions class="margin-top" :column="2" border>
          <el-descriptions-item label="订单号">{{ orderDetail.orderNo }}</el-descriptions-item>
          <el-descriptions-item label="支付方式">
            <template v-if="orderDetail.payType == '0'">微信</template>
            <template v-if="orderDetail.payType == '1'">支付宝</template>
            <template v-if="orderDetail.payType == '2'">现金</template>
            <template v-if="orderDetail.payType == '3'">余额</template>
            <template v-if="orderDetail.payType == '9'">组合</template>
            <span class="amount">（¥{{ orderDetail.payAmount }}）</span>
          </el-descriptions-item>
          <el-descriptions-item label="客户姓名">{{ orderDetail.appUserName }}</el-descriptions-item>
          <el-descriptions-item label="客户电话">{{ orderDetail.appUserPhone }}</el-descriptions-item>
          <el-descriptions-item label="付款金额">¥{{ orderDetail.payAmount }}</el-descriptions-item>
          <el-descriptions-item label="储值金额" v-if="orderDetail.orderStatus == '2'">¥{{ orderDetail.rechargeAmount }}</el-descriptions-item>
          <el-descriptions-item label="储值赠送金额" v-if="orderDetail.orderStatus == '2'">¥{{ orderDetail.giveAmount }}</el-descriptions-item>
          <el-descriptions-item label="储值福利金额" v-if="orderDetail.orderStatus == '2'">¥{{ orderDetail.welfareAmount }}</el-descriptions-item>
          <el-descriptions-item label="下单时间">{{ orderDetail.createTime }}</el-descriptions-item>
          <el-descriptions-item label="充值门店" :span="2">{{ orderDetail.storeName || '--' }}</el-descriptions-item>
          <el-descriptions-item label="备注">{{ orderDetail.remark || '--' }}</el-descriptions-item>
        </el-descriptions>
      </el-card>

      <el-card class="box-card detail-card" shadow="never" v-if="orderDetail.rechargePasswordCard">
        <div class="detail-header">储值卡明细 : {{ orderDetail.rechargePasswordCard.cardNo }}</div>
        <br/>
        <el-descriptions class="margin-top" :column="2" border>
          <el-descriptions-item label="储值金额">¥{{ orderDetail.rechargePasswordCard.rechargeAmount }}</el-descriptions-item>
          <el-descriptions-item label="储值剩余金额">¥{{ orderDetail.rechargePasswordCard.rechargeBalance }}</el-descriptions-item>
          <el-descriptions-item label="赠送金额">¥{{ orderDetail.rechargePasswordCard.giveAmount }}</el-descriptions-item>
          <el-descriptions-item label="赠送剩余金额">¥{{ orderDetail.rechargePasswordCard.giveBalance }}</el-descriptions-item>
          <el-descriptions-item label="福利金额">¥{{ orderDetail.rechargePasswordCard.welfareAmount }}</el-descriptions-item>
          <el-descriptions-item label="福利剩余金额">¥{{ orderDetail.rechargePasswordCard.welfareBalance }}</el-descriptions-item>
          <el-descriptions-item label="储值卡状态" :span="2">
            <dict-tag :options="dict.type.recharge_use_status" :value="orderDetail.rechargePasswordCard.rechargeStatus" />
          </el-descriptions-item>
        </el-descriptions>
      </el-card>

      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">关 闭</el-button>
      </div>
    </el-dialog>

    <!-- 撤单对话框 -->
    <el-dialog title="撤单确认" :visible.sync="openRefundPage" width="500px" append-to-body destroy-on-close :close-on-click-modal="false">
      <el-form ref="refundVO" :model="refundVO" :rules="refundRules">
        <el-form-item label="撤单原因" prop="refundDescribe" label-width="80px">
          <el-input v-model="refundVO.refundDescribe" type="textarea" placeholder="请输入撤单原因" maxlength="500" :rows="5" show-word-limit>
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitRefund" :loading="refundLoading">确 定</el-button>
        <el-button @click="openRefundPage = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listOrder, getOrder, delOrder, addOrder, updateOrder, getPayDetailById } from '@/api/recharge/order'
import { allOrg } from '@/api/system/store'
import { refundOrderGoods } from '@/api/order/goods'
import { refundRecharge } from '@/api/recharge/refund'

export default {
  name: 'OrderRechargeRecord',
  dicts: ['recharge_use_status', 'pay_status','recharge_refund_status', 'recharge_pay_type', 'recharge_order_status'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 充值订单表格数据
      orderList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      openRefundPage: false,
      // 查询参数
      queryParams: {
        orderNo: null,
        sourceType: null,
        orgId: null,
        storeName: null,
        phoneNumber: null,
        realName: null,
        orderStatus: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {},
      queryCreateTime: null,
      queryPayTime: null,
      userInfoVO: null,
      orderDetail: {},
      storeList: [],
      payDetailList: [],
      refundVO: {
        orderId: null,
        refundDescribe: null
      },
      // 新增的属性
      refundLoading: false,
      refundRules: {
        refundDescribe: [
          { required: true, message: '请输入撤单原因', trigger: 'blur' },
          { min: 2, max: 500, message: '长度在 2 到 500 个字符', trigger: 'blur' }
        ]
      },
      datePickerOptions: {
        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])
            }
          }
        ]
      }
    }
  },
  created() {
    allOrg().then((res) => {
      res.data.forEach((org) => {
        if (org.sourceType == '02') {
          this.storeList.push(org)
        }
      })
    })
    this.handleUser()
    this.getList()
  },
  methods: {
    getCreateTime() {
      if (this.queryCreateTime != null) {
        this.queryParams.createTimeFrom = this.queryCreateTime[0]
        this.queryParams.createTimeTo = this.queryCreateTime[1]
      }
    },
    getPayTime() {
      if (this.queryPayTime != null) {
        this.queryParams.beginPayTime = this.queryPayTime[0]
        this.queryParams.endPayTime = this.queryPayTime[1]
      }
    },
    handleUser() {
      this.userInfoVO = this.getUserInfo()
    },
    /** 查询充值订单列表 */
    getList() {
      this.$nextTick(() => {
        this.$refs.pagination.handleSearch(true)
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {}
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryCreateTime = null
      this.queryParams.createTimeFrom = null
      this.queryParams.createTimeTo = null

      this.queryPayTime = null
      this.queryParams.beginPayTime = null
      this.queryParams.endPayTime = null
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '添加充值订单'
    },
    /** 支付明细详情 */
    handleDetail(row) {
      this.reset()
      const id = row.id
      getOrder(id).then((response) => {
        this.orderDetail = response.data
        this.open = true
        this.title = '支付明细详情'
      })
    },
    // 撤单
    refundOrder(row) {
      this.refundVO = {}
      this.openRefundPage = true
      this.refundVO.orderId = row.id
    },
    /** 提交撤单 */
    submitRefund() {
      this.$refs.refundVO.validate(valid => {
        if (valid) {
          this.$confirm('是否确认撤回该订单？', '提示', {
            type: 'warning'
          }).then(() => {
            this.refundLoading = true
            refundRecharge(this.refundVO)
              .then(response => {
                this.$modal.msgSuccess('撤单成功')
                this.getList()
                this.openRefundPage = false
              })
              .finally(() => {
                this.refundLoading = false
              })
          })
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal
        .confirm('是否确认删除充值订单编号为"' + ids + '"的数据项？')
        .then(function () {
          return delOrder(ids)
        })
        .then(() => {
          this.getList()
          this.$modal.msgSuccess('删除成功')
        })
        .catch(() => { })
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        'mapi/recharge/order/export',
        {
          ...this.queryParams
        },
        `recharge_order_${new Date().getTime()}.xlsx`
      )
    },
    checkClose(done) {
      this.$confirm('是否关闭表单，关闭后数据将丢失？')
        .then(function () {
          done()
        })
        .then(() => { })
        .catch(() => { })
    },
    /** 格式化金额显示 */
    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);
        }

        &.detail-card {
            margin-bottom: 20px;

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

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

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

    .detail-header {
        font-size: 15px;
        font-weight: bold;
        color: #303133;
        margin-bottom: 20px;
    }

    .amount {
        color: #f56c6c;
        font-weight: 500;
        font-size: 14px;
    }

    .points {
        color: #e6a23c;
        font-weight: 500;
        font-size: 14px;
    }

    .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-descriptions) {
        margin: 10px 0;

        .el-descriptions-item__label {
            width: 120px;
            font-weight: bold;
            background-color: #fafafa;
        }

        .el-descriptions-item__content {
            padding: 12px 15px;
        }
    }

    :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;
            }
        }
    }

    .dialog-footer {
        text-align: right;
        padding-top: 20px;
    }
}
</style>
