<template>
  <div>
    <div class="row">
      <el-form :mode="queryForm" inline>
        <el-form-item label="商品类型">
          <el-select v-model="queryForm.goodsCategory" style="width: 150px;">
            <el-option label="优惠券" value="优惠券"></el-option>
            <el-option label="其它商品" value="其它商品"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="queryForm.status" style="width: 150px;">
            <el-option v-for="item in statusList" :key="item.label" :label="item.label" :value="item.label"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="搜索">
          <el-input v-model="queryForm.pointsGoodsName" placeholder="搜索关键词"></el-input>
        </el-form-item>
        <el-form-item>
          <el-date-picker v-model="time" type="daterange" range-separator="至" start-placeholder="开始时间"
            end-placeholder="结束时间" @change="timeChange" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :loading="tableData.loading" icon="Search" @click="searchHandle">搜索</el-button>
          <el-button :loading="tableData.loading" icon="Refresh" @click="resetHandle">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="row">
      <div class="total_info">
        <div class="item">
          <img class="icon" src="@/assets/applocation/dds.png">
          <div class="info">
            <span class="t1">总订单数</span>
            <span class="t2">{{ totalInfo.count }}</span>
          </div>
        </div>
        <div class="item">
          <img class="icon" src="@/assets/applocation/ddje.png">
          <div class="info">
            <span class="t1">已支付金额（元）</span>
            <span class="t2">¥ {{ multiplyAndFormat(totalInfo.totalAmount) }}</span>
          </div>
        </div>
      </div>
    </div>
    <div class="row mt14">
      <el-table :data="tableData.list" border stripe v-loading="tableData.loading">
        <el-table-column label="订单号" prop="orderNo" width="200"></el-table-column>
        <el-table-column label="用户" prop="orderNo" width="200">
          <template v-slot="scope">
            <div class="column">
              <span class="t1">{{ scope.row.nickName }}</span>
              <span class="t2">{{ scope.row.phone }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="商品" prop="pointsGoodsName" width="200">
          <template v-slot="scope">
            <div class="goods_info" v-if="includesString(scope.row.goodsCategory, '其它商品')">
              <el-image class="icon" :src="scope.row.goodsImageUrl" fit="cover"></el-image>
              <div class="info">
                <div class="name">{{ scope.row.pointsGoodsName }}</div>
              </div>
            </div>
            <div class="coupon_info" v-if="includesString(scope.row.goodsCategory, '优惠券')">
              <div class="icon">
                <CouponIcon :item="scope.row.couponInfo" />
              </div>
              <div class="info">
                <div class="name">
                  {{ scope.row.pointsGoodsName }}
                </div>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="商品类型" prop="goodsCategory"></el-table-column>
        <el-table-column label="消耗积分" prop="spendPoints"></el-table-column>
        <el-table-column label="支付金额" prop="extraPaymentAmount"></el-table-column>
        <el-table-column label="状态" prop="status" width="100">
          <template v-slot="scope">
            <el-tag :type="statusFilter(scope.row.status).type" disable-transitions>
              {{ statusFilter(scope.row.status).label }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="下单时间" prop="createTime"></el-table-column>
        <el-table-column label="兑换码" prop="couponCode"></el-table-column>
        <el-table-column label="核销时间" prop="checkoutTime"></el-table-column>
        <el-table-column label="操作" width="120" fixed="right">
          <template v-slot="scope">
            <el-button link type="primary" @click="goodsRecordCheckoutHandle(scope.row)"
              v-if="includesString(scope.row.status, '待核销')">核销</el-button>
            <el-button link type="danger" @click="returnCostHandle(scope.row)"
              v-if="includesString(scope.row.status, '退款中')">审核</el-button>
          </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, 30, 50, 100]" background layout="total, sizes, prev, pager, next, jumper"
        :total="tableData.total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
    </div>
    <el-dialog title="退款" width="600px" v-model="returnVisable">
      <el-form :model="returnForm" label-width="150" label-position="left">
        <el-form-item label="是否同意">
          <el-radio-group v-model="returnForm.type">
            <el-radio label="同意" :value="1"></el-radio>
            <el-radio label="驳回" :value="0"></el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="驳回原因" v-if="returnForm.type === 0">
          <el-input type="textarea" v-model="returnForm.reason" placeholder="请输入驳回原因"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="returnVisable = false">取消</el-button>
          <el-button type="primary" @click="returnCostConfirmHandle" :loading="returnLoading">同意</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import dayjs from 'dayjs'
import { ref, reactive, onMounted } from 'vue'
import { goodsRecordPage, goodsRecordTotal, goodsRecordCheckout, goodsRecordAgreeRefund, goodsRecordRejectRefund } from '@/api/points'
import CouponIcon from './coupon-icon.vue';
import { includesString, multiplyAndFormat } from '@/utils'
import { ElMessageBox } from 'element-plus'

const time = ref([])
const queryForm = reactive({
  startTime: '',
  endTime: '',
  pointsGoodsName: '',
  goodsCategory: '', // 商品类型 优惠券 其它商品
  receiveType: '', // 领取方式 店内自取、系统发放
  status: ''
})

function timeChange(e) {
  if (e && e.length) {
    queryForm.startTime = dayjs(e[0]).format("YYYY-MM-DD 00:00:00");
    queryForm.endTime = dayjs(e[1]).format("YYYY-MM-DD 23:59:59");
  } else {
    queryForm.startTime = "";
    queryForm.endTime = "";
  }
}

const statusList = ref([
  {
    label: '待支付',
    type: 'info'
  },
  {
    label: '待核销',
    type: 'primary'
  },
  {
    label: '已完成',
    type: 'success'
  },
  {
    label: '退款中',
    type: 'warning'
  },
  {
    label: '已退款',
    type: 'info'
  },
])

function statusFilter(status) {
  const obj = statusList.value.find(item => item.label == status)
  if (obj) {
    return obj
  } else {
    return {
      label: status,
      type: 'info'
    }
  }
}

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

const totalInfo = reactive({
  count: 0,
  totalAmount: 0
})

function searchHandle() {
  tableData.page = 1
  goodsRecordPageAjax();
  goodsRecordTotalAjax()
}

function resetHandle() {
  time.value = []
  queryForm.startTime = ''
  queryForm.endTime = ''
  queryForm.pointsGoodsName = ''
  queryForm.goodsCategory = ''
  queryForm.receiveType = ''
  queryForm.status = ''

  goodsRecordPageAjax();
  goodsRecordTotalAjax()
}

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

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

// 积分:积分商品:兑换统计
async function goodsRecordTotalAjax() {
  try {
    const res = await goodsRecordTotal({
      ...queryForm,
      page: tableData.page,
      size: tableData.size
    })
    totalInfo.count = res.count || 0
    totalInfo.totalAmount = res.totalAmount || 0
  } catch (error) {
    console.log(error);
  }
}

// 积分:积分商品:兑换记录
async function goodsRecordPageAjax() {
  try {
    tableData.loading = true
    const res = await goodsRecordPage({
      ...queryForm,
      page: tableData.page,
      size: tableData.size
    })
    tableData.list = res.records
    tableData.total = res.totalRow
  } catch (error) {
    console.log(error);
  }
  setTimeout(() => {
    tableData.loading = false
  }, 500);
}

// 核销
function goodsRecordCheckoutHandle(row) {
  ElMessageBox.confirm('确认要核销吗？').then(async () => {
    try {
      await goodsRecordCheckout(row.couponCode)
      ElNotification({
        title: '注意',
        message: '核销成功',
        type: 'success'
      })
      goodsRecordPageAjax()
    } catch (error) {
      console.log(error);
    }
  }).catch(() => {

  })
}

// 退款操作
const returnVisable = ref(false)
const returnLoading = ref(false)
const returnForm = ref({
  type: 1,
  recordId: '',
  orderNo: '',
  reason: '',
})
function returnCostHandle(row) {
  returnForm.value.recordId = row.id
  returnForm.value.orderNo = row.orderNo
  returnVisable.value = true
}

// 退款操作
async function returnCostConfirmHandle() {
  try {
    returnLoading.value = true
    if (returnForm.value.type == 1) {
      // 同意
      await goodsRecordAgreeRefund(returnForm.value)
    } else {
      // 驳回
      await goodsRecordRejectRefund(returnForm.value)
    }
    returnVisable.value = false
    ElNotification({
      title: '注意',
      message: '操作成功',
      type: 'success'
    })
    goodsRecordPageAjax()
  } catch (error) {
    console.log(error);
  }
  setTimeout(() => {
    returnLoading.value = false
  }, 500);
}

onMounted(() => {
  goodsRecordPageAjax()
  goodsRecordTotalAjax()
})
</script>

<style scoped lang="scss">
.goods_info,
.coupon_info {
  display: flex;
  align-items: center;
  gap: 14px;

  .icon {
    $size: 70px;
    width: $size;
    height: $size;
    display: flex;
    align-items: center;
    justify-content: center;
    border: 1px solid #ececec;
    border-radius: 8px;
  }

  .info {
    display: flex;
    align-items: center;

    .name {
      font-size: 14px;
      color: #666;
    }
  }
}

.row {
  &.mt14 {
    margin-top: 14px;
  }
}

.column {
  display: flex;
  flex-direction: column;

  .t1 {
    font-size: 14px;
    color: #333;
  }

  .t2 {
    font-size: 14px;
    color: #666;
  }
}

.total_info {
  display: flex;
  gap: 14px;

  .item {
    display: flex;
    align-items: center;
    gap: 10px;
    padding: 14px;
    background-color: #fff;
    border: 1px solid #ececec;
    border-radius: 8px;

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

    .info {
      display: flex;
      gap: 4px;
      flex-direction: column;

      .t1 {
        font-size: 14px;
        color: #666;
      }

      .t2 {
        color: #333;
        font-size: 16px;
      }
    }
  }
}
</style>