<template>
  <view>
    <!-- 导航栏 -->
    <u-navbar back-icon-color="#000000" title-color="#000000" :border-bottom="false" title="确认订单">
      <view slot="right" class="pr-base" @tap="$u.routeAuth('/pages/auxiliary_cart/index')">
        <image class="w-48rpx h-48rpx" src="/static/images/cart/short-cart.png" mode="scaleToFill" />
      </view>
    </u-navbar>

    <loading-view v-if="isFirstLoading"></loading-view>

    <!-- <view v-if="orderInfo.shipping_address">
      <view class="fixed top-0 left-0 w-full h-full flex items-center justify-center flex-1">
        <view class="text-center">
          <view>您还没有收货地址哟！</view>
          <view
            class="bg-white border border-solid border-hex-efefef h-60rpx px-40rpx mt-20rpx leading-60rpx rounded-30rpx text-24rpx text-center inline-block"
            @tap="$u.routeAuth('/pageA/new_address/index', { type: 'select' })"
          >
            新建地址
          </view>
        </view>
      </view>
    </view> -->

    <!--  -->
    <view v-if="skuOne.require_shipping_address ||  type != 'points'" class="flex items-center justify-between px-40rpx bg-white pb-30rpx"
      @tap="addressAry.length?$u.routeAuth('/pageA/address/index'):$u.routeAuth('/pageA/new_address/index?addressType=select')">
      <view>
        <template v-if="orderInfo.shipping_address">
          <view class="flex items-center text-black">
            <image v-if="address.is_default" class="w-59rpx" src="/static/images/order/defalut-icon.png"
              mode="widthFix" />
            <text>{{ address.zone }}</text>
          </view>
          <view class="text-xl text-black my-14rpx"> {{ address.address }} </view>
          <view class="text-lg text-black"> {{ address.consignee }} {{ address.telephone }} </view>
        </template>
        <template v-else>
          <view class="flex items-center text-black">
            <text>暂无默认地址</text>
          </view>
          <view class="text-xl text-black my-14rpx"> 请选择 </view>
        </template>
      </view>
      <view>
        <u-icon name="arrow-right" color="#808080" size="38"></u-icon>
      </view>
    </view>
    <view class="bg-white rounded-xs mt-24rpx py-base px-40rpx" v-if="goodsList.length">
      <block v-for="(item, index) in goodsList" :key="index">
        <view>
          <view class="flex">
            <u-image border-radius="10" width="190rpx" height="190rpx" :src="item.sku.cover" :lazy-load="true">
            </u-image>
            <view class="flex-1 ml-16rpx w-0 flex justify-between flex-col">
              <view>
                <view>
                  <view class="line-2">{{ item.sku.name }}</view>
                </view>
                <view class="mt-10rpx">
                  <u-tag v-for="spec in item.sku.specs" :key="spec" size="mini" :text="spec" class="mr-6rpx"
                    shape="square" color="#A6A6A6" bg-color="transparent" mode="dark" />
                </view>
              </view>
              <view class="flex items-end">
                <view class="flex-1">
                  <view class="">
                    <view class="flex-1">￥{{ item.sku.sell_price }}</view>
                  </view>
                  <view class="flex items-center" v-if="item.sku.vip_price>0">
                    <view class="">￥{{ item.sku.vip_price }}</view>
                    <image class="w-58rpx h-58rpx ml-10rpx" src="/static/svg/svip.svg" mode=""></image>
                  </view>
                </view>
                <view class="text-lg"> x{{ item.quantity }} </view>
              </view>
            </view>
          </view>
        </view>
        <view class="my-20rpx" v-if="index != goodsList.length - 1">
          <u-line color="#E5E5E5" />
        </view>
      </block>
    </view>

    <!--  -->
    <view class="bg-white mt-base rounded-xs px-40rpx py-20rpx" v-if="type != 'bargains' && type != 'points'">
      <view class="flex items-center justify-between">
        <view class="text-md">选择优惠卷</view>
        <view class="flex items-center" @tap="onOpenCoupon">
          <view class="text-md text-txGray mr-10rpx">{{ couponShowText }}</view>
          <u-icon name="arrow-right" color="#808080" size="30"></u-icon>
        </view>
      </view>
      <view class="text-gray-400 text-sm">因系统迁移优惠券问题请联系客服</view>
    </view>
    <!--  -->
    <view class="bg-white mt-base rounded-xs pb-base px-40rpx pt-rowSm text-md">
      <view class="flex items-center justify-between py-rowSm text-txBase" v-if="orderInfo.total_points>0">
        <view>抵扣积分</view>
        <view>{{ orderInfo.total_points }}</view>
      </view>
      <view class="flex items-center justify-between py-rowSm text-txBase">
        <view>商品金额</view>
        <view>￥{{ orderInfo.products_total_amount }}</view>
      </view>
      <view class="flex items-center justify-between py-rowSm text-txBase">
        <view>运费</view>
        <view>￥{{ orderInfo.shipping_fee }}</view>
      </view>
      <view class="flex items-center justify-between py-rowSm text-txBase" v-if="type != 'bargains' && type != 'points'">
        <view>优惠卷</view>
        <view class="text-bgSubtitle">-￥{{ orderInfo.coupon_discount_amount }}</view>
      </view>
      <view class="flex items-center justify-between py-rowSm text-txBase">
        <view>会员优惠</view>
        <view class="text-bgSubtitle">-￥{{ orderInfo.vip_discount_amount }}</view>
      </view>
      <view class="flex items-center justify-between py-rowSm text-txBase" v-if="type == 'bargains'">
        <view>砍价优惠</view>
        <view class="text-bgSubtitle">-￥{{ orderInfo.bargain_amount }}</view>
      </view>
      <!--  -->
      <view class="text-md border-t border-txBorder flex items-center justify-end py-base">
        <view class="text-txBase">实付金额：</view>
        <view class="text-bgSubtitle">￥{{ orderInfo.total_amount }}</view>
      </view>
      <!--  -->
      <view class="border-t border-txBorder pt-base text-md">
        <textarea
          v-model="remarks"
          :adjust-position="false"
          class="min-h-130rpx w-full"
          placeholder-style="text-h999"
          placeholder="订单备注："
          maxlength="100"
          auto-height
        />
      </view>
    </view>

    <cu-popup v-model="couponShow" mode="bottom" border-radius="20" closeable close-icon-size="24">
      <view>
        <view class="text-center py-30rpx text-lg">优惠券</view>
        <scroll-view scroll-y="true" class="max-h-900rpx bg-hex-f6f6f6">
          <coupon-list v-model="tempCouponId" :list="couponsList"></coupon-list>
        </scroll-view>
        <view class="p-base">
          <view class="btn bg-hex-FB4A34 h-84rpx leading-84rpx text-white" @tap="onCounponChange">
            <text>确定</text>
          </view>
        </view>
      </view>
    </cu-popup>

    <!--  -->
    <view class="h-130rpx"></view>
    <!--  -->
    <view class="flex items-center justify-end bg-white shadow-up fixed right-0 left-0 bottom-0 cu-bar tabbar">
      <view class="text-md text-txBase">
        合计: <text class="text-xl" v-if="orderInfo.total_points >0"> {{orderInfo.total_points}}积分+</text> <text class="text-xl text-txSvip">￥{{ orderInfo.total_amount }}</text>
      </view>
      <view @tap="createOrder" class="w-180rpx h-66rpx leading-66rpx text-center text-lg ml-40rpx text-white bg-primary rounded-lg mr-base">提交订单</view>
      <view v-if="is_company" @tap="createPreOrder" class="w-180rpx h-66rpx leading-66rpx text-center text-lg ml-20rpx text-white bg-hex-D43030 rounded-lg mr-base">生成订单</view>
    </view>
  </view>
