<template>
  <view class="order-detail">
    <!-- 订单状态操作 -->
    <view class="cell">
      <view
        class="order-status"
        @click="toOrderStatus"
        v-if="order.status > 100 || order.deliveryType !== 'self'"
      >
        <text class="text">{{cms.orderStatus[order.status]}}</text>
        <text class="btn-text">查看详情</text>
        <text class="icon-aw"></text>
      </view>
      <!--  -->
      <view class="order-status" v-else>
        <text class="text">待自提</text>
      </view>
      <!-- 不同状态文字提示 -->
      <view class="tips">
        <text v-if="order.status === 2">请尽快支付，以免订单被取消</text>
        <text
          v-if="order.status >= 5 && order.status <= 20"
        >{{order.deliveryType === 'self' ? '商品已在准备中，请按时自提哟' : '商品已在路上'}}</text>
        <text v-if="order.status === 110">感谢您对京西菜市的信任，期待再次光临</text>
        <text v-if="order.status === 115">您的订单已取消</text>
      </view>
      <!-- 不同状态可操作按钮 -->
      <view class="order-op">
        <view
          class="btn-normal btn-cancel"
          v-if="order.status < 110 && countDownText !== '已超时'"
          @click="handleClickBtn('cancel')"
        >取消订单</view>
		    <!-- 该售后接口不完善，暂时取消售后 -->
        <!-- order.status === 110 -->
        <!-- <view
            class="btn-normal btn-afsOrder"
            v-if="afsOrderStatus"
            @click="handleClickBtn('afsOrder')"
          >申请售后
        </view> -->
        <view
          class="btn-normal btn-rebuy"
          v-if="order.status === 110 || order.status === 115"
          @click="handleClickBtn('rebuy')"
        >再来一单</view>
        <view
          :class="{
            'btn-normal': true,
            'btn-repay': true,
            'btn-disable': countDownText === '已超时'
          }"
          v-if="order.status === 2"
          @click="handleClickBtn('repay')"
        >去支付({{countDownText}})</view>
      </view>
      <!-- 配送员信息 -->
      <view class="deliver-man-info" v-if="order.courierMobile">
        <view class="deliver-left">
          <text class="icon-avatar"></text>
          <view class="deliver-courier">
            <text class="courier-name">{{order.courierName}}</text>
            <text class="courier-vendorName">{{cms.vendorName[order.waybillVendorID]}}</text>
          </view>
        </view>
        <view class="deliver-right" @click="concatCourier">
          <text class="icon-tel"></text>
        </view>
      </view>
    </view>
    <!-- 售后单信息 -->
    <view class="cell2 wall" v-if="afsOrders.length">
      <text class="wall-title">售后单信息</text>
      <view class="wall-content" v-for="item in afsOrders" :key="item.afsOrderID">
        <text class="left">售后单号</text>
        <text class="right" @click="toAfsOrderDetail(item.afsOrderID)">{{item.afsOrderID}}</text>
      </view>
    </view>
    <!-- 售后单信息 -->
    <!-- 订单商品信息 -->
    <view class="cell2">
      <view class="order-goods-list">
        <goods-group
          v-for="(val, key) in groupList"
          :key="key"
          :storeID="key"
          :storeName="order.storeName"
          :skuList="val"
        ></goods-group>
      </view>
      <!-- 费用 -->
      <view class="other-price" >
        <left-right-cell noClick>
          <template v-slot:left>
            <text>商品总价</text>
          </template>
          <template v-slot:right>
            <text>￥{{$filters.toFixed2(order.salePrice)}}</text>
          </template>
        </left-right-cell>
        <left-right-cell noClick>
          <template v-slot:left>
            <text >重量</text>
          </template>
          <template v-slot:right>
            <text v-if="order.weight">{{$filters.switchWeight(order.weight)}}</text>
          </template>
        </left-right-cell>
        <left-right-cell noClick>
          <template v-slot:left>
            <text>配送费</text>
          </template>
          <template v-slot:right>
            <text>￥{{$filters.toFixed2(order.desiredFee)}}</text>
          </template>
        </left-right-cell>
      </view>
      <!-- 费用 -->
      <!-- 联系商家 -->
      <view class="concat-store">
        <left-right-cell noClick>
          <template v-slot:left>
            <view>
              <view class="concat-wrapper">
                <view class="tel-store" @click="concatStore">
                  <text class="icon-mobile"></text>
                  <text class="text">联系商家</text>
                </view>
                <!-- <div class="contanct-online" @click="toOnline">在线联系</div> -->
              </view>
            </view>
          </template>
          <template v-slot:right>
            <view>
              <view class="actual-price">
                实付
                <span class="span">￥{{$filters.toFixed2(order.actualPayPrice)}}</span>
              </view>
            </view>
          </template>
        </left-right-cell>
      </view>
      <!-- 联系商家 -->
    </view>
    <!-- 配送信息 -->
    <view class="cell2 wall">
      <text class="wall-title">配送信息{{order.deliveryType === 'self' ? '(自提订单)' : ''}}</text>
      <view class="wall-content">
        <text class="left">预计{{order.deliveryType === 'self' ? '自提' : '送达'}}</text>
        <text>：</text>
        <text class="right">{{expectTimeText}}</text>
      </view>
      <view class="wall-content" v-if="order.deliveryType !== 'self'">
        <text class="left">送货地址</text>
        <text>：</text>
        <view class="right">
          <view>{{order.consigneeName}}</view>
          <view>{{order.consigneeMobile}}</view>
          <view>{{order.consigneeAddress}}</view>
        </view>
      </view>
      <view class="wall-content">
        <text class="left">备注</text>
        <text>：</text>
        <view class="right">
          <text>{{order.buyerComment}}</text>
        </view>
      </view>
    </view>
    <!-- 配送信息 -->
    <!-- 订单信息 -->
    <view class="cell2 wall">
      <view class="wall-title">订单信息</view>
      <view class="wall-content">
        <text class="left">订单号</text>
        <text>：</text>
        <text class="right">{{order.vendorOrderID}}</text>
      </view>
      <view class="wall-content">
        <text class="left">支付方式</text>
        <text>：</text>
        <text class="right">微信支付</text>
      </view>
      <view class="wall-content">
        <text class="left">下单时间</text>
        <text>：</text>
        <text class="right">{{$filters.dateToLLLL(order.orderCreatedAt)}}</text>
      </view>
    </view>
    <!-- 订单信息 -->
    <!-- loading -->
    <zy-loading></zy-loading>
  </view>
