<template>
  <div class="order-list__box">
    <div class="tabs-content">
      <a-tabs v-model:activeKey="mainData.tabIndex" @change="changeTab">
        <a-tab-pane v-for="(item, index) in mainData.tabs" :key="index" :tab="item.name" />
      </a-tabs>
    </div>
    <div v-if="mainData.list.length > 0" class="list-container">
      <div v-for="(item, index) in mainData.list" :key="index">
        <div class="item" @click="toOrderDetail(item.orderId, item.orderRefundId)">
          <!-- 普通订单 -->
          <div v-if="tabCurrent != 'REFUND'">
            <div class="top">
              <div class="left">{{ item.orderId }}</div>
              <div class="right">{{ statusFilter(item) }}</div>
            </div>

            <div v-for="(goodsItem, goodsIndex) in item.orderDetails" :key="goodsIndex">
              <div class="goods" :class="'goods' + goodsIndex">
                <img :src="goodsItem.imgUrl" />
                <div class="main">
                  <div class="left">
                    <div class="name ellipsis-2">{{ goodsItem.goodsName }}</div>
                    <div class="des">{{ goodsItem.goodsSpecValue }}</div>
                  </div>
                  <div class="right">
                    <div class="price">¥{{ formatPriceText(goodsItem.price) }}</div>
                    <div class="num">x{{ goodsItem.num }}</div>
                  </div>
                </div>
              </div>
            </div>

            <div class="total">
              <div class="left">{{ item.createTime }}</div>
              <div class="right">共{{ item.totalNum }}件 订单总额:<span>¥{{ formatPriceText(item.payAmount) }}</span></div>
            </div>
          </div>

          <!-- 售后订单 -->
          <div v-if="tabCurrent == 'REFUND'">
            <div class="top">
              <div class="left">{{ item.orderId }}</div>
              <div class="right">{{ statusFilter2(item.orderStatus) }}</div>
            </div>

            <!-- 拒绝申请 -->
            <div v-if="item.examineStatus === 'FAIL'">
              <div v-for="(goodsItem, goodsIndex) in item.orderDetails" :key="goodsIndex">
                <div class="goods" :class="'goods' + goodsIndex">
                  <image :src="goodsItem.imgUrl" mode="aspectFill"></image>
                  <div class="main">
                    <div class="left">
                      <div class="name ellipsis-2">{{ goodsItem.goodsName }}</div>
                      <div class="des">{{ goodsItem.goodsSpecValue }}</div>
                    </div>
                    <div class="right">
                      <div class="price">¥{{ formatPriceText(goodsItem.price) }}</div>
                      <div class="num">x{{ goodsItem.refundNum }}</div>
                    </div>
                  </div>
                </div>
              </div>
              <div class="total">
                <div class="left">{{ item.createTime }}</div>
                <div class="right">共{{ item.totalNum }}件 {{ item.orderStatus == 'NOPAY' ? '应付' : '实付' }}总额:<span>¥{{
                  formatPriceText(item.payAmount) }}</span></div>
              </div>
            </div>
            <!-- 其他 -->
            <div v-else>
              <div v-for="(goodsItem, goodsIndex) in item.orderDetails" :key="goodsIndex">
                <div class="goods" :class="'goods' + goodsIndex" v-if="goodsItem.refund">
                  <image :src="goodsItem.imgUrl" mode="aspectFill"></image>
                  <div class="main">
                    <div class="left">
                      <div class="name ellipsis-2">{{ goodsItem.goodsName }}</div>
                      <div class="des">{{ goodsItem.goodsSpecValue }}</div>
                    </div>
                    <div class="right">
                      <div class="price">¥{{ formatPriceText(goodsItem.price) }}</div>
                      <div class="num">x{{ goodsItem.refundNum }}</div>
                    </div>
                  </div>
                </div>
              </div>
              <div class="total">
                <div class="left">{{ item.createTime }}</div>
                <div class="right">共{{ getRefundNum(item.orderDetails) }}件
                  {{ item.orderStatus == 'OVER' ? '实退' : '应退' }}总额:<span>¥{{ formatPriceText(item.refundAmount)
                    }}</span>
                </div>
              </div>
            </div>
          </div>

          <div v-if="item.isShareOrder">
            <div class="btn-group btn-group2">
              <div class="tips">分销订单</div>
              <div class="btns">
                <div class="button gray">查看订单</div>
              </div>
            </div>
          </div>
          <div v-else>
            <!-- 按钮：待付款 -->
            <div class="btn-group btn-group2" v-if="item.orderStatus == 'NOPAY'">
              <div class="tips">请在30分钟内付款</div>
              <div class="btns">
                <div class="button red">立即付款</div>
              </div>
            </div>
            <!-- 按钮：待发货 -->
            <!-- <div class="btn-group" v-if="item.orderStatus == 'DFH'">
            </div> -->
            <!-- 按钮：待服务 -->
            <!-- <div class="btn-group" v-if="item.orderStatus == 'YFH'">
            </div> -->
            <!-- 按钮：待评价 -->
            <!-- <div class="btn-group" v-if="item.orderStatus == 'OVER' && tabCurrent != 'REFUND'">
            </div> -->
            <!-- 按钮：超时未支付 -->
            <div class="btn-group" v-if="item.orderStatus == 'TIMEOUT'">
              <div class="button gray">查看订单</div>
            </div>
            <!-- 按钮：售后中 -->
            <div class="btn-group" v-if="item.orderStatus == 'REFUND'">
              <div class="button gray">查看订单</div>
            </div>
            <!-- 按钮：售后中 待商家处理 -->
            <div class="btn-group" v-if="item.orderStatus == 'DSJCL'">
              <div class="button gray" @click="toReturnDetail(item.orderRefundId)">售后详情</div>
            </div>
            <!-- 按钮：售后中 待买家处理 -->
            <div class="btn-group" v-if="item.orderStatus == 'DMJCL'">
              <div class="button red" @click="toReturnDetail(item.orderRefundId)" v-if="item.examineStatus == 'OK'">
                提交资料
              </div>
              <div class="button white" @click="toApplyReturn(item.orderId)" v-if="item.examineStatus == 'FAIL'">
                重新申请
              </div>
            </div>
          </div>
        </div>
      </div>
      <a-flex v-if="mainData.total > mainData.list.length" align="center" justify="center">
        <a-button type="link" @click="handleLoadMore">点击查看更多订单</a-button>
      </a-flex>
    </div>
    <div v-else class="list-container">
      <a-empty />
    </div>
  </div>
