<template>
  <div>
    <v-tabs v-model="tab" align-tabs="start" color="primary" :bg-color="props.tabListBg ? '#f7f8fa': '#fff'" @update:modelValue="queryParams.pageNo = 1, getOrderPage()">
      <v-tab v-for="(val, i) in tabList" :key="i" :value="val.value">{{ val.title }}</v-tab>
    </v-tabs>
    <div v-if="orderList.length" class="mt-3">
      <div v-for="val in orderList" :key="val.id" class="order-item mb-3">
        <div class="order-item-header px-5">
          <div style="width: 40%;">
            <span>订单号：{{ val.no }}</span>
            <span class="ml-5">{{ timesTampChange(val.createTime) }}</span>
          </div>
          <div class="text-end color-warning" :class="formatOrderColor(val)" style="flex: 1">
            {{ formatOrderStatus(val) }}
          </div>
        </div>
        <!-- 商品列表 -->
        <GoodsItem v-for="k in val.items" :key="k.id" :item="k" />
        <!-- 操作按钮 -->
        <div class="text-end pa-3 font-size-13 color-666">
          <div>共{{ val.productCount }}件商品，合计：￥{{ fen2yuan(val.payPrice) }}</div>
          <v-btn class="mt-2" variant="tonal" rounded="xl" @click.stop="handleDetail(val)">查看详情</v-btn>
          <v-btn v-if="val.buttons.includes('confirm')" class="mt-2 ml-3" variant="tonal" color="success" rounded="xl" @click.stop="handleConfirm(val)">确认收货</v-btn>
          <!-- <v-btn v-if="val.buttons.includes('comment')" class="mt-2" variant="tonal" rounded="xl" @click.stop="handleComment(val)">评价</v-btn> -->
          <!-- <v-btn v-if="val.buttons.includes('express')" class="mt-2" variant="tonal" rounded="xl">查看物流</v-btn> -->
          <v-btn v-if="val.buttons.includes('cancel')" class="mt-2 ml-3" variant="tonal" rounded="xl" @click.stop="handleCancel(val)">取消订单</v-btn>
          <v-btn v-if="val.buttons.includes('delete')" class="mt-2 ml-3" variant="tonal" color="error" rounded="xl" @click.stop="handleDelete(val)">删除订单</v-btn>
          <v-btn v-if="val.buttons.includes('pay')" class="mt-2 ml-3" variant="tonal" color="primary" rounded="xl" @click.stop="handlePay(val)">继续支付</v-btn>
        </div>
      </div>
      <CtPagination :total="total" :page="queryParams.pageNo" :limit="queryParams.pageSize" @handleChange="handleChangePage"></CtPagination>
    </div>
    <Empty v-else :elevation="false" :message="tab === -1 ? '暂无订单' : '暂无' + tabList.find(e => e.value === tab).title + '订单'"></Empty>
  </div>

  <!-- <CtDialog :visible="showDialog" titleClass="text-h6" :footer="true" :widthType="3" title="商品评论" @submit="handleSubmit" @close="handleClose">
    <CommentForm ref="commentFormRef" v-if="showDialog" :orderId="commentOrderId" />
  </CtDialog> -->
  <!-- 支付 -->
  <CtDialog :visible="showPay" titleClass="text-h6" :widthType="3" title="收银台" :footer="false" @close="payCancel">
    <pay ref="payRef" :id="payOrderId" @paySuccess="paySuccess"></pay>
  </CtDialog>
</template>

<script setup>
defineOptions({ name: 'mall-user-order-index'})
import { ref } from 'vue'
import { getMallOrderPage, receiveOrder, deleteTradeOrder, cancelTradeOrder, createOrderItemComment } from '@/api/mall/user'
import { timesTampChange } from '@/utils/date'
import { fen2yuan, handleOrderButtons, formatOrderStatus, formatOrderColor } from '@/hooks/web/useGoods'
import Confirm from '@/plugins/confirm'
import Snackbar from '@/plugins/snackbar'
import GoodsItem from '../../components/GoodsItem/index.vue'
import CommentForm from './commentForm.vue'
import pay from '@/views/mall/components/details/order/pay.vue'
import { useRoute } from 'vue-router'; const route = useRoute()
import { useRouter } from 'vue-router'; const router = useRouter()