</template>

<script>
import { errToast, alert, toast, modal,openWeixinMiniprogram,jumpPage } from "@/utils/uniapi.js";
import ZyLoading from "@/components/Loading/loading";
import { mapGetters, mapActions } from "vuex";
import { groupByStore } from '@/utils'
import GoodsGroup from "../orderCmp/goods-group/goods-group.vue";
import LeftRightCell from "@/components/layout/left-right-cell.vue";
import { formatDate } from "@/utils/assist.js";
import {store} from '@/store'

import goodPage from '@/apis/goodPage';
import orderPage from '@/apis/orderPage'
import { handleCreatePay } from '@/utils/uniapi.js'
export default {
  components: {
    ZyLoading,
    GoodsGroup,
    LeftRightCell,
  },
  data() {
    return {
      order: {},
      storeTel: "",
      orderGoods: [],
      groupList: [],
      countDownText: "",
      timer: null,
      isOnLoad: false,
      afsOrders: [],
    };
  },
  async onLoad(query) {
    await this.globalLogin()
    // console.log(query);
    const { vendorOrderID } = query;
    try {
      this.showLoad();
      await this.oneOrder(vendorOrderID);
      const { storeID, vendorID, status } = this.order;
      await this.getStoreTel(storeID);
      await this.getOrderGoods(vendorOrderID, vendorID);
      if (status === 110) {
        // 完成订单查找售后单
        this.afsOrders = (await orderPage.getAfsOrders(vendorOrderID)).data || []
      }
      this.groupList = groupByStore(this.orderGoods)
    } catch (e) {
      console.error(e);
      alert(e);
    } finally {
      this.hideLoad();
      this.isOnLoad = true;
    }
  },
  async onShow() {
    if (this.isOnLoad) {
      // 请求售后单
      const { vendorOrderID, status } = this.order;
      if (status === 110) {
        // 完成订单查找售后单
        this.afsOrders = (await orderPage.getAfsOrders(vendorOrderID)).data || []
      }
    }
  },
  // 下拉刷新
  async onPullDownRefresh() {
    console.log("下拉刷新");
    // uni.stopPullDownRefresh()
    try {
      this.showLoad();
      const { vendorOrderID, storeID, vendorID, status } = this.order;
      await this.oneOrder(vendorOrderID);
      await this.getStoreTel(storeID);
      await this.getOrderGoods(vendorOrderID, vendorID);
      if (status === 110) {
        // 完成订单查找售后单
        this.afsOrders = (await orderPage.getAfsOrders(vendorOrderID)).data || []
      }
      this.groupList = groupByStore(this.orderGoods);
      // console.log("groupList", this.groupList);
    } catch (e) {
      console.error(e);
      errToast(e);
    } finally {
      uni.stopPullDownRefresh();
      this.hideLoad();
    }
  },
  beforeDestroy() {
    clearInterval(this.timer);
    this.timer = null;
  },
  computed: {
    ...mapGetters({
      cms: "login/cms",
      isMaterial: "indexPage/isMaterial",
      isPurchase: "indexPage/isPurchase",
      storeMap: "indexPage/storeMap",
      materialInfo: "indexPage/materialInfo",
      storeID: "indexPage/storeID",
    }),
    // 处理售后状态
    afsOrderStatus() {
      let flag = false
      if (this.order) {
        let time = new Date() - new Date(this.order.orderFinishedAt)
        // console.log('time',time,'2天,毫秒',48 * 60 * 60 * 1000)
        // 订单完成后,两天内可申请售后
        flag = (this.order.status === 110 && time < 48 * 60 * 60 * 1000)?true:false
      }
      return flag
    },
    // 配送时间处理
    expectTimeText() {
      let { expectedDeliveredTime } = this.order;
      if (!expectedDeliveredTime || Date(expectedDeliveredTime) <= 0) {
        return "立即送达";
      } else {
        return formatDate(expectedDeliveredTime, "YYYY-MM-DD hh:mm:ss");
      }
    },
  },
  methods: {
    ...mapActions({
      clearAllShopCar: "cartPage/clearAllShopCar",
      changeCar: "cartPage/changeCar",
    }),
    // 查询订单
    async oneOrder(vendorOrderID) {
      try {
        let { data } = await orderPage.getMyOrders({ vendorOrderID });
        // console.log("订单数据", data[0]);
        this.order = data[0];
        // 倒计时
        if (this.order.status === 2) {
          // 先清除再倒计时
          clearInterval(this.timer);
          this.timer = null;
          let needPayEndAt =
            this.order.needPayEndAt ||
            +new Date(this.order.orderCreatedAt) + 10 * 60 * 1000;
          this.countDownText = this.updateCountDown(needPayEndAt);
          if (this.countDownText === "已超时") return false;
          this.timer = setInterval(() => {
            this.countDownText = this.updateCountDown(needPayEndAt);
          }, 1000);
        }
      } catch (e) {
        console.error(e);
        throw e;
      }
    },
    // 查询门店电话
    async getStoreTel(storeID) {
      try {
        if (this.storeMap && this.storeMap[storeID] && this.storeMap[storeID].mobile) this.storeTel = this.storeMap[storeID].mobile
        else {
          await store.dispatch('indexPage/getStoreInfo', { storeID })
          this.getStoreTel(storeID)
        }
      } catch (e) {
        console.error(e);
        throw e;
      }
    },
    // 查询订单商品
    async getOrderGoods(vendorOrderID, vendorID) {
      try {
        let res = await orderPage.getOrderSkuInfo(vendorOrderID, vendorID);
        
        this.orderGoods = res.map((item) => ({
          ...item,
          storeID: this.order.storeID,
          storeName: this.order.storeName,
          id: item.jxSkuID,
          nameID: item.nameID,
          img: item.image,
          name: item.skuName,
          curPrice: item.salePrice,
          count: item.count,
        }));
      } catch (e) {
        console.error(e);
        throw e;
      }
    },
    // 倒计时
    updateCountDown(endAt) {
      let time = new Date(endAt) - new Date();
      if (time <= 0) {
        if(this.order.status === 2){
          // 由待支付变为取消订单
          orderPage.buyerCancelOrder({
              vendorOrderID: order.vendorOrderID,
              vendorID: order.vendorID,
              reason: "支付超时",
          });
          this.oneOrder(this.order.vendorOrderID)
        }
        return "已超时";
      } else {
        return `还剩${formatDate(time, "mm")}分${formatDate(time, "ss")}秒`;
      }
    },
    // 操作
    async handleClickBtn(key) {
      // console.log("操作", key, this.order); 
      const order = this.order;
      if (key === "repay") {
        if (this.countDownText === "已超时") return false;
        // 重新支付
        try {
          this.showLoad();
          // 获取支付信息
          let payInfo = null

          // #ifdef MP-WEIXIN
          payInfo = await orderPage.pay4Order({
            vendorOrderID: order.vendorOrderID,
            payType: 2,
            vendorPayType: "W06",
            subAppID:"wx4b5930c13f8b1170",
          });
          await handleCreatePay(
            payInfo.vendorOrderID,
            payInfo.prepayID,
            JSON.parse(payInfo.codeURL)
          );
          // #endif

          // #ifdef MP-TOUTIAO
          payInfo = await orderPage.pay4Order({
            vendorOrderID: order.vendorOrderID,
            payType: 3,
            vendorPayType: 'tt',
            // subAppID: "tta6a1d01c399f264201",  // 京西菜市
            subAppID: "tta6a1d01c399f264201",   // 京西到家
          });
          await handleCreatePay(
            payInfo.vendorOrderID,
            payInfo.prepayID,
            payInfo.codeURL,
            payInfo
          );
          // #endif

          // #ifdef MP-KUAISHOU
          payInfo = await orderPage.pay4Order({
            vendorOrderID: order.vendorOrderID,
            payType: 4,
            vendorPayType: 'ks',
            // subAppID: "tta6a1d01c399f264201",  // 京西菜市
            subAppID: "ks680887971696897880",   // 京西到家
          });
          await handleCreatePay(
            payInfo.vendorOrderID,
            payInfo.prepayID,
            payInfo.codeURL,
            payInfo
          );
          // #endif

          // #ifdef APP-PLUS || APP
          let res = await modal("温馨提示", '为了保证您的账户安全，即将跳转到微信进行支付');

          if (res) {
            let jxParams = {
              "origin": "weixinappcs",
              "vendorOrderID": order.vendorOrderID,
              "storeID": order.storeID,
              "name":order.storeName,
              "totalPrice":order.actualPayPrice
            }
            // console.log('打印jxParams', JSON.stringify(jxParams))
            openWeixinMiniprogram(`pagesPay/JX-pay/JX-pay?jxParams=${JSON.stringify(jxParams)}`)
          }


          // #endif

          // #ifdef MP-ALIPAY
          payInfo = await orderPage.pay4Order({
            vendorOrderID: order.vendorOrderID,
            payType: 2,
            vendorPayType: 'A02',
          });
          await handleCreatePay(
            payInfo.vendorOrderID,
            payInfo.prepayID,
            payInfo.codeURL
          );
          // #endif

          // 支付成功，跳转到待收货订单

          await this.oneOrder(order.vendorOrderID);
          await this.getOrderGoods(order.vendorOrderID, order.vendorID);
        } catch (e) {
          console.error(e);
          if ("errKey" in e) {
            errToast("订单支付失败，请稍后重试");
          } else {
            errToast(e);
          }
        } finally {
          this.hideLoad();
        }
      } else if (key === "rebuy") {
        // 再来一单
        // 请求商品
        // console.log('在来一单---------')
        try {
          this.showLoad();
          let { skuNames } = await goodPage.getStoresSkus({
            skuIDs: Array.from(
              new Set(order.skuList.map((item) => item.skuID))
            ),
            storeID: order.storeID,
          });
          console.log(skuNames);

          // #ifdef MP-WEIXIN
          if (this.isMaterial && this.materialInfo && this.materialInfo.fromStoreInfo.packageSwitch === 1) return toast(`非常抱歉,无法购买物料，请联系运营${this.materialInfo.fromStoreInfo.marketManPhone}`)
          // #endif

          if (skuNames.length > 0) {
            // 把数量加上
            skuNames.forEach((skuName, i) => {
              let findItem = order.skuList.filter(
                (item) => item.skuID === skuName.id
              );
              console.log(findItem, skuNames[i]);
              if (findItem) {
                skuNames[i].count = findItem.reduce(
                  (prev, next) => prev + next.skuCount2,
                  0
                );
              }
            });
            store.commit('indexPage/changeStoreID', [skuNames[0].storeID])
           
            // 获取单门店的数据信息，保存到storeMap中
            if (!this.storeMap[store.getters.storeID])  await store.dispatch('indexPage/getStoreInfo',{storeID:this.storeID[0]})

            // 清空购物车，放入购物车
            await this.clearAllShopCar();

             await this.changeCar({  // 放入购物车
              skuName: skuNames,
            });
            // 跳转到购物车页面
            // #ifndef MP-TOUTIAO || APP-PLUS || APP
            jumpPage("switchTab","/pages/cart/index")
            // #endif
                  
            // #ifdef MP-TOUTIAO || APP-PLUS || APP
            jumpPage("navigateTo","/pages/cart/index")
            // #endif
          } else {
            throw new Error("订单商品已下架");
          }
        } catch (e) {
          console.error(e);
          errToast(e);
        } finally {
          this.hideLoad();
        }
      } else if (key === "received") {
        toast("暂无功能");
      } else if (key === "cancel") {
        if (this.order.status < 15) {
          let res = await modal("取消订单", "是否取消该单");
          if (res) {
            try {
              await orderPage.buyerCancelOrder({
                vendorOrderID: order.vendorOrderID,
                vendorID: order.vendorID,
                reason: "买家取消订单",
              });
              toast("取消成功");
              await this.oneOrder(order.vendorOrderID);
            } catch (e) {
              // alert(e)
              if (this.isMaterial) {
                if (this.isPurchase) {
                  alert("请联系运营取消采购订单");
                } else {
                  alert("请联系运营取消物料申请");
                }
              } else {
                if (this.storeTel) {
                  let confirm = await modal("取消订单", "是否联系商家取消订单");
                  if (confirm)
                    uni.makePhoneCall({ phoneNumber: this.storeTel });
                } else {
                  toast("暂无商家联系方式");
                }
              }
            }
          }
        } else {
          if (this.isMaterial) {
            alert("请联系运营取消物料申请");
          } else {
            let confirm = await modal("取消订单", "是否联系商家取消订单");
            if (confirm) uni.makePhoneCall({ phoneNumber: this.storeTel });
          }
        }
      } else if (key === "afsOrder") {
        uni.setStorageSync('createAfsOrder',order)
        jumpPage("redirectTo",`/pagesOrders/create-afsorder/index?vendorOrderID=${order.vendorOrderID}&vendorID=${order.vendorID}`)
      }
    },
    // 联系配送员
    async concatCourier() {
      let confirm = await modal("联系配送员", "是否呼叫骑手");
      if (confirm) uni.makePhoneCall({ phoneNumber: this.order.courierMobile });
    },
    // 联系商家
    async concatStore() {
      if (this.storeTel) {
        let confirm = await modal("联系商家", "是否联系商家");
        if (confirm) uni.makePhoneCall({ phoneNumber: this.storeTel });
      } else {
        toast("暂无商家联系方式");
      }
    },
    toOnline() {
      const { vendorOrderID, vendorID } = this.order;
      jumpPage("navigateTo",`/pagesOrders/online-contact/index?vendorOrderID=${vendorOrderID}&vendorID=${vendorID}`)
    },
    // 跳转到订单序列页面
    toOrderStatus() {
      const { vendorOrderID, vendorID } = this.order;
      jumpPage("navigateTo",`/pagesOrders/order-status/index?vendorOrderID=${vendorOrderID}&vendorID=${vendorID}`)
    },
    // 跳转到售后单详情
    toAfsOrderDetail(afsOrderID) {
      const { vendorOrderID, vendorID } = this.order;
      jumpPage("navigateTo",`/pagesOrders/afsorder-detail/index?vendorOrderID=${vendorOrderID}&afsOrderID=${afsOrderID}&vendorID=${vendorID}`)
    },
  },
};
</script>

<style lang="scss">
@import "./order-detail.scss";
page {
  background: #f4f4f4;
}
</style>