</template>

<script setup lang="js">
import { onMounted, reactive, computed } from 'vue';
import { message, Modal } from 'ant-design-vue';
import {
  cancelOrder,
  ackComplete,
  remindNotice,
  getMyOrderList
} from '@/api/order';
import { useUserStore } from '@/store/user';

const props = defineProps({
  type: {
    type: String,
    default: ''
  }
})

const emits = defineEmits(['view-detail']);

const userStore = useUserStore();

const tabCurrent = computed(() => mainData.tabs[mainData.tabIndex].key);

const mainData = reactive({
  tabs: [
    { key: '', name: '全部' },
    { key: 'NOPAY', name: '待付款' },
    { key: 'DQR', name: '待确认' },
    { key: 'DJH', name: '待拣货' },
    { key: 'JHZ', name: '拣货中' },
    { key: 'DFH', name: '待发货' },
    { key: 'DPS', name: '待配送' },
    { key: 'PSDQ', name: '配送待取' },
    { key: 'PSZ', name: '配送中' },
    { key: 'OVER', name: '已完成' },
    { key: 'CLOSE', name: '已关闭' }
  ],
  tabIndex: 0,
  list: [],
  pageNo: 1,
  total: 0,
  canRemindShipment: true
})

const statusFilter = item => {
  const statusMap = {
    DQR: '待确认',
    NOPAY: '待付款',
    DJH: '待拣货',
    JHZ: '拣货中',
    DFH: '待发货',
    DTK: '待退款',
    DPS: '待配送',
    PSZ: '配送中',
    OVER: '已完成',
    CLOSE: '已关闭',
    REFUND: '售后/退款',
    TIMEOUT: '超时未支付'
  }
  if (item.orderStatus == 'OVER' && item.commentService) {
    return '已完成'
  } else {
    return statusMap[item.orderStatus]
  }
}

const statusFilter2 = (val) => {
  const statusMap = {
    DSJCL: '待商家处理',
    DSJSH: '待商家收货',
    DMJCL: '待买家处理',
    OVER: '退款成功',
    CANCEL: '已取消'
  }
  return statusMap[val]
}

const getRefundNum = (orderDetails) => {
  let refundNum = 0
  orderDetails.forEach(item => {
    if (item.refund) {
      refundNum = refundNum + item.refundNum
    }
  })
  return refundNum
}

const changeTab = tabIndex => {
  mainData.tabIndex = tabIndex;
  resetParams();
  fetchOrderList();
}

const resetParams = () => {
  mainData.list = []
  mainData.pageNo = 1
  mainData.total = 0
}

