<template>
  <zj-page-layout :hasFooter="true" :isScroll="true" :refresherTriggered="refresherTriggered"
    @refresherrefresh="refresherrefresh" @scrolltolower="scrolltolower">
    <template slot="header">
      <view class="tab-container">
        <u-tabs :scrollable="true" :list="tabList" :current="curTab" @click="changeTab" lineColor="#3D8FFD" :activeStyle="{
          color: '#3D8FFD'
        }" :inactiveStyle="{
  color: '#666666'
}" itemStyle="height: 88rpx;">
        </u-tabs>
      </view>
    </template>

    <view class="list-container">
      <block v-for="(item, index) in orderList" :key='index'>
        <view class="item" @tap="toOrderDetail(item.orderId, item.orderRefundId)">

          <!-- 普通订单 -->
          <block v-if="tabCurrent != 'REFUND'">
            <view class="top">
              <view class="left">{{ item.orderId }}</view>
              <view class="right">{{ statusFilter(item) }}</view>
            </view>

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

            <view class="total">
              <view class="left">{{ item.createTime }}</view>
              <view class="right">共{{ item.totalNum }}件 订单总额:<text>¥{{ item.payAmount | priceFilter }}</text></view>
            </view>
          </block>

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

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

          <block v-if="item.isShareOrder">
            <view class="btn-group btn-group2">
              <view class="tips">分销订单</view>
              <view class="btns">
                <view class="button gray">查看订单</view>
              </view>
            </view>
          </block>
          <block v-else>
            <!-- 按钮：待确认 -->
            <view class="btn-group" v-if="item.orderStatus == 'DQR'">
              <view class="button gray">查看订单</view>
            </view>
            <!-- 按钮：待付款 -->
            <view class="btn-group btn-group2" v-if="item.orderStatus == 'NOPAY'">
              <view class="tips">请在30分钟内付款</view>
              <view class="btns">
                <!-- <view class="button gray" @tap.stop="cancelOrder(item.orderId)">取消订单</view> -->
                <view class="button white" v-if="!item.isChangeAddress" @tap.stop="navToPage(`/packageMine/pages/order/changeAddress?orderId=${item.orderId}`)">修改地址</view>
                <view class="button red" @tap.stop="payOrder(item.orderId)">立即付款</view>
              </view>
            </view>
            <!-- 按钮：待发货 -->
            <view class="btn-group" v-if="item.orderStatus == 'DFH'">
              <view class="button white" v-if="!item.isChangeAddress" @tap.stop="navToPage(`/packageMine/pages/order/changeAddress?orderId=${item.orderId}`)">修改地址</view>
              <view class="button white" @tap.stop="remindShipment(item.orderId)">提醒发货</view>
              <view class="button white" v-if="checkCanReturn(item)" @tap.stop="toApplyReturn(item.orderId)">申请售后</view>
            </view>
            <!-- 按钮：待服务 -->
            <view class="btn-group" v-if="item.orderStatus == 'YFH'">
              <!-- <view class="button gray" @tap.stop="toLogistics(item.companyCode, item.logisticsNo)">查看物流</view> -->
              <view class="button white" v-if="!item.isChangeAddress" @tap.stop="navToPage(`/packageMine/pages/order/changeAddress?orderId=${item.orderId}`)">修改地址</view>
              <view class="button red" @tap.stop="confirmReceipt(item.orderId)">服务完成</view>
              <view class="button white" v-if="checkCanReturn(item)" @tap.stop="toApplyReturn(item.orderId)">申请售后</view>
            </view>
            <!-- 按钮：待评价 -->
            <view class="btn-group" v-if="item.orderStatus == 'OVER' && tabCurrent != 'REFUND'">
              <view class="button gray" v-if="item.orderTaxId" @tap.stop="toInvoiceDetail(item.orderTaxId)">查看发票</view>
              <view class="button white" v-else @tap.stop="toInvoiceForm(item.orderId)">开发票</view>
              <!-- <view class="button gray" @tap.stop="toLogistics(item.companyCode, item.logisticsNo)">查看物流</view> -->
              <view class="button gray" @tap.stop="navToPage('/packageWorkorder/pages/userWorkorderList')">服务详情</view>
              <view class="button white" v-if="checkCanReturn(item)" @tap.stop="toApplyReturn(item.orderId)">申请售后</view>
              <view class="button red" v-if="!item.commentService" @tap.stop="navToPage(`/packageMine/pages/order/evaluate?orderId=${item.orderId}`)">评价</view>
            </view>
            <!-- 按钮：已关闭 -->
            <view class="btn-group" v-if="item.orderStatus == 'CLOSE'">
              <view class="button gray">查看订单</view>
            </view>
            <!-- 按钮：超时未支付 -->
            <view class="btn-group" v-if="item.orderStatus == 'TIMEOUT'">
              <view class="button gray">查看订单</view>
            </view>
            <!-- 按钮：售后中 -->
            <view class="btn-group" v-if="item.orderStatus == 'REFUND'">
              <view class="button gray">查看订单</view>
            </view>
            <!-- 按钮：售后中 待商家处理 -->
            <view class="btn-group" v-if="item.orderStatus == 'DSJCL'">
              <view class="button gray" @tap.stop="toReturnDetail(item.orderRefundId)">售后详情</view>
            </view>
            <!-- 按钮：售后中 待买家处理 -->
            <view class="btn-group" v-if="item.orderStatus == 'DMJCL'">
              <view class="button red" @tap.stop="toReturnDetail(item.orderRefundId)" v-if="item.examineStatus == 'OK'">提交资料
              </view>
              <view class="button white" @tap.stop="toApplyReturn(item.orderId)" v-if="item.examineStatus == 'FAIL'">重新申请
              </view>
            </view>
            <!-- 按钮：售后中 待商家收货 -->
            <view class="btn-group" v-if="item.orderStatus == 'DSJSH'">
              <view class="button gray" @tap.stop="toReturnDetail(item.orderRefundId)">售后详情</view>
            </view>
            <!-- 按钮：售后中 退款成功 -->
            <view class="btn-group" v-if="item.orderStatus == 'OVER' && tabCurrent == 'REFUND'">
              <view class="button gray" @tap.stop="toReturnDetail(item.orderRefundId)">售后详情</view>
            </view>
          </block>

        </view>
      </block>
    </view>

    <Loading :loadStatus="loadStatus" :dataList="orderList" />
  </zj-page-layout>
