<template>
  <view class="container p-bottom" :style="appThemeStyle">
    <view class="container-br"></view>

    <view v-if="order.goodsList.length">
      <!-- 实物订单：选择配送方式 -->
      <block v-if="order.orderType == OrderTypeEnum.PHYSICAL.value">
        <!-- 配送方式选项卡 -->
        <view v-if="isShowTab" class="swiper-tab dis-flex flex-y-center flex-x-around">
          <view class="swiper-tab-item" :class="{on: curDelivery == DeliveryTypeEnum.EXPRESS.value}" @click="handleSwichDelivery(DeliveryTypeEnum.EXPRESS.value)">
            <text>快递配送</text>
          </view>
        </view>

        <!-- 快递配送：配送地址 -->
        <view v-if="curDelivery == DeliveryTypeEnum.EXPRESS.value" @click="onSelectAddress" class="flow-delivery">
          <view class="flow-delivery__detail dis-flex flex-y-center">
            <view class="detail-location dis-flex">
              <text class="iconfont icon-dingwei"></text>
            </view>
            <view class="detail-content flex-box">
              <block v-if="order.address">
                <view class="detail-content__title dis-flex">
                  <text class="f-30">{{ order.address.name }}</text>
                  <text class="detail-content__title-phone f-28">{{ order.address.phone }}</text>
                </view>
                <view class="address detail-content__describe">
                  <text class="region" v-for="(region, idx) in order.address.region" :key="idx">{{ region }}</text>
                  <text class="detail">{{ order.address.detail }}</text>
                </view>
              </block>
              <block v-else>
                <view class="detail-content__describe dis-flex">
                  <text class="col-6">请选择配送地址</text>
                </view>
              </block>
            </view>
            <view class="detail-arrow dis-flex">
              <text class="iconfont icon-arrow-right"></text>
            </view>
          </view>
        </view>
      </block>

      <!-- 商品列表 -->
      <view class="checkout_list" v-for="(item, index) in order.goodsList" :key="index">
        <view class="flow-shopList dis-flex" data-index="index" @click="onTargetGoods(item.goods_id)">
          <!-- 商品图片 -->
          <view class="flow-list-left">
            <image mode="scaleToFill" :src="item?.productpic"></image>
            <text class="goods-props">时长：{{ item.productlimit }} 月</text> <br />
            <text class="goods-props">赠送：{{ item.productlimit1 }}</text
            ><br />
            <text class="goods-props">宽带：{{ item.productdkband }}</text
            ><br />
            <text class="goods-props">赠送时长：{{ item.productlimit }}</text>
          </view>
          <view class="flow-list-right flex-box">
            <!-- 商品名称 -->
            <text class="goods-name twoline-hide">{{ item.productname }}</text>
            <!-- 商品规格 -->
            <view class="goods-props clearfix">
              <view class="goods-props-item">
                <!-- <text class="group-name">时长：{{ item.productlimit }} 月</text><br />
                <text class="group-name">赠送：{{ item.productlimit1 }}</text
                ><br />
                <text class="group-name">宽带：{{ item.productdkband }}</text
                ><br />
                <text class="group-name">赠送时长：{{ item.productlimit }}</text
                ><br /> -->
                <text class="group-name">注：{{ item.productmemo }}</text>
                <!-- <text>火爆；</text> -->
              </view>
            </view>
            <!-- 商品数量和单价 -->
            <view class="flow-list-cont dis-flex flex-x-between flex-y-center">
              <text class="small">×1</text>
              <text class="flow-cont" style="text-decoration: line-through !important" :class="[item.is_user_grade ? 'price-delete' : '']">原价：￥{{ item.productprice }}</text>
            </view>
            <!-- 会员折扣价 -->
            <view class="grade-price">
              <text>折扣价：￥{{ item.productprice1 }}</text>
            </view>
          </view>
        </view>
      </view>
      <view class="flow-num-box b-f">
        <!-- <text>共{{ order.orderTotalNum }}件商品，合计：</text>
        <text class="flow-money col-m">￥{{ order.orderTotalPrice }}</text> -->
        <text>共 1 件商品</text>
      </view>

      <!-- 商品金额 -->
      <view class="flow-all-money b-f m-top20">
        <view class="flow-all-list dis-flex">
          <text class="flex-five">订单总金额：</text>
          <view class="flex-five t-r">
            <text class="col-m">￥{{ order.goodsList[0]?.productprice1 }}</text>
          </view>
        </view>

        <view class="flow-all-list dis-flex">
          <text class="flex-five">时长：</text>
          <view class="flex-five t-r">
            <text class="">{{ order.goodsList[0]?.productlimit }} {{order.goodsList[0]?.productlimittype}}</text>
          </view>
        </view>
        <view class="flow-all-list dis-flex">
          <text class="flex-five">宽带：</text>
          <view class="flex-five t-r">
            <text class="">{{ order.goodsList[0]?.productdkband }} M</text>
          </view>
        </view>
        <view class="flow-all-list dis-flex">
          <text class="flex-five">赠送时长：</text>
          <view class="flex-five t-r">
            <text class="">{{ order.goodsList[0]?.productlimit }} 小时</text>
          </view>
        </view>
        <view class="flow-all-list dis-flex">
          <text class="flex-five">类型：</text>
          <view class="flex-five t-r">
            <text v-if="mode === 'buyNow'" class="col-m">购入新账户</text>
            <text v-if="mode === 'buyXuyue'" class="col-m">账户续约</text>
          </view>
        </view>

        <!-- 优惠券 -->
        <!-- <view v-if="$checkModule('market-coupon')" class="flow-all-list dis-flex">
          <text class="flex-five">优惠券：</text>
          <view class="flex-five t-r">
            <view v-if="order.couponList.length > 0" @click="handleShowPopup()">
              <text class="col-m" v-if="order.couponId > 0">-￥{{ order.couponMoney }}</text>
              <text class="col-m" v-else>有{{ order.couponList.length }}张优惠券</text>
              <text class="right-arrow iconfont icon-arrow-right"></text>
            </view>
            <text v-else class="">无优惠券可用</text>
          </view>
        </view> -->
        <!-- 支付方式 -->
        <view class="flow-all-list">
          <text class="flex-five-center">请选择支付方式</text>
          <view class="flex-five t-r">
            <view class="payment-method">
              <view v-for="(item, index) in methodsPal" :key="index" class="pay-item dis-flex flex-x-between" @click="handleSelectPayType(index)">
                <view class="item-left dis-flex flex-y-center">
                  <view class="item-left_icon" :class="`${item.paysortname}`">
                    <text class="iconfont" :class="[item.paysortname == '支付宝' ? 'icon-alipay alipay' : 'icon-wechat-pay wechat']"></text>
                  </view>
                  <view class="item-left_text">
                    <text>{{ item.paysortname }}</text>
                  </view>
                </view>
                <view class="item-right col-m r_flex_center">
                  <view class="gouxuan-box" :class="[curPaymentItem && curPaymentItem.paysortid == item.paysortid ? 'actvie-zf' : '']">
                    <i-check-small
                      theme="outline"
                      size="16"
                      fill="#fff"
                      :strokeWidth="4"
                      strokeLinejoin="bevel"
                      strokeLinecap="square"
                      v-if="curPaymentItem && curPaymentItem.paysortid == item.paysortid"
                    />
                  </view>
                </view>
              </view>
              <view class="payment-method" style="text-align: center; margin-top: 10px" v-if="methodsPal.length === 0"> 该企业没有支付方式 </view>
            </view>
          </view>
        </view>

        <!-- 积分抵扣 -->
        <view v-if="$checkModule('market-points') && order.isAllowPoints" class="points flow-all-list dis-flex flex-y-center">
          <view class="block-left flex-five" @click="handleShowPoints()">
            <text class="title">可用{{ setting.points_name }}抵扣：</text>
            <text class="iconfont icon-help"></text>
          </view>
          <view class="flex-five dis-flex flex-x-end flex-y-center">
            <text class="points-money col-m">-￥{{ order.pointsMoney }}</text>
            <u-switch v-model="isUsePoints" size="48" active-color="#07c160" @change="getOrderData()"></u-switch>
          </view>
        </view>
        <!-- 配送费用 -->
        <view v-if="false" class="dis-flex flow-all-list">
          <text class="flex-five">配送费用：</text>
          <view class="flex-five t-r">
            <view v-if="order.address">
              <text class="col-m" v-if="order.isIntraRegion">+￥{{ order.expressPrice }}</text>
              <text v-else>不在配送范围</text>
            </view>
            <view v-else>
              <text class="col-7">请先选择配送地址</text>
            </view>
          </view>
        </view>
      </view>

      <!-- 买家留言 -->
      <view class="flow-all-money b-f m-top20">
        <view class="ipt-wrapper flow-all-list">
          <input class="input" v-model="remark" placeholder="选填：买家留言（50字以内）" />
        </view>
      </view>

      <!-- 提交订单 -->
      <view class="flow-fixed-footer b-f m-top10">
        <view class="dis-flex chackout-box">
          <view class="chackout-left pl-12"
            >实付款：
            <text class="col-m">￥{{ order.goodsList[0]?.productprice1 }}</text>
          </view>
          <view class="chackout-right" @click="onSubmitOrder()">
            <view class="flow-btn f-32" :class="{disabled}">提交订单</view>
          </view>
        </view>
      </view>

      <!-- 积分说明弹窗 -->
      <u-modal v-model="showPoints" :title="`${setting.points_name}说明`">
        <scroll-view class="points-content" :scroll-y="true">
          <text>{{ setting.points_describe }}</text>
        </scroll-view>
      </u-modal>

      <!-- 优惠券弹出框 -->
      <u-popup v-model="showPopup" mode="bottom">
        <view class="popup__coupon">
          <view class="coupon__title f-30">选择优惠券</view>
          <!-- 优惠券列表 -->
          <view class="coupon-list">
            <scroll-view :scroll-y="true" style="height: 565rpx">
              <view class="coupon-item" v-for="(item, index) in order.couponList" :key="index">
                <view class="item-wrapper" :class="[item.is_apply ? 'color-' + CouponColors[`${index % CouponColors.length}`] : 'color-gray']">
                  <view class="coupon-type">{{ CouponTypeEnum[item.coupon_type].name }}</view>
                  <view class="tip dis-flex flex-dir-column flex-x-center">
                    <view v-if="item.coupon_type == CouponTypeEnum.FULL_DISCOUNT.value">
                      <text class="f-30">￥</text>
                      <text class="money">{{ item.reduce_price }}</text>
                    </view>
                    <text class="money" v-if="item.coupon_type == CouponTypeEnum.DISCOUNT.value">{{ item.discount }}折</text>
                    <text class="pay-line">满{{ item.min_price }}元可用</text>
                  </view>
                  <view class="split-line"></view>
                  <view class="content dis-flex flex-dir-column flex-x-between">
                    <view class="title">{{ item.name }}</view>
                    <view class="bottom dis-flex flex-y-center">
                      <view class="time flex-box">
                        <block v-if="item.start_time === item.end_time">{{ item.start_time }} 当天有效</block>
                        <block v-else>{{ item.start_time }}~{{ item.end_time }}</block>
                      </view>
                    </view>
                  </view>
                </view>
              </view>
            </scroll-view>
          </view>
          <!-- 不使用优惠券 -->
          <view class="coupon__do_not dis-flex flex-y-center flex-x-center">
            <view class="control dis-flex flex-y-center flex-x-center" @click="handleNotUseCoupon()">
              <text class="f-26">不使用优惠券</text>
            </view>
          </view>
        </view>
      </u-popup>
    </view>
    <u-toast ref="uToast" />

    <div id="form" v-show="false" v-html="formDom"></div>
  </view>
