<template>
  <page-layer>
    <template #header>
      <el-date-picker
          v-model="dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :shortcuts="shortcuts"
          style="width: 260px"
      ></el-date-picker>
      <el-input v-model="patientId" clearable style="width: 100px" placeholder="门诊ID号"></el-input>
      <el-input v-model="patientName" clearable style="width: 100px" placeholder="姓名"></el-input>
      <el-input v-model="tradeNo" clearable style="width: 130px" placeholder="订单号"></el-input>
      <span>&nbsp;订单类型：</span>
      <el-select v-model="orderType" style="width: 100px">
        <el-option v-for="item in orderTypes" :key="item.code" :value="item.code" :label="item.label"></el-option>
      </el-select>
      <span>&nbsp;订单状态：</span>
      <el-select v-model="payStatus" style="width: 100px">
        <el-option v-for="item in payStatuses" :key="item.code" :value="item.code" :label="item.label"></el-option>
      </el-select>
      <span></span>
      <el-button type="primary" icon="Search" @click="fetchData">查询</el-button>
      <el-button type="primary" icon="Upload" @click="exportExcel">导出Excel</el-button>
    </template>
    <template #main>
      <el-table :data="data.list" stripe highlight-current-row>
        <el-table-column prop="patientId" label="门诊ID" width="80"></el-table-column>
        <el-table-column prop="patientName" label="姓名" width="80"></el-table-column>
        <el-table-column prop="body" label="商品" width="180"></el-table-column>
        <el-table-column prop="totalFee" label="金额" width="80" sortable></el-table-column>
        <el-table-column prop="tradeNo" label="订单号" width="160"></el-table-column>
        <el-table-column prop="createDatetime" label="开单时间" width="140" sortable></el-table-column>
        <el-table-column prop="payDatetime" label="支付时间" width="140"></el-table-column>
        <el-table-column label="支付状态" width="80">
          <template #default="scope">
            <span v-html="filterPayStatus(scope.row.payStatus)"></span>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template v-slot="scope">
            <el-button type="danger" icon="Money" @click="doRefund(scope.row)" :disabled="scope.row.payStatus === 4">
              退款
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[15, 30, 45, 70, 100]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="data.totalSize"
          style="margin-top: 5px"
      ></el-pagination>
    </template>
  </page-layer>
</template>

<script>
import {reactive, ref} from 'vue'
import {shortcuts} from '@/data/shortcuts'
import {selectOrdersByConditions, refundOrder} from '@/api/wxpay-refund'
import {ElMessage, ElMessageBox} from 'element-plus'
import {formatDate, getDatetime} from '@/utils/date'
import store from '@/store'
import {downloadExcel} from '@/utils/excel'
import PageLayer from "@/layout/PageLayer";

export default {
  components: {PageLayer},
  setup() {
    const windowSize = store.state.app.windowSize
    const tableHeight = windowSize.h - 85
    const dateRange = ref(null)
    const patientId = ref(null)
    const patientName = ref(null)
    const tradeNo = ref(null)
    const payStatus = ref(-1)
    const payStatuses = initPayStatuses()
    const orderType = ref(-1)
    const orderTypes = initOrderTypes()
    const data = reactive({
      totalSize: 0,
      list: [],
    })
    const pageSize = ref(30)
    const currentPage = ref(1)
    const handleSizeChange = (val) => {
      pageSize.value = val
      fetchData()
    }
    const handleCurrentChange = (val) => {
      currentPage.value = val
      fetchData()
    }

    const fetchData = () => {
      if (!tradeNo.value && !dateRange.value) {
        ElMessage({
          message: '请选择时间范围',
          type: 'warning',
          duration: 2000,
          showClose: true,
        })
        return
      }
      const param = {
        patientId: patientId.value,
        patientName: patientName.value,
        orderType: orderType.value,
        payStatus: payStatus.value,
        tradeNo: tradeNo.value,
        currentPage: currentPage.value,
        pageSize: pageSize.value,
        from: 1,
      }
      if (dateRange.value) {
        param.start = formatDate(dateRange.value[0])
        param.end = formatDate(dateRange.value[1])
      }
      selectOrdersByConditions(param)
          .then((res) => {
            data.totalSize = res.totalSize
            data.list = res.list
          })
          .catch(() => {
            data.value = {}
          })
    }

    const exportExcel = () => {
      if (!tradeNo.value && !dateRange.value) {
        ElMessage({
          message: '请选择时间范围',
          type: 'warning',
          duration: 2000,
          showClose: true,
        })
        return
      }
      store.commit('app/setLoading', true)
      const data = {
        param: {
          start: formatDate(dateRange.value[0]),
          end: formatDate(dateRange.value[1]),
          patientId: patientId.value,
          patientName: patientName.value,
          orderType: orderType.value,
          payStatus: payStatus.value,
          tradeNo: tradeNo.value,
          currentPage: 1,
          pageSize: -1,
        },
        url: '/wxRefund/exportExcel',
        fileName: '服务号订单数据（' + formatDate(dateRange.value[0]) + ' - ' + formatDate(dateRange.value[1]) + '）.xlsx',
      }
      setTimeout(() => {
        downloadExcel(data)
      }, 100)
    }

    const doRefund = (row) => {
      ElMessageBox.prompt('请输入退款原因：', '提示', {
        confirmButtonText: '确定退款',
        cancelButtonText: '取消',
      })
          .then(({value}) => {
            const param = {
              id: row.id,
              totalFee: row.totalFee,
              tradeNo: row.tradeNo,
              refundReason: value,
              refundOpDatetime: getDatetime(),
              refundOpCode: store.state.user.info.code,
            }
            refundOrder(param).then(() => {
              ElMessage({
                message: '退款成功',
                type: 'success',
                duration: 2000,
                showClose: true,
              })
            })
          })
          .catch(() => {
          })
    }
    return {
      tableHeight,
      dateRange,
      shortcuts,
      patientId,
      patientName,
      tradeNo,
      payStatus,
      payStatuses,
      orderType,
      orderTypes,
      filterPayStatus,
      data,
      fetchData,
      doRefund,
      pageSize,
      currentPage,
      handleSizeChange,
      handleCurrentChange,
      exportExcel,
    }
  },
}

function initPayStatuses() {
  return [
    {code: -1, label: '全部'},
    {code: 99, label: '初值'},
    {code: 0, label: '未支付'},
    {code: 1, label: '支付成功'},
    {code: 2, label: '已关闭'},
    {code: 4, label: '已退款'},
    {code: 7, label: '退款失败'},
  ]
}

function filterPayStatus(val) {
  switch (val) {
    case 99:
      return '<span style="color: #909399">初值</span>'
    case 0:
      return '<span style="color: #909399">未支付</span>'
    case 1:
      return '<span style="color: #67C23A">支付成功</span>'
    case 2:
      return '<span style="color: #909399">已关闭</span>'
    case 3:
      return '<span style="color: #F56C6C">支付失败</span>'
    case 4:
      return '<span style="color: #E6A23C">已退款</span>'
    case 5:
      return '<span style="color: #909399">已接收，等待扣款</span>'
    case 6:
      return '<span style="color: #67C23A">用户支付中</span>'
    case 7:
      return '<span style="color: #F56C6C">退款失败</span>'
  }
  return '未知'
}

function initOrderTypes() {
  return [
    {code: -1, label: '全部'},
    {code: 1, label: '挂号费'},
    {code: 2, label: '门诊缴费'},
    {code: 3, label: '住院预交金'},
  ]
}
</script>