</template>

<script>
  let btnLoading = false;
  import { add } from '@/utils'
  export default {
    data() {
      return {
        type: '',
        goods: [],
        cards: [],
        addressId: '',
        couponId: '',
        goodsList: [],
        orderInfo: {},
        addressList: [],
        remarks: '',
        tempCouponId: '',
        couponShow: false,
        isFirstLoading:true,
        addressAry:[],
        cuId:null
      };
    },
    onLoad(options) {
      const data = JSON.parse(decodeURIComponent(options.data));

      uni.$on('address:select', this.addressUpdate);

      this.type = data.type;
      this.goods = data?.goods ?? [];
      this.cards = data?.cards ?? [];
      this.cuId = data?.cuId
    },

    computed: {
      skuOne(){
        return this.goodsList[0]?.sku ?? {}
      },
      //收货地址
      address() {
        return this.orderInfo.shipping_address;
      },
      //优惠券列表
      couponsList() {
        return this.orderInfo?.coupons ?? [];
      },
      //优惠券文本显示
      couponShowText() {
        if (!!this.couponId) return this.currentCoupon?.name ?? '已过期';
        if (this.couponsList.length) return `${this.couponsList.length}张可用`;
        else return '当前无可用';
      },
      //当前优惠券
      currentCoupon() {
        const coupon = this.couponsList.find((e) => e.id == this.couponId);
        return coupon;
      },
      //配送支持
      isDistribution() {
        return this.orderInfo?.shipping_supported ?? false;
      },
      user() {
        return this.$store.getters.user ?? {};
      },
      //是否为店员
      is_company() {
        return this.user?.is_company ?? false
      }
    },
    onShow() {
      this.getDetail();
      this.getAddress()
    },
    methods: {
      //创建订单
      async createOrder() {
        const {
          remarks,
          addressId,
          couponId,
          isDistribution
        } = this;
        if(this.type != 'points' || this.skuOne?.require_shipping_address){
          if (!addressId) return this.$u.toast('收货地址不能为空');
          if (!isDistribution) return this.$u.toast('所在地区不支持配送');
        }

        const params = {
          coupon_id: couponId,
          shipping_address_id: addressId,
          note: remarks,
        };

        if(this.type == 'points'){
          const {
            num,
            sku_id
          } = this.goods[0];
          params.sku_id = sku_id
          params.quantity = num
        }else if (this.type == 'bargains') {
          params.cuId = this.cuId
        } else if (this.type == 'cart') {
          params.shopping_cart = this.cards;
        } else {
          const {
            num,
            sku_id
          } = this.goods[0];
          params.product = {
            sku_id: sku_id,
            quantity: num,
          };
        }

        if (btnLoading) return;
        btnLoading = true;

        try {
          let order;
          if(this.type == 'points'){
            order = await this.$api.post(`/v1/points/orders`, params);
          }else if(this.type == 'bargains'){
            order = await this.$api.post(`/v1/bargains/create-mall-order/${this.cuId}`, params);
          }else{
            order = await this.$api.post('/v1/order/orders', params);
          }
          if(order.status==1 || order.status==2){//支付成功
            this.$u.routeAuth({
              url: '/pages/payment_results/payment_results',
              type: 'redirectTo',
              params: {
                id: order.id,
                type: 'success',
              },
            });
          }else if(order.status==0){ //待付款
            this.$u.routeAuth({
              url: '/pages/confirm_payment/confirm_payment',
              type: 'redirectTo',
              params: {
                id: order.id
              }
            });
          }
          // this.$u.routeAuth({
          //   url: '/pages/confirm_payment/confirm_payment',
          //   type: 'redirectTo',
          //   params: {
          //     id: order.id
          //   }
          // });
        } catch (error) {
          // console.log(error);
        } finally {
          btnLoading = false;
        }
      },
      //优惠券改变
      onCounponChange() {
        this.couponId = this.tempCouponId;
        this.getDetail();
        this.couponShow = false;
      },
      onOpenCoupon(){
        if(this.couponsList.length==0) return this.$u.toast('当前无可用优惠券')
        this.couponShow = true
      },
      //地址更换
      addressUpdate({
        id
      }) {
        this.addressId = id;
      },
      //确认订单详情
      async getDetail() {
        const params = {
          coupon_id: this.couponId,
          shipping_address_id: this.addressId,
        };
        if(this.type == 'points'){
          const {
            num,
            sku_id
          } = this.goods[0];
          params.sku_id = sku_id
          params.quantity= num
        }else if(this.type == 'bargains'){
          params.bargain_order_id = this.cuId
          const {
            num,
            sku_id
          } = this.goods[0];
          params.product = {
            sku_id: sku_id,
            quantity: num,
          };
        }else if (this.type == 'cart') {
          params.shopping_cart = this.cards;
        } else {
          const {
            num,
            sku_id
          } = this.goods[0];
          params.product = {
            sku_id: sku_id,
            quantity: num,
          };
        }
        try {
          let orderInfo
          if(this.type == 'points'){
             orderInfo = await this.$api.post('/v1/points/order-check', params);
          }else{
             orderInfo = await this.$api.post('/v1/order/verify-order', params);
          }
          orderInfo.shipping_address && (this.addressId = orderInfo.shipping_address.id);
          this.goodsList = orderInfo.products;
          this.orderInfo = orderInfo;
        } catch (error) {
          console.log(error);
        }finally{
          this.isFirstLoading = false
        }
      },
      async getAddress(){
        const resData = await this.$api.get('/v1/shipping-addresses')
        this.addressAry = resData
      },
      createPreOrder() {
        const params = {
          products: this.goodsList.map(item => {
            return {
              sku_id: item.sku.id,
              quantity: item.quantity,
              send: item.quantity
            }
          }),
          note: this.remarks
        }
        uni.showLoading()
        this.$api.post(`/v1/order-pre`, params).then(res => {
          uni.hideLoading()
          this.$u.route('/pageB/code/index', { id: res.order_pre })
        })
      }
    },
    watch: {
      couponShow(e) {
        if (e) this.tempCouponId = this.couponId;
      },
    },
  };
</script>

<style lang="scss" scoped>
  .listChid:last-child {
    border: 0;
  }
</style>
