<!-- 拼团订单 -->
<template>
  <div>
    <div class="row">
      <el-form :model="queryForm" inline>
        <el-form-item label="订单状态">
          <el-select v-model="queryForm.status" style="width: 150px;">
            <el-option v-for="item in statusList" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="下单时间">
          <el-date-picker style="width: 300px" v-model="confirmOrderTimes" type="daterange" range-separator="至"
            start-placeholder="开始日期" end-placeholder="结束日期" value-format="YYYY-MM-DD"
            @change="confirmOrderTimesChange"></el-date-picker>
        </el-form-item>
        <el-form-item label="核销时间">
          <el-date-picker style="width: 300px" v-model="checkoutOrderTimes" type="daterange" range-separator="至"
            start-placeholder="开始日期" end-placeholder="结束日期" value-format="YYYY-MM-DD"
            @change="checkoutOrderTimesChange"></el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-input :maxlength="11" v-model="queryForm.phone" placeholder="请输入手机号"
            @input="e => queryForm.phone = filterNumberInput(e, 1)"></el-input>
        </el-form-item>
        <el-form-item>
          <el-input v-model="queryForm.orderNo" placeholder="请输入订单号"></el-input>
        </el-form-item>
        <!-- <el-form-item>
          <el-input v-model="queryForm.groupOrderNo" placeholder="请输入关联团单号"></el-input>
        </el-form-item> -->
        <el-form-item>
          <el-input v-model="queryForm.name" placeholder="请输入套餐名称"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" :loading="tableData.loading" @click="searchHandle">搜索</el-button>
          <el-button icon="Refresh" :loading="tableData.loading" @click="refreshHandle">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="row">
      <div class="info_wrap">
        <div class="item">
          <div class="icon">
            <img class="img" src="@/assets/fenxiao/3.png">
          </div>
          <div class="info">
            <div>总订单数</div>
            <div>{{ multiplyAndFormat(infoObj.countNum || 0) }}</div>
          </div>
        </div>
        <div class="item">
          <div class="icon">
            <img class="img" src="@/assets/fenxiao/4.png">
          </div>
          <div class="info">
            <div>已支付金额（元）</div>
            <div>{{ multiplyAndFormat(infoObj.paidAmountTotal || 0) }}</div>
          </div>
        </div>
        <div class="item">
          <div class="icon">
            <img class="img" src="@/assets/fenxiao/5.png">
          </div>
          <div class="info">
            <div>已退款金额（元）</div>
            <div>{{ multiplyAndFormat(infoObj.refundAmount || 0) }}</div>
          </div>
        </div>
      </div>
    </div>
    <div class="row mt14">
      <el-table :data="tableData.list" stripe border v-loading="tableData.loading">
        <el-table-column label="订单号" prop="orderNo" width="180"></el-table-column>
        <el-table-column label="套餐" prop="packageName" width="200">
          <template v-slot="scope">
            <div class="center">
              <el-image :src="scope.row.images[0]" style="width: 40px;height: 40px;flex-shrink: 0;"></el-image>
              <el-text>{{ scope.row.packageName }}</el-text>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="价格（元）" prop="price" width="130"></el-table-column>
        <el-table-column label="购买用户" prop="userName" width="200">
          <template v-slot="scope">
            <div class="center">
              {{ scope.row.nickname }} / {{ scope.row.phone }}
            </div>
          </template>
        </el-table-column>
        <el-table-column label="分享人数" prop="shareNum" width="130"></el-table-column>
        <el-table-column label="最终支付金额（元）" prop="finalPrice" width="180"></el-table-column>
        <el-table-column label="支付时间" prop="payTime" width="180"></el-table-column>
        <el-table-column label="状态" prop="status" width="100">
          <template v-slot="scope">
            <el-tag disable-transitions :type="statusFilter(scope.row).type">
              {{ statusFilter(scope.row).label }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="核销码" prop="verifyCode" width="180"></el-table-column>
        <el-table-column label="核销时间" prop="verifyTime" width="180"></el-table-column>
        <el-table-column label="操作" width="120" fixed="right">
          <template v-slot="scope">
            <template v-if="scope.row.status == 'refunding'">
              <el-button link type="danger" @click="refundPopupHandle(scope.row)">审核</el-button>
            </template>
            <template v-if="scope.row.status == 'wait_verify'">
              <el-popconfirm title="确认要退款吗？" @confirm="refundHandle(scope.row)">
                <template #reference>
                  <el-button link type="danger">退款</el-button>
                </template>
              </el-popconfirm>
            </template>
            <template v-if="scope.row.status == 'wait_verify'">
              <el-popconfirm title="确认要核销吗？" @confirm="checkoutHandle(scope.row)">
                <template #reference>
                  <el-button link type="primary">核销</el-button>
                </template>
              </el-popconfirm>
            </template>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="row mt14">
      <el-pagination v-model:current-page="tableData.page" v-model:page-size="tableData.size"
        :page-sizes="[10, 20, 50, 100, 500]" background layout="total, sizes, prev, pager, next, jumper"
        :total="tableData.total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
    </div>
    <refundDialog ref="refundDialogRef" @confirm="confirmRefundHandle" />
  </div>
</template>

<script setup>
import dayjs from 'dayjs'
import { ref, reactive } from 'vue'
import refundDialog from '@/components/refundDialog/index.vue'
import { filterNumberInput, multiplyAndFormat } from '@/utils'
import { packageOrder, packageConfirmRefund, packageRejectRefund, packageCheckout, packageOrderStat } from '@/api/market/ware'

const refundDialogRef = ref(null)

const statusList = ref([
  {
    label: '进行中',
    value: 'ing',
    type: 'warning'
  },
  {
    label: '待核销',
    value: 'wait_verify',
    type: 'warning'
  },
  {
    label: '已核销',
    value: 'finish',
    type: 'success'
  },
  {
    label: '退款中',
    value: 'refunding',
    type: 'danger'
  },
  {
    label: '已退款',
    value: 'refund',
    type: 'info'
  },
  {
    label: '已取消',
    value: 'cancel',
    type: 'info'
  },
  {
    label: '超时',
    value: 'timeout',
    type: 'danger'
  }
])

// 筛选tag type
function statusFilter(row) {
  let obj = statusList.value.find(item => item.value == row.status)
  if (obj) {
    return obj
  } else {
    return {
      label: row.status,
      value: 'unknown',
      type: 'info'
    }
  }
}

const confirmOrderTimes = ref([])
const checkoutOrderTimes = ref([])
const queryForm = reactive({
  status: '',
  orderStartTime: '',
  orderEndTime: '',
  verifyStartTime: '',
  verifyEndTime: '',
  phone: '',
  orderNo: '',
  groupOrderNo: '',
  name: ''
})

// 搜索
function searchHandle() {
  tableData.page = 1
  getData()
}

// 重置搜索
function refreshHandle() {
  confirmOrderTimes.value = []
  checkoutOrderTimes.value = []

  queryForm.status = ''
  queryForm.orderStartTime = ''
  queryForm.orderEndTime = ''
  queryForm.verifyStartTime = ''
  queryForm.verifyEndTime = ''
  queryForm.phone = ''
  queryForm.orderNo = ''
  queryForm.groupOrderNo = ''
  queryForm.name = ''
  searchHandle()
}

// 下单时间范围
function confirmOrderTimesChange(value) {
  if (value && value.length === 2) {
    queryForm.orderStartTime = dayjs(value[0]).format('YYYY-MM-DD 00:00:00');
    queryForm.orderEndTime = dayjs(value[1]).format('YYYY-MM-DD 23:59:59');
  } else {
    queryForm.orderStartTime = '';
    queryForm.orderEndTime = '';
  }
}

// 核销时间范围
function checkoutOrderTimesChange(value) {
  if (value && value.length === 2) {
    queryForm.verifyStartTime = dayjs(value[0]).format('YYYY-MM-DD 00:00:00');
    queryForm.verifyEndTime = dayjs(value[1]).format('YYYY-MM-DD 23:59:59');
  } else {
    queryForm.verifyStartTime = '';
    queryForm.verifyEndTime = '';
  }
}

// 订单统计数据
const infoObj = reactive({
  countNum: 0,          // 总交易笔数
  paidAmountTotal: 0,   // 已支付金额
  refundAmount: 0       // 已退款金额
})

const tableData = reactive({
  page: 1,
  size: 10,
  total: 0,
  list: [],
  loading: false
})

// 分页大小发生变化
function handleSizeChange(e) {
  tableData.size = e;
  getData();
}

// 分页发生变化
function handleCurrentChange(e) {
  tableData.page = e;
  getData();
}

// 直接退款操作
async function refundHandle(row) {
  try {
    tableData.loading = true
    await packageConfirmRefund({
      recordId: row.id,
      orderNo: row.orderNo,
      reason: ''
    })
    ElNotification({
      title: '注意',
      message: '操作成功',
      type: 'success'
    })
    getData()
  } catch (error) {
    console.log(error);
  }
  tableData.loading = false
}

// 确认退款操作
async function confirmRefundHandle(form) {
  try {
    tableData.loading = true
    if (form.type === 1) {
      // 通过
      await packageConfirmRefund({
        recordId: refundRow.value.id,
        orderNo: refundRow.value.orderNo,
        reason: form.reason
      })
      ElNotification({
        title: '注意',
        message: '审核通过',
        type: 'success'
      })
    } else {
      // 驳回
      await packageRejectRefund({
        recordId: refundRow.value.id,
        orderNo: refundRow.value.orderNo,
        reason: form.reason
      })
      ElNotification({
        title: '注意',
        message: '审核驳回',
        type: 'success'
      })
    }
    getData()
  } catch (error) {
    console.log(error);
  }
  tableData.loading = false
}

// 显示审核退款弹窗
const refundRow = ref(null)
async function refundPopupHandle(row) {
  refundRow.value = row
  refundDialogRef.value.show()
}

// 核销操作
async function checkoutHandle(row) {
  try {
    tableData.loading = true
    await packageCheckout({
      verifyCode: row.verifyCode
    })
    ElNotification({
      title: '注意',
      message: '已核销',
      type: 'success'
    })
    getData()
  } catch (error) {
    console.log(error);
  }
}

// 获取订单列表
async function getTableData() {
  try {
    tableData.loading = true
    const res = await packageOrder({
      ...queryForm,
      page: tableData.page,
      size: tableData.size
    })
    tableData.list = res.records
    tableData.total = res.totalRow
  } catch (error) {
    console.log(error);
  }
  setTimeout(() => {
    tableData.loading = false
  }, 300);
}

// 获取统计数据
async function packageOrderStatAjax() {
  try {
    const res = await packageOrderStat({
      ...queryForm,
    })
    infoObj.countNum = res.countNum
    infoObj.paidAmountTotal = res.paidAmountTotal
    infoObj.refundAmount = res.refundAmount
  } catch (error) {
    console.log(error);
  }
}

// 统一获取数据
function getData() {
  getTableData()
  packageOrderStatAjax()
}

onMounted(() => {
  getData()
})
</script>

<style scoped lang="scss">
.row {
  &.mt14 {
    margin-top: 14px;
  }
}

.center {
  display: flex;
  gap: 10px;
}

.info_wrap {
  display: flex;
  gap: 48px;

  .item {
    display: flex;
    align-items: center;
    border: 1px solid #D9D9D9;
    border-radius: 8px;
    padding: 0 10px;

    .icon {
      width: 44px;
      height: 44px;

      .img {
        width: 100%;
        height: 100%;
      }
    }

    .info {
      flex: 1;
      padding: 10px;
    }
  }
}
</style>