const props = defineProps({
  tabListBg: {
    type: Boolean,
    default: true
  },
})

const tab = ref(route?.query?.tab ? (route.query.tab)-0 : -1)
const tabList = [
  { title: '全部', value: -1 },
  { title: '待付款', value: 0 },
  { title: '待发货', value: 10 },
  { title: '待收货', value: 20 },
  { title: '已完成', value: 30 },
  { title: '已取消', value: 40 },
  // { title: '待评价', value: 30 }
]
const total = ref(0)
const queryParams = ref({
  pageNo: 1,
  pageSize: 10
})

// 获取订单列表
const orderList = ref([])
const getOrderPage = async () => {
  queryParams.value.status = tab.value
  if (tab.value === -1) delete queryParams.value.status
  if (tab.value === 30) queryParams.value.commentStatus = false

  const result = await getMallOrderPage(queryParams.value)

  result.list.forEach(order => handleOrderButtons(order))
  orderList.value = result.list
  total.value = result.total
}
getOrderPage()

// 分页
const handleChangePage = (e) => {
  queryParams.value.pageNo = e
  getOrderPage()
}

// 查看详情
const handleDetail = ({ id }) => {
  window.open(`/mall/user/order/detail/${id}`)
}

// 删除订单
const handleDelete = async ({ id }) => {
  Confirm('系统提示', '是否确认删除该订单？').then(async () => {
    await deleteTradeOrder(id)
    Snackbar.success('删除成功')
    await getOrderPage()
  })
}

// 取消订单
const handleCancel = async ({ id }) => {
  Confirm('系统提示', '是否确认取消该订单？').then(async () => {
    await cancelTradeOrder(id)
    Snackbar.success('取消成功')
    await getOrderPage()
  })
}

// 商品评论
// const showDialog = ref(false)
// const commentOrderId = ref(null) // 订单id
// const commentFormRef = ref()
// const handleComment = (val) => {
//   commentOrderId.value = val.id
//   showDialog.value = true
// }
// const handleClose = () => {
//   commentOrderId.value = null
//   showDialog.value = false
// }
// const handleSubmit = async () => {
//   const commentList = commentFormRef.value.commentList
//   for (const comment of commentList) {
//     await createOrderItemComment(comment)
//   }
//   Snackbar.success('评论成功')
//   handleClose()
//   getOrderPage()
// }

// // 收货成功后提示去评论
// const handlePromptComment = (id) => {
//   Confirm('确认收货成功', '是否前往评价？', { sureText: '立即评价', cancelText: '关闭' }).then(() => {
//     handleComment({ id })
//   })
// }

// 确认收货
const handleConfirm = ({ id }) => {
  if (!id) return
  Confirm('系统提示', '是否确认收货？').then(async () => {
    await receiveOrder(id)
    Snackbar.success('收货成功')
    queryParams.value.pageNo = 1
    await getOrderPage()
    handlePromptComment(id) // 收货成功后提示去评论
  })
}

const showPay = ref(false)
const payOrderId  = ref('')
const handlePay = (val) => {
  if (!payOrderId) return Snackbar.success('订单错误！')
  payOrderId.value = val.payOrderId
  showPay.value = true
}
// 
const payCancel = () => {
  Snackbar.warning('您已取消支付！')
  showPay.value = false
  // router.push({ path: '/mall/user/order', query: { tab: 0 } })
}
const paySuccess = (e) => {
  // Snackbar.success('支付成功！')
  // showPay.value = false
  // getOrderPage()
  router.push({ path: '/mall/payOver', query: { price: e.price }})
}

</script>

<style scoped lang="scss">
.order-item {
  border: 1px solid #dbdbdb;
  &-header {
    display: flex;
    background-color: #f2f4f7;
    height: 36px;
    line-height: 36px;
    font-size: 13px;
    color: #666;
  }
}
</style>