</template>

<script>
import { weixinPay, mini_env } from '@/common/utils/util.js';

export default {
  filters: {
    statusFilter(val) {
      const statusMap = {
        DQR: '待确认',
        NOPAY: '待付款',
        DFH: '待发货',
        YFH: '待服务',
        OVER: '待评价',
        CLOSE: '已关闭',
        REFUND: '售后/退款',
        TIMEOUT: '超时未支付'
      }
      return statusMap[val]
    },
    statusFilter2(val) {
      const statusMap = {
        DSJCL: '待商家处理',
        DSJSH: '待商家收货',
        DMJCL: '待买家处理',
        OVER: '退款成功',
        CANCEL: '已取消',
      }
      return statusMap[val]
    },
  },
  data() {
    return {
      configInfo: {},
      tabList: [
        { key: '', name: '全部' },
        { key: 'NOPAY', name: '待付款' },
        { key: 'DFH', name: '待服务' },
        { key: 'YFH', name: '服务中' },
        { key: 'OVER', name: '待评价' },
        { key: 'REFUND', name: '售后/退款' },
      ],
      tabCurrent: '', // 当前tab状态
      orderList: [], // 订单列表
      loadStatus: 0,
      refresherTriggered: false, // 下拉刷新状态
      pageNum: 1,
      autoDetailId: null, // 自动跳转到详情页id
      canRemindShipment: true, // 能否点击提醒发货
    }
  },

  computed: {
    curTab() {
      return this.tabList.map(item => item.key).indexOf(this.tabCurrent) || 0;
    }
  },

  async onLoad({ tab, orderId }) {
    this.tabCurrent = tab;
    console.log(this.tabCurrent);
    if (orderId) {
      this.autoDetailId = orderId;
    }
    this.getOrderList();

    this.configInfo = await this.$getConfigInfo();

    this.crossPage.$on('refreshOrderList', (data) => {
      // if(data) {
      // 	this.tabCurrent = 'REFUND';
      // }
      this.refreshList();
    })
  },

  onUnload() {
    this.crossPage.$off('refreshOrderList');
  },

  methods: {
    getOrderList() {
      this.loadStatus = 1;
      let url = '';
      let orderStatus = '';
      if (this.tabCurrent == 'REFUND') {
        url = '/order/refund/list';
        orderStatus = '';
      } else {
        url = '/order/my/order';
        orderStatus = this.tabCurrent;
      }
      this.$api.get(url, {
        pageNo: this.pageNum,
        pageSize: 10,
        orderStatus: orderStatus,
        userId: this.$store.state.user.userId
      }).then(res => {
        this.loadStatus = 0;
        let list = res.data.records;
        if (list.length < 10) {
          this.loadStatus = 2;
        }
        this.orderList = this.orderList.concat(list);

        if (this.autoDetailId) {
          this.toOrderDetail(this.autoDetailId);
        }
      }).catch(() => {
        this.loadStatus = 2;
      }).finally(res => {
        this.refresherTriggered = false;
      })
    },

    statusFilter(item) {
      const statusMap = {
        DQR: '待确认',
        NOPAY: '待付款',
        DFH: '待发货',
        YFH: '待服务',
        OVER: '待评价',
        CLOSE: '已关闭',
        REFUND: '售后/退款',
        TIMEOUT: '超时未支付'
      }
      if (item.orderStatus == 'OVER' && item.commentService) {
        return '已完成';
      } else {
        return statusMap[item.orderStatus];
      }
    },

    // 滚动到底部
    scrolltolower(e) {
      if (this.loadStatus === 0) {
        this.pageNum++;
        this.getOrderList();
      }
    },

    // 触发下拉刷新
    async refresherrefresh(e) {
      this.refresherTriggered = true;
      this.refreshList();
    },

    refreshList() {
      this.orderList = [];
      this.pageNum = 1;
      this.getOrderList();
    },

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

    // 检查是否可以申请售后（根据orderShareStatus, payTypeId）
    checkCanReturn(item) {
      const hasRefund = item.orderDetails.some(o => o.refund);
      if (!item.orderShareStatus || item.orderShareStatus === 'OVER' || item.orderShareStatus === 'CANCEL' || item.payTypeId == 'STORE' || hasRefund) {
        return false;
      } else {
        return true;
      }
    },

    // 切换类型
    changeTab(item) {
      this.tabCurrent = item.key;
      this.refreshList();
    },

    // 申请退款
    toApplyReturn(orderId) {
      this.$navToPage({
        url: '/packageMine/pages/order/return/apply?orderId=' + orderId
      })
    },

    // 去订单详情
    toOrderDetail(orderId = '', orderRefundId = '') {
      this.autoDetailId = null;
      if (orderRefundId) {
        return this.$navToPage({
          url: '/packageMine/pages/order/return/detail?orderRefundId=' + orderRefundId
        })
      }
      this.$navToPage({
        url: '/packageMine/pages/order/detail?orderId=' + orderId + '&orderRefundId=' + orderRefundId
      })
    },

    // 取消订单
    cancelOrder(orderId) {
      this.$modal({
        content: '确定要取消订单吗？'
      }).then(() => {
        this.$api.post('/order/cancel', {
          orderId
        }).then(res => {
          this.refreshList();
          this.$successToast();
        })
      }).catch(() => { })
    },

    // 服务完成
    confirmReceipt(orderId) {
      this.$modal({
        content: '请确认是否已完成服务？'
      }).then(() => {
        this.$api.post('/order/ack', {
          orderId
        }).then(res => {
          this.refreshList();
          this.$successToast();
        })
      }).catch(() => { })
    },

    // 立即付款
    payOrder(orderId) {
      mini_env((bool) => {
        let that = this;
        this.$api.post('/order/wait/pay', {
          userId: this.$store.state.user.userId,
          orderId: orderId,
          ...(() => {
            if (bool) {
              return {
                miniPay: true,
                openId: this.$store.state.user.miniOpenId
              }
            }
            return {}
          })()
        }).then(res => {
          if (bool) {
            uniWebview.navigateTo({
              url: `/pages/pay/pay?${Object.entries({
                ...res.data,
                payPackage: res.data.payPackage.split("=")[0] || "",
                payPackageVal: res.data.payPackage.split("=")[1] || ""
              }).map(item => item.join("=")).join("&")}`
            })
          } else {
            weixinPay(res.data, function (res) {
              that.$successToast('支付成功');
              that.pageNum = 1;
              that.getOrderList();
              that.requestMessage();
            })
          }
        })
      })
    },

    // 消息推送
    requestMessage() {
      let that = this;
      uni.showModal({
        title: '温馨提示',
        content: '为更好的促进您与买家的交流，需要在您的订单成交时向您发送消息',
        confirmText: "同意",
        cancelText: "拒绝",
        success: function (res) {
          if (res.confirm) {
            let tmplIds = [that.configInfo.template];
            uni.requestSubscribeMessage({
              tmplIds: tmplIds,
              success(res) {
                let status = null;
                tmplIds.map((item, index) => {
                  if (res[item] == 'accept') {
                    status = 'accept';
                  }
                })
                if (status == 'accept') {
                  that.$successToast('订阅成功');
                } else {
                  that.$toast('订阅取消');
                }
              },
              fail(res) {
                console.log(res);
                that.$toast('订阅失败');
              }
            })
          } else if (res.cancel) {
            uni.showModal({
              title: '温馨提示',
              content: '拒绝后您将无法获取实时的与卖家（买家）的交易消息',
              confirmText: "知道了",
              showCancel: false,
              success: function (res) {

              }
            });
          }
        }
      });
    },

    // 开发票
    toInvoiceForm(orderId = '', orderRefundId = '') {
      this.navToPage('/packageMine/pages/invoice/form?orderType=ORDER&orderId=' + orderId + '&orderRefundId=' + orderRefundId);
    },

    // 发票详情
    toInvoiceDetail(orderTaxId = '') {
      this.navToPage('/packageMine/pages/invoice/detail?orderTaxId=' + orderTaxId);
    },

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

    // 去查看物流
    toLogistics(companyCode, logisticsNo) {
      this.$navToPage({
        url: '/packageMine/pages/order/logistics?companyCode=' + companyCode + '&logisticsNo=' + logisticsNo
      })
    },

    navToPage(url) {
      this.$navToPage({
        url
      })
    },

    // 提醒发货
    remindShipment(orderId) {
      if (!this.canRemindShipment) return this.$toast('请勿频繁操作');
      this.canRemindShipment = false;
      setTimeout(() => { this.canRemindShipment = true }, 3000)

      this.$api.post('/order/notice', {
        orderId: orderId,
        userId: this.$store.state.user.userId
      }).then(res => {
        this.$successToast('提醒发货成功');
      })
    },
  }
}
</script>

