<template>
  <div class="page order-detail">
    <div class="Od__item Od__status">
      <div class="Od__status-desc">
        <div class="Od__status-statusTxt">{{ orderInfo.orderStatusInfo.orderStatusText }}</div>
        <div class="Od__status-txt">{{ orderInfo.orderStatusInfo.text }}</div>
      </div>
      <cr-image
        width="2.666667rem"
        height="2.666667rem"
        class="Od__status-img"
        :src="orderStatusImg"
      />
    </div>
    <div
      v-if="orderInfo.shipmentInfo && orderInfo.shipmentInfo.promoterPhoneNo"
      class="Od__item Od__price"
    >
      <div class="Od__price-statistic">
        <span>取货方式</span>
        <span>门店自提</span>
      </div>
      <div class="Od__price-statistic">
        <span>推广员手机号</span>
        <span>{{ orderInfo.shipmentInfo.promoterPhoneNo }}</span>
      </div>
      <div v-if="orderInfo.orderStatusInfo.orderStatus == 41" class="Od__price-notice">
        您的取货方式为门店自提，请您线下联系推广员取货即可
      </div>
    </div>
    <div v-else class="Od__item Od__address">
      <div class="Od__address-person">
        <cr-tag v-if="orderInfo.receiverInfo.addrDefault == 1" type="primary">默认</cr-tag>
        <span>
          {{ orderInfo.receiverInfo.receiverName }}
          {{ orderInfo.receiverInfo.receiverPhoneNo }}
        </span>
      </div>
      <div class="Od__address-desc">
        <div>{{ orderInfo.receiverInfo.addrFullName }}</div>
      </div>
    </div>
    <div class="Od__item Od__list">
      <list-item
        :list="orderInfo"
        :can-click="true"
        :order-config-xincheng="$config.xincheng"
        :show-after="
          orderInfo.orderStatusInfo.orderStatus == 31 || orderInfo.orderStatusInfo.orderStatus == 41
        "
        :after-show="true"
        :show-expiration-date="true"
      />
    </div>
    <div class="only-customer" @click="goToCustomer()">
      <cr-image class="only-customer-img" src="https://img.lkbang.net/comcuster.png" />
      联系客服
    </div>
    <div v-if="giftCardDesc && giftCardDescLinkUrl" class="giftcard-desc">
      <cr-image
        src="https://img.lkbang.net/giftcard-icon.5dac221c.png"
        width="12px"
        height="12px"
      />
      <span class="desc">{{ giftCardDesc }}</span>
      <div class="link" @click="toGiftcardsPage(giftCardDescLinkUrl)">
        <span>查看</span>
        <cr-icon type="arrow" />
      </div>
    </div>
    <div class="Od__item Od__price">
      <!-- 活动优惠金额 -->
      <div v-if="orderInfo.feeInfo.activityDeductionFee" class="Od__price-statistic">
        <span>活动优惠</span>
        <span>¥{{ orderInfo.feeInfo.activityDeductionFee || 0 }}</span>
      </div>
      <!-- 优惠券抵扣金额 -->
      <div v-if="orderInfo.feeInfo.couponDeductionFee" class="Od__price-statistic">
        <span>优惠</span>
        <span>¥{{ orderInfo.feeInfo.couponDeductionFee || 0 }}</span>
      </div>
      <!-- 现金券抵扣金额 -->
      <div v-if="orderInfo.feeInfo.cashCouponDeductionFee" class="Od__price-statistic">
        <span>现金券</span>
        <span>¥{{ orderInfo.feeInfo.cashCouponDeductionFee || 0 }}</span>
      </div>

      <!-- 运费优惠券抵扣金额 -->
      <div v-if="orderInfo.feeInfo.freightDeductionFee" class="Od__price-statistic">
        <span>运费优惠</span>
        <span>¥{{ orderInfo.feeInfo.freightDeductionFee || 0 }}</span>
      </div>
      <div v-if="orderInfo.feeInfo.giftCardDeductionFee" class="Od__price-statistic">
        <span>礼品卡</span>
        <span>¥{{ orderInfo.feeInfo.giftCardDeductionFee || 0 }}</span>
      </div>
      <div class="Od__price-statistic">
        <span>运费</span>
        <!-- 订单运费总金额 -->
        <span>¥{{ orderInfo.feeInfo.totalFreightFee || 0 }}</span>
      </div>
      <div v-if="orderInfo.feeInfo.payDeductionFee" class="Od__price-statistic">
        <span>支付优惠</span>
        <span>¥{{ orderInfo.feeInfo.payDeductionFee || 0 }}</span>
      </div>
      <div class="Od__price-statistic">
        <span v-if="orderInfo.orderStatusInfo.orderStatus == 11">待付款</span>
        <span v-else>实付款</span>
        <!-- 订单总金额 -->
        <span class="Od__price-bold">¥{{ orderInfo.feeInfo.totalFee || 0 }}</span>
      </div>
    </div>
    <div class="Od__item Od__info">
      <div class="Od__info-item">
        订单编号：<span>{{ orderInfo.orderDetail.orderNo || '' }}</span>
        <span class="Od__info-right" @click="copyOrderNo">复制</span>
      </div>
      <div class="Od__info-item">
        下单时间：<span>{{ orderInfo.orderDetail.orderTime || '' }}</span>
      </div>
      <div v-if="orderInfo.orderDetail.payTime" class="Od__info-item">
        支付时间：<span>{{ orderInfo.orderDetail.payTime || '' }}</span>
      </div>
      <div v-if="orderInfo.payDetail && orderInfo.payDetail.creditPayAmt" class="Od__info-item">
        信用支付金额：<span>{{ orderInfo.payDetail.creditPayAmt || '' }}</span>
      </div>
      <div v-if="orderInfo.payDetail && orderInfo.payDetail.wxPayAmt" class="Od__info-item">
        微信支付金额：<span>{{ orderInfo.payDetail.wxPayAmt || '' }}</span>
      </div>
      <div v-if="orderInfo.payDetail && orderInfo.payDetail.aliPayAmt" class="Od__info-item">
        支付宝支付金额：<span>{{ orderInfo.payDetail.aliPayAmt || '' }}</span>
      </div>
      <div v-if="orderInfo.orderDetail.payType" class="Od__info-item">
        支付方式：<span>{{ orderInfo.orderDetail.payType }}</span>
      </div>
      <div v-if="orderInfo.orderDetail.deliveryAt" class="Od__info-item">
        发货时间：<span>{{ orderInfo.orderDetail.deliveryAt }}</span>
      </div>
      <div v-if="orderInfo.orderDetail.orderCompleteTime" class="Od__info-item">
        完成时间：<span>{{ orderInfo.orderDetail.orderCompleteTime }}</span>
      </div>
    </div>
    <div class="Od__bottom">
      <!-- 11-待付款 21-待发货 31-待收货 41-已完成 51-已取消 52-取消订单审核中-->
      <!-- <cr-button
        v-if="
          orderInfo.orderStatusInfo.isShowRemindCancel == 1 &&
            (orderInfo.orderStatusInfo.orderStatus == 31 ||
              orderInfo.orderStatusInfo.orderStatus == 51)
        "
        size="small"
        plain
        type="default"
        shape="circle"
        @click="urgeStatusbtn"
      >
        催促一下
      </cr-button> -->
      <cr-button
        v-if="orderInfo.orderStatusInfo.orderStatus == 11"
        size="small"
        plain
        type="default"
        shape="circle"
        hairline
        @click="openCancelPopup(orderInfo.orderStatusInfo.orderStatus)"
      >
        取消订单
      </cr-button>
      <template v-if="orderInfo.orderStatusInfo.orderStatus == 11">
        <prepayBtn
          :order-status="orderInfo.orderStatusInfo.orderStatus"
          :order-data="orderInfo"
          @clickBtn="toPay"
        />
      </template>

      <!-- <cr-button
        v-if="
          (orderInfo.orderStatusInfo.orderStatus == 21 ||
            orderInfo.orderStatusInfo.orderStatus == 31) &&
            orderInfo.orderStatusInfo.isShowRefund
        "
        size="small"
        plain
        type="default"
        shape="circle"
        hairline
        @click="orderRefundPopup(orderInfo.orderStatusInfo)"
      >
        {{ orderInfo.orderStatusInfo.orderStatus == 21 ? '申请退款' : '取消订单' }}
      </cr-button> -->
      <cr-button
        v-if="
          orderInfo.orderStatusInfo.orderStatus == 21 &&
            orderInfo.orderStatusInfo.isShowRefund &&
            !orderInfo.orderStatusInfo.isShowRefundAudit &&
            $config.yxm
        "
        size="small"
        plain
        type="default"
        shape="circle"
        hairline
        @click="orderRefundPopup(orderInfo)"
      >
        申请退款
      </cr-button>
      <cr-button
        v-if="
          orderInfo.orderStatusInfo.orderStatus == 21 &&
            orderInfo.orderStatusInfo.isShowRefundAudit &&
            orderInfo.orderStatusInfo.isShowRefund
        "
        size="small"
        plain
        type="primary"
        shape="circle"
        hairline
        disabled
      >
        审核中
      </cr-button>
      <cr-button
        v-if="orderInfo.orderStatusInfo.orderStatus == 21"
        size="small"
        plain
        type="default"
        shape="circle"
        hairline
        @click="orderNotify"
      >
        提醒发货
      </cr-button>
      <cr-button
        v-if="
          (orderInfo.orderStatusInfo.orderStatus == 41 ||
            orderInfo.orderStatusInfo.orderStatus == 31) &&
            orderInfo.orderStatusInfo.isShowLogistics
        "
        size="small"
        plain
        type="default"
        shape="circle"
        hairline
        @click="expressActionsCheck"
      >
        查看物流
      </cr-button>
      <cr-button
        v-if="
          orderInfo.orderStatusInfo.orderStatus == 31 &&
            orderInfo.orderStatusInfo.isShowRemindCancel !== 1
        "
        size="small"
        plain
        type="primary"
        shape="circle"
        hairline
        @click="orderConfirmPopup"
      >
        确认收货
      </cr-button>
      <cr-button
        v-if="
          orderInfo.orderStatusInfo.orderStatus == 41 || orderInfo.orderStatusInfo.orderStatus == 51
        "
        size="small"
        plain
        type="primary"
        shape="circle"
        hairline
        @click="toGoods"
      >
        再次购买
      </cr-button>
      <!-- <cr-button
        v-if="
          orderInfo.orderStatusInfo.isShowRemindCancel == 1 &&
            orderInfo.orderStatusInfo.orderStatus == 31
        "
        size="small"
        plain
        type="primary"
        shape="circle"
        @click="cancelRefundPopup"
      >
        撤销申请
      </cr-button> -->
    </div>
    <cancel-popup
      ref="cancelPopupRef"
      v-model="showCancelPopup"
      :order-info="{
        orderNo,
        orderStatus,
        totalFee: orderInfo.feeInfo.totalFee,
        skuList: orderInfo.skuList
      }"
      @complete="handleCancelState"
    />
    <cancel-popup-now
      v-model="showCancelPopupNow"
      :order-info="{
        orderNo,
        orderStatus,
        totalFee: orderInfo.feeInfo.totalFee,
        skuList: orderInfo.skuList
      }"
      @complete="handleCancelState"
    />
    <RefundDialog
      v-model="refundImmediately"
      :refund-status="refundStatus"
      :refund-contract-info-list="refundContractInfoList"
      :cash-coupon-cancel-note="orderInfo.orderStatusInfo.cashCouponCancelNote"
    />
  </div>