</template>

<script>
import * as Verify from '@/utils/verify'
import * as CheckoutApi from '@/api/checkout'
import * as AppApi from '@/api/app'
import {CouponTypeEnum} from '@/common/enum/coupon'
import {OrderTypeEnum, DeliveryTypeEnum} from '@/common/enum/order'
import storage from '@/utils/storage'
import {Alipay, Wechat} from '@/core/payment'

const CouponColors = ['red', 'blue', 'violet', 'yellow']

// 根据指定mode获取对应的api类
const getCheckoutApi = (mode) => {
  const apiEnum = {
    buyNow: CheckoutApi,
    cart: CheckoutApi
  }
  return apiEnum[mode]
}

// 根据指定mode获取param
const getModeParam = (mode, options) => {
  const param = {}

  console.log(options, 'options')

  // 结算模式: 立即购买
  if (mode === 'buyNow') {
    // param.goodsId = options.goodsId
    // param.goodsNum = options.goodsNum
    // param.goodsSkuId = options.goodsSkuId
  }
  // 结算模式: 购物车
  if (mode === 'cart') {
    // param.cartIds = options.cartIds
  }
  return param
}

export default {
  data() {
    return {
      // 枚举类
      OrderTypeEnum,
      DeliveryTypeEnum,
      CouponTypeEnum,
      // 当前页面参数
      options: {},
      // 配送方式
      isShowTab: false,
      DeliveryTypeEnum,
      curDelivery: null,
      // 优惠券颜色组
      CouponColors,
      // 选择的优惠券
      selectCouponId: 0,
      // 是否使用积分抵扣
      isUsePoints: false,
      // 买家留言
      remark: '',
      // 禁用submit按钮
      disabled: false,
      // 是否显示积分说明
      showPoints: false,
      // 是否显示优惠券弹窗
      showPopup: false,
      // 订单信息 (从后端api中获取)
      order: {
        // 商品列表
        goodsList: [],
        // 优惠券列表
        couponList: [],
        // 是否存在收货地址
        existAddress: false,
        // 默认收货地址
        address: null,
        // 是否存在收货地址
        existAddress: false,
        // 当前用户收货城市是否存在配送规则中
        isIntraRegion: true,
        // 是否存在错误
        hasError: false,
        // 错误信息
        errorMsg: ''
      },
      // 个人信息
      personal: {},
      // 商城设置
      setting: {},
      // 支付宝
      methodsPal: [],
      curPaymentItem: {},
      // 提交支付表单
      formDom: '',
      // 购买类型
      mode: ''
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  async onLoad(options) {
    this.mode = options?.mode
    if (options?.goodsId) {
      let query = options
      this.queryData = await this.getProductData(query.goodsId)
      // 获取当前订单信息
      this.getOrderData()
    } else {
      this.$toast('没有商品')
    }
  },

  /**
   * 生命周期函数--监听页面的卸载
   */
  onUnload() {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {},

  methods: {
    // 选择支付方式
    handleSelectPayType(index) {
      this.curPaymentItem = this.methodsPal[index]
    },

    // 获取订单数据
    async getOrderData() {
      // 获取支付数据
      const params = {
        pageindex: 1,
        rows: 99,
        pagevalue: 288,
        'paysortagentsqym.value': storage.get('wx_qym'),
        'paysortsfky.value': 1
      }
      const {Data: res} = await AppApi.getPalList(params)
      this.methodsPal = res.Data
      this.handleSelectPayType(0)
      this.initData()

      // const app = this
      // const {
      //   options: {mode}
      // } = app
      // // 请求的参数
      // const params = app.getRequestParam()
      // // 请求api
      // getCheckoutApi(mode)
      //   .order(mode, params)
      //   .then((result) => app.initData(result.data))
      //   .catch((err) => err)
    },

    async getProductData(id) {
      const params = {
        pageindex: 1,
        rows: 9,
        'productid.value': id
      }
      const {Data: res} = await AppApi.getShopList(params)
      return res.Data
    },

    // 初始化数据
    initData(setting, personal) {
      const app = this
      const order = {
        // 优惠劵
        couponList: [],
        // 地址
        address: {},
        // 配送方式
        delivery: 10,
        // 商品
        goodsList: this.queryData
      }
      app.order = order
      app.personal = {
        address_id: 15328,
        balance: '0.00',
        points: 0,
        user_id: 19016
      }
      app.setting = {
        deliveryType: [10],
        points_describe: '积分不可兑现、不可转让',
        points_name: '积分'
      }
      // 显示错误信息
      if (order.hasError) {
        app.showToast(order.errorMsg, 3000)
      }
      // 当前选择的配送方式
      app.curDelivery = order.delivery
      // 如果只有一种配送方式则不显示选项卡
      app.isShowTab = app.setting.deliveryType.length > 1

      console.log(order, '订单数据')
    },

    // 获取api请求的参数
    getRequestParam() {
      const app = this
      const {options} = app
      // 结算模式的固定参数
      const modeParam = getModeParam(options.mode, options)
      // 订单结算参数(用户选择)
      const orderParam = {
        delivery: app.curDelivery || 0,
        couponId: app.selectCouponId || 0,
        isUsePoints: app.isUsePoints ? 1 : 0
      }
      return {...orderParam, ...modeParam}
    },

    // 切换配送方式
    handleSwichDelivery(key) {
      this.curDelivery = key
      this.getOrderData()
    },

    // 显示积分说明
    handleShowPoints() {
      this.showPoints = true
    },

    // 显示优惠券弹窗
    handleShowPopup() {
      this.showPopup = true
    },

    // 选择优惠券
    handleSelectCoupon(index) {
      const app = this
      const {couponList} = app.order
      // 当前选择的优惠券
      const couponItem = couponList[index]
      // 判断是否在适用范围
      if (!couponItem.is_apply) {
        app.showToast(couponItem.not_apply_info)
        return
      }
      // 记录选中的优惠券id
      app.selectCouponId = couponItem.user_coupon_id
      // 重新获取订单信息
      app.getOrderData()
      // 隐藏优惠券弹层
      app.showPopup = false
    },

    // 不使用优惠券
    handleNotUseCoupon() {
      const app = this
      app.selectCouponId = 0
      // 重新获取订单信息
      app.getOrderData()
      // 隐藏优惠券弹层
      app.showPopup = false
    },

    // 快递配送：选择收货地址
    onSelectAddress() {
      this.$navTo('pages/address/index', {from: 'checkout'})
    },

    // 跳转到商品详情页
    onTargetGoods(goodsId) {
      this.$navTo('pages/goods/detail', {goodsId})
    },

    // 提交支付订单
    async onSubmitOrder() {
      const app = this
      if (app.disabled) {
        return false
      }
      // 支付方式
      if (!app.curPaymentItem.paysortname) {
        app.$toast('您还没有选择支付方式')
        return false
      }

      // 按钮禁用
      app.disabled = true

      const pram = {
        // 客户id
        customerid: storage.get('wx_userid'),
        // wx_openid
        openid: storage.get('wx_openid'),
        // 支付方式
        paysortid: app.curPaymentItem.paysortid,
        // 用户id
        yhinfoid: storage.get('wx_yhinfo')[0] ? storage.get('wx_yhinfo')[0].yhinfoid : '',
        // 资费类型
        productid: app.order.goodsList[0].productid
        // 金额
        // price: Number(this.order.goodsList[0].productprice1).toFixed(2)
      }

      let res = {}
      switch (app.mode) {
        // 购买新账户
        case 'buyNow':
          res = await AppApi.plFomr3(pram).finally(() => (app.disabled = false))
          break

        // 续约
        case 'buyXuyue':
          res = await AppApi.plXufei(pram).finally(() => (app.disabled = false))
          break
        default:
          break
      }

      app.disabled = true
      app.$toast('发起' + app.curPaymentItem.paysortname + '支付...')

      if (app.curPaymentItem.paysortname == '支付宝') {
        // 发起支付宝支付
        this.formDom = res.Data
        // app.$toast('提交支付宝中...')
        if (this.formDom) {
          setTimeout(() => {
            document.forms['alipaysubmit'].submit()
            app.disabled = false
          }, 500)

          setTimeout(() => {
            app.$navTo('pages/user/index')
          }, 1000)
        }
      } else if (app.curPaymentItem.paysortname == '微信') {
        // 发起微信支付
        this.formDom = res.Data
        const wechat = res

        // app.$toast('提交微信中...')

        WeixinJSBridge.invoke(
          'getBrandWCPayRequest',
          {
            appId: wechat.Data.appId, //公众号ID，由商户传入
            timeStamp: wechat.Data.timeStamp, //时间戳，自1970年以来的秒数
            nonceStr: wechat.Data.nonceStr, //随机串
            package: wechat.Data.package,
            signType: wechat.Data.signType, //微信签名方式：
            paySign: wechat.Data.paySign
          },
          function (res) {
            // 支付成功
            if (res.err_msg == 'get_brand_wcpay_request:ok') {
              // 使用以上方式判断前端返回,微信团队郑重提示：
              app.$toast('支付成功')
              app.$navTo('pages/user/index')
            }
            // 支付过程中用户取消
            if (res.err_msg == 'get_brand_wcpay_request:cancel') {
              app.$toast('支付取消')
              app.disabled = false
            }
            // 支付失败
            if (res.err_msg == 'get_brand_wcpay_request:fail') {
              app.$toast('支付失败')
              app.disabled = false
            }
          }
        )
      }
    },

    // 跳转到我的订单(等待1秒)
    navToMyOrder() {
      setTimeout(() => {
        this.$navTo('pages/order/index', {}, 'redirectTo')
      }, 1000)
    },

    // 表单提交的数据
    getFormData() {
      const app = this
      const {options} = app
      // 表单数据
      const form = {
        delivery: app.curDelivery,
        couponId: app.selectCouponId || 0,
        isUsePoints: app.isUsePoints ? 1 : 0,
        remark: app.remark || ''
      }
      // 获取不同模式的参数
      const modeParam = getModeParam(options.mode, options)
      return {...form, ...modeParam}
    },

    // 表单验证
    onVerifyFrom() {
      const app = this
      if (app.hasError) {
        app.showToast(app.errorMsg, 3000)
        return false
      }
      return true
    },

    // 显示toast信息
    showToast(title, duration = 2000) {
      this.$refs.uToast.show({title, duration})
    }
  }
}
</script>

<style lang="scss" scoped>
@import './style.scss';
</style>