<style lang="scss">
.tab-container {
  background: #FFFFFF;
}

.list-container {
  padding: 1rpx 20rpx 0;

  .item {
    @include zj-card;
    margin-top: 20rpx;
    background: #FFFFFF;
    border-radius: 20rpx;
    padding: 0 20rpx;

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

      .left {
        font-size: 28rpx;
        font-weight: 500;
      }

      .right {
        font-size: 28rpx;
        color: $reg-font;
      }
    }

    .goods {
      display: flex;
      justify-content: space-between;
      margin-top: 20rpx;

      &.goods0 {
        margin-top: 0;
      }

      image {
        width: 140rpx;
        height: 140rpx;
        display: block;
        flex-shrink: 0;
        margin-right: 20rpx;
      }

      .main {
        flex: 1;
        display: flex;
        justify-content: space-between;

        .left {
          .name {
            font-size: 28rpx;
            color: #333333;
            line-height: 36rpx;
          }

          .des {
            font-size: 28rpx;
            color: #999999;
            margin-top: 10rpx;
          }
        }

        .right {
          flex-shrink: 0;
          margin-left: 20rpx;
          text-align: right;

          .price {
            font-size: 28rpx;
            color: #333333;
            line-height: 28rpx;
            font-weight: 600;
            margin-top: 6rpx;
          }

          .num {
            font-size: 28rpx;
            color: #999999;
            line-height: 28rpx;
            margin-top: 16rpx;
          }
        }
      }
    }

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

      .left {
        font-size: 24rpx;
        color: #666666;
      }

      .right {
        font-size: 24rpx;
        color: #666666;

        text {
          color: $minor-color;
          font-size: 32rpx;
          font-weight: 600;
          margin-left: 8rpx;
        }
      }
    }

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

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

        .tips {
          font-size: 28rpx;
          color: $minor-color;
        }

        .btns {
          display: flex;
        }
      }

      .button {
        width: 140rpx;
        height: 48rpx;
        border-radius: 48rpx;
        text-align: center;
        line-height: 48rpx;
        font-size: 24rpx;
        margin-left: 20rpx;
        flex-shrink: 0;

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

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

        &.white {
          color: $theme-color;
          border: 1px solid $theme-color;
        }

        &.red {
          color: #FFFFFF;
          border: 1px solid $theme-color;
          background: $theme-color;
        }
      }
    }
  }
}
</style>