</template>
<script>
import cfg from '@/config';
import ListItem from '../orderList/components/ListItem.vue';
import CancelPopup from '../orderList/components/CancelPopup.vue';
import CancelPopupNow from '../orderList/components/CancelPopupNow.vue';
import RefundDialog from '../orderList/components/RefundDialog.vue';
import clipTextMixins from '@/mixins/clipText.mixins';
import localStorage from '@/service/localStorage.service';
import orderApi from '@/api/order.api';
import prepayBtn from '@/components/prepayBtn.vue';
import img11 from '@/assets/images/order/11.png';
import img21 from '@/assets/images/order/21.png';
import img31 from '@/assets/images/order/31.png';
import img41 from '@/assets/images/order/41.png';
import img51 from '@/assets/images/order/51.png';
import { REFUND_TYPE } from '../../constants/refund';
const orderStatusImgs = {
  11: img11,
  21: img21,
  31: img31,
  41: img41,
  51: img51,
  61: img51,
  62: img51
};
export default {
  name: 'OrderDetail',
  components: {
    ListItem,
    CancelPopup,
    CancelPopupNow,
    RefundDialog,
    prepayBtn
  },
  mixins: [clipTextMixins],
  data() {
    return {
      REFUND_TYPE,
      orderInfo: {
        feeInfo: {},
        orderDetail: {},
        orderStatusInfo: {},
        receiverInfo: {},
        skuList: [],
        payDetail: {},
        orderNo: ''
      },
      orderNo: '',
      orderStatus: '',
      showCancelPopup: false,
      showCancelPopupNow: false,
      refundImmediately: false,
      refundContractInfoList: [],

      refundStatus: 0,
      afterCurrentSkuInfo: {}
    };
  },
  computed: {
    giftCardDesc() {
      return this.orderInfo &&
        this.orderInfo.giftCardReturnInfo &&
        this.orderInfo.giftCardReturnInfo.text
        ? this.orderInfo.giftCardReturnInfo.text
        : '';
    },
    giftCardDescLinkUrl() {
      return this.orderInfo &&
        this.orderInfo.giftCardReturnInfo &&
        this.orderInfo.giftCardReturnInfo.jumpUrl
        ? this.orderInfo.giftCardReturnInfo.jumpUrl
        : '';
    },
    isRefundBtn() {
      const orderStatus = this.orderInfo.orderStatusInfo.orderStatus;
      let isShow = false;
      if ((orderStatus == 21 || orderStatus == 31) && this.orderInfo.orderStatusInfo.isShowRefund) {
        if (this.$config.xincheng) {
          isShow = true;
        } else {
          if (orderStatus != 21) {
            isShow = true;
          }
        }
      }
      return isShow;
    },
    orderStatusImg() {
      return orderStatusImgs[this.orderInfo.orderStatusInfo.orderStatus] || '';
    }
  },
  created() {
    this.orderNo = this.$route.query.orderNo;
    this.getDetail();
  },
  methods: {
    // 跳转礼品卡页面
    toGiftcardsPage(url) {
      if (url) {
        url = url.replace('{token}', localStorage.get('vccToken'));
        window.location.href = url;
      }
    },
    // 联系客服
    goToCustomer() {
      const customerLink = this.orderInfo.customerConf.customerLink;
      if (this.$bridge.isApp) {
        this.$bridge.openNewUrl({
          data: {
            newUrl: customerLink
          }
        });
        return false;
      }
      window.location.href = customerLink;
    },
    cancelRefundPopup() {
      let tips = {
        message:
          this.orderInfo.orderStatusInfo.cashCouponCancelNote ||
          '您的订单取消申请商家正在审核中，确认撤销取消订单申请吗?',
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        // eslint-disable-next-line space-before-function-paren
        onConfirm: async () => {
          await orderApi.cancelRevoke({ orderNo: this.orderNo });
          this.refresh();
        }
      };
      this.$dialog(tips);
    },
    // 催办接口
    async urgeStatusbtn() {
      await orderApi.remindCancel({ orderNo: this.orderNo });
      this.$toast.success('催办成功');
    },
    async getDetail() {
      const [res] = await orderApi.orderDetail({ orderNo: this.orderNo });
      this.orderInfo = res;
      this.orderStatus = this.orderInfo.orderStatusInfo.orderStatus;
    },
    contractCS() {
      cfg.SOBOT_URL.replace('{userId}', localStorage.get('userId') || Math.random() * 100);
      window.location.href = cfg.SOBOT_URL;
    },
    async cancelOrder() {
      const [res, error] = await orderApi.orderCancelReasonV2({
        orderNo: this.orderInfo.orderDetail.orderNo
      });
      if (!error) {
        this.$refs.cancelPopupRef.reasonList = res.cancelReasonList;
        this.$refs.cancelPopupRef.iconAndTips = res.iconAndTips;
        this.showCancelPopup = true;
      }
      // let tip = {
      //   message: this.orderInfo.orderStatusInfo.cancelNote || '',
      //   confirmButtonText: '仍要取消',
      //   cancelButtonText: '留下商品',
      //   onConfirm: () => {
      //     this.showCancelPopup = true;
      //   }
      // };
      // this.$dialog(tip);
    },

    async showContractPopup(confirmCallback) {
      // 调接口 判断是否 需要签合同
      const [data] = await orderApi.queryNote({
        orderNo: this.orderInfo.orderDetail.orderNo
      });
      if (data.noteNeedContract) {
        // 需要签合同 弹窗 点了解一下 验证是否勾选合同 合同可以点击跳转
        this.refundImmediately = true;
        this.refundContractInfoList = data.contractInfoList || [];
      } else {
        const orderStatusInfo = this.orderInfo.orderStatusInfo;
        // 不需要签合同
        let tips = {
          title: '退款、退货须知',
          message: orderStatusInfo.cashCouponCancelNote || orderStatusInfo.cancelNote || '',
          confirmButtonText: '已了解',
          cancelButtonText: '取消',
          onConfirm: () => {
            confirmCallback();
          }
        };
        this.$dialog(tips);
      }
    },

    async orderRefundPopup(obj) {
      if (obj.orderStatusInfo.showCashCouponCancelNote) {
        this.refundStatus = 0;
        this.showContractPopup(this.cancelOrder);
      } else {
        // 调取弹窗接口
        this.cancelOrder();
      }
    },
    openCancelPopup(status) {
      let tips = {};
      if (status == 11) {
        if (this.orderInfo.orderStatusInfo.paymentInProgress) {
          tips = {
            message: '订单支付处理中，请稍后再试',
            confirmButtonText: '知道了',
            showCancelButton: false
          };
        } else {
          this.showCancelPopupNow = true;
          return;
        }
      } else {
        tips = {
          message: this.orderInfo.orderStatusInfo.cancelNote || '宝贝已经发货了，您真的要取消吗？',
          confirmButtonText: '仍要取消',
          cancelButtonText: '留下商品',
          onConfirm: () => {
            this.showCancelPopupNow = true;
          }
        };
      }
      this.$dialog(tips);
    },
    handleItemClick(item) {
      this.toGoods(item);
    },
    updateCurrentOrder(state, txt) {
      this.$set(this.orderInfo.orderStatusInfo, `orderStatus`, state);
      this.$set(this.orderInfo.orderStatusInfo, `orderStatusText`, txt);
    },
    toPay() {
      if (this.orderInfo.orderStatusInfo.paymentInProgress) {
        this.$dialog({
          message: '支付中，请勿重复支付',
          confirmButtonText: '知道了',
          showCancelButton: false
        });
        return;
      }
      this.$router.push({ name: 'pay', query: { orderNo: this.orderNo } });
    },
    toGoods() {
      this.$router.push({
        path: '/goodDetail',
        query: { skuNo: this.orderInfo.skuList[0].skuNo }
      });
    },
    orderConfirmPopup() {
      if (!this.orderNo) return;
      this.$dialog({
        message: '确定该订单已收货吗？',
        onConfirm: () => {
          orderApi
            .orderConfirm({
              orderNo: this.orderNo,
              status: 41
            })
            .then(res => {
              if (res[0]) {
                this.updateCurrentOrder(41, '交易完成');
                this.$toast('操作成功');
              }
            });
        }
      });
    },
    handleCancelState() {
      this.refresh();
      this.updateCurrentOrder(51, '交易关闭');
    },
    onOptionClick(info) {
      this.toAfter(info);
    },
    goRefundTypePage() {
      const { orderSkuId } = this.afterCurrentSkuInfo?.currentSku || {};
      if (orderSkuId) {
        this.$router.push({
          name: 'refundType',
          query: { orderSkuId }
        });
        localStorage.set('orderInfo', this.afterCurrentSkuInfo);
        this.afterCurrentSkuInfo = {};
      }
    },
    toAfter(info) {
      // const {
      //   orderStatusInfo: { cashCouponCancelNote }
      // } = info || {};
      const { orderSkuId, afterServiceInfo, afterServiceType } = info.currentSku;
      // if (
      //   (this.orderInfo.orderStatusInfo.orderType == 5 ||
      //     this.orderInfo.orderStatusInfo.orderType == 2) &&
      //   this.orderInfo.orderStatusInfo.orderStatus == 31
      // ) {
      //   this.$dialog({
      //     title: '您购买的商品确认收货后才可申请售后哦！',
      //     showCancelButton: false
      //   });
      //   return;
      // }
      // 超过售后时间弹框
      if (
        afterServiceInfo.cannotApplyAfsNote &&
        ![
          REFUND_TYPE.AUDITING,
          REFUND_TYPE.AUDIT_PASS,
          REFUND_TYPE.AUDIT_REFUSE,
          REFUND_TYPE.POSTING
        ].includes(+afterServiceInfo.serviceStatus)
      ) {
        this.$dialog({
          message: `${afterServiceInfo.cannotApplyAfsNote}`,
          showCancelButton: false,
          confirmButtonText: '知道了'
        });
        return false;
      }
      if (
        afterServiceInfo.showCashCouponCancelNote &&
        [0, 90].includes(+afterServiceInfo.serviceStatus)
      ) {
        this.refundStatus = 1;
        this.afterCurrentSkuInfo = info;
        this.showContractPopup(() => {
          this.$router.push({
            name: 'refundType',
            query: { orderSkuId }
          });
          localStorage.set('orderInfo', info);
        });
        return;
      }
      //售后状态
      let refundUrlName = '';
      // 已经取消售后或者商家拒绝售后   重新走售后流程
      let isRefund = [REFUND_TYPE.CANCEL, REFUND_TYPE.UN_ACCEPT, REFUND_TYPE.AUDIT_REFUSE].includes(
        +afterServiceInfo.serviceStatus
      );
      //afterServiceType售后类型 1-仅退款 2-退货退款

      if (+afterServiceType === 1 && !isRefund) {
        refundUrlName = 'refundOnlyDetail';
      } else if (+afterServiceType === 2 && !isRefund) {
        refundUrlName = 'refundDetail';
      } else {
        refundUrlName = 'refundType';
      }
      this.$router.push({
        name: refundUrlName,
        query: {
          orderSkuId
        }
      });
      localStorage.set('orderInfo', info);
    },
    toRefund() {
      this.$router.push({
        path: '/goodDetail',
        query: { skuNo: this.orderInfo.skuList[0].skuNo }
      });
    },
    expressActionsCheck() {
      const { expressInfoList } = this.orderInfo;
      if (expressInfoList.length > 1) {
        this.expressActions = expressInfoList.map(item => {
          return {
            name: item.deliveryNo,
            deliveryNo: item.deliveryNo,
            expressCompanyCode: item.expressCompanyCode
          };
        });
        this.showExpressPopup = true;
      } else {
        this.toExpress(expressInfoList[0]);
      }
    },
    toExpress(item) {
      // 物流信息传参，订单号对应于orderNo，根据expressCompanyCode（公司编码）和deliveryNo（物流单号）是否存在判断传参
      const { expressCompanyCode, deliveryNo } = item;
      this.$router.push({
        path: '/expressDetail',
        query: deliveryNo
          ? { expressCompanyCode, deliveryNo, orderNo: this.orderNo }
          : { deliveryOrderId: this.orderNo, orderNo: this.orderNo }
      });
    },
    orderNotify() {
      this.$toast.success('已通知卖家');
    },
    copyOrderNo() {
      this.setClipboardData({
        data: this.orderNo,
        success: () => {
          this.$toast.success('已复制');
        }
      });
    },
    refresh() {
      setTimeout(() => {
        window.history.go(0);
      }, 500);
    }
  }
};
</script>
<style lang="less" src="./index.less" scoped></style>