const fetchOrderList = async () => {
  const orderStatus = mainData.tabs[mainData.tabIndex].key || ''
  const res = await getMyOrderList({
    pageNo: mainData.pageNo,
    pageSize: 10,
    orderStatus: orderStatus,
    userId: userStore.userInfo?.userId || ''
  })
  mainData.list = mainData.list.concat(res.data?.records || []);
  mainData.total = res.data?.total || 0;
}

const handleLoadMore = () => {
  mainData.pageNo += 1;
  fetchOrderList();
}


// 申请退款
const toApplyReturn = (orderId) => {
  // url: '/packageMine/pages/order/return/apply?orderId=' + orderId
}

// 去订单详情
const toOrderDetail = (orderId = '', orderRefundId = '') => {
  emits('view-detail', { orderId, orderRefundId })
}

// 去售后详情
const toReturnDetail = (orderRefundId) => {
  // this.$navToPage({
  //   url: '/packageMine/pages/order/return/detail?orderRefundId=' + orderRefundId
  // })
}

// 提醒发货
const remindShipment = (orderId) => {
  mainData.canRemindShipment = false
  setTimeout(() => {
    mainData.canRemindShipment = true
  }, 3000)
  remindNotice({
    orderId: orderId,
    userId: userStore.userInfo?.userId || ''
  }).then(() => {
    message.success('提醒发货成功')
  })
}

// 取消订单
const handleCancelOrder = orderId => {
  cancelOrder({
    orderId: orderId
  }).then(() => {
    resetParams()
    fetchOrderList()
    message.success('取消成功')
  })
}

// 服务完成
const confirmReceipt = orderId => {
  Modal.confirm({
    title: '完成服务',
    content: '请确认是否已完成服务？',
    onOk() {
      ackComplete({
        orderId: orderId
      }).then(() => {
        message.success('完成服务成功')
      })
    }
  })
}

const formatPriceText = price => {
  if (!price) return '0.00'
  price = Number(price)
  return price.toFixed(2)
}

onMounted(() => {
  mainData.tabIndex = mainData.tabs.findIndex(item => item.key === props.type);
  if (mainData.tabIndex < 0) {
    mainData.tabIndex = 0;
  }
  fetchOrderList()
})

</script>

<style lang="less" scoped>
.order-list__box {
  .tab-container {
    background: #ffffff;
  }

  .list-container {
    .item {
      padding-bottom: 10px;
      border-bottom: 1px solid @border-color;

      .top {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 10px 0;

        .left {
          font-size: 14px;
          font-weight: 500;
        }

        .right {
          font-size: 14px;
        }
      }

      .goods {
        display: flex;
        justify-content: space-between;
        margin-top: 10px;
        img {
          width: 70px;
          height: 70px;
          object-fit: cover;
        }

        &.goods0 {
          margin-top: 0;
        }

        image {
          width: 70px;
          height: 70px;
          display: div;
          flex-shrink: 0;
          margin-right: 10px;
        }

        .main {
          margin-left: 10px;
          flex: 1;
          display: flex;
          justify-content: space-between;

          .left {
            .name {
              font-size: 14px;
              color: #333333;
              line-height: 18px;
            }

            .des {
              font-size: 14px;
              color: #999999;
              margin-top: 5px;
            }
          }

          .right {
            flex-shrink: 0;
            margin-left: 10px;
            text-align: right;

            .price {
              font-size: 14px;
              color: #333333;
              line-height: 14px;
              font-weight: 600;
              margin-top: 3;
            }

            .num {
              font-size: 14px;
              color: #999999;
              line-height: 14px;
              margin-top: 8px;
            }
          }
        }
      }

      .total {
        display: flex;
        justify-content: space-between;
        height: 25px;
        align-items: center;

        .left {
          font-size: 12px;
          color: #666666;
        }

        .right {
          font-size: 12;
          color: #666666;

          text {
            color: #ff577e;
            ;
            font-size: 16px;
            font-weight: 600;
            margin-left: 4px;
          }
        }
      }

      .btn-group {
        border-top: 1px solid #eaeaea;
        height: 50px;
        display: flex;
        justify-content: flex-end;
        align-items: center;

        &.btn-group2 {
          justify-content: space-between;

          .tips {
            font-size: 14px;
            color: #ff577e;
          }

          .btns {
            display: flex;
          }
        }

        .button {
          width: 70px;
          height: 24px;
          border-radius: 24px;
          text-align: center;
          line-height: 24px;
          font-size: 12px;
          margin-left: 10px;
          flex-shrink: 0;

          &:first-child {
            margin-left: 0;
          }

          &.gray {
            color: #999999;
            border: 1px solid #999999;
          }

          &.white {
          }

          &.red {
          }
        }
      }
    }
  }
}
</style>
