<template>
  <view :style="themeColor()" class="payment-wrap">
      <view class="payment-body min-h-[100vh]" v-if="orderData">
          <!-- #ifdef MP -->
          <top-tabbar :data="topTabbarData" :scrollBool="topTabarObj.getScrollBool()"/>
          <!-- #endif -->
          <view class="pt-[30rpx] sidebar-margin payment-bottom">
              <view class="mb-[var(--top-m)] rounded-[var(--rounded-big)] bg-white">
                  <view class="min-h-[140rpx] flex items-center px-[30rpx]"  v-if="orderData.sku_snapshot.goods.is_need_address">
                      <!-- 收货地址 -->
                      <view class="w-full" @click="toSelectAddress">
                          <view v-if="!$u.test.isEmpty(orderData.address_info)" class="pt-[20rpx] pb-[30rpx] flex items-center">
                              <image class="w-[60rpx] h-[60rpx] mr-[20rpx] flex-shrink-0" :src="img('addon/pintuan/payment/position_01.png')" mode="aspectFit"/>
                              <view class="flex flex-col overflow-hidden">
                                  <text class="text-[26rpx] text-[var(--text-color-light9)] mt-[16rpx] truncate max-w-[536rpx]">{{ orderData.address_info.full_address.substring(0, orderData.address_info.full_address.lastIndexOf(orderData.address_info.address)) }}</text>
                                  <text class="font-500 text-[30rpx] mt-[14rpx] text-[#333] truncate max-w-[536rpx]">{{ orderData.address_info.address }}</text>
                                  <view class="flex items-center text-[26rpx] text-[var(--text-color-light6)] mt-[16rpx]">
                                      <text class="mr-[16rpx]">{{ orderData.address_info.name }}</text>
                                      <text>{{ mobileHide(orderData.address_info.mobile) }}</text>
                                  </view>
                              </view>
                              <text class="ml-auto nc-iconfont nc-icon-youV6xx text-[26rpx] text-[var(--text-color-light9)]"></text>
                          </view>
                          <view v-else class="flex items-center">
                              <image class="w-[26rpx] h-[30rpx] mr-[10rpx]" :src="img('addon/pintuan/payment/position_02.png')" mode="aspectFit"/>
                              <text class="text-[28rpx]">添加收货地址</text>
                              <text class="nc-iconfont nc-icon-youV6xx text-[26rpx] text-[var(--text-color-light9)] ml-auto"></text>
                          </view>
                      </view>
                  </view>
              </view>

              <view class="mb-[var(--top-m)] card-template p-[0] pb-[var(--pad-top-m)]">
                  <view class="pt-[var(--pad-top-m)] pb-[14rpx]">
                      <view class="px-[var(--pad-sidebar-m)]" >
                          <view class="flex">
                              <u--image radius="var(--goods-rounded-big)" width="180rpx" height="180rpx" :src="img(orderData.sku_snapshot.goods.cover)" model="aspectFill">
                                  <template #error>
                                      <image class="w-[180rpx] h-[180rpx] rounded-[var(--goods-rounded-big)] overflow-hidden" :src="img('static/resource/images/diy/shop_default.jpg')" mode="aspectFill"/>
                                  </template>
                              </u--image>
                              <view class="flex flex-1 w-0 flex-col justify-between ml-[20rpx] py-[6rpx]">
                                  <view class="line-normal">
                                      <view class="truncate text-[#303133] text-[28rpx] leading-[32rpx]">{{ orderData.sku_snapshot.goods.title }}</view>
                                      <view class="mt-[14rpx] flex" v-if="orderData.sku_snapshot.sku_name">
                                          <text class="truncate text-[24rpx] text-[var(--text-color-light9)] leading-[28rpx]">{{ orderData.sku_snapshot.sku_name }}</text>
                                      </view>
                                  </view>
                                  <view class="flex justify-between items-baseline">
                                      <view class="text-[var(--price-text-color)] flex items-baseline  price-font">
                                          <text class="text-[24rpx] font-500 mr-[4rpx]">￥</text>
                                          <text class="text-[40rpx] font-500">{{ parseFloat(orderData.sku_snapshot.goods_money).toFixed(2).split('.')[0] }}</text>
                                          <text class="text-[24rpx] font-500">.{{ parseFloat(orderData.sku_snapshot.goods_money).toFixed(2).split('.')[1] }}</text>
                                      </view>
                                      <view class="font-400 text-[28rpx] text-[#303133]">
                                          <text>x</text>
                                          <text>{{ orderData.num }}</text>
                                      </view>
                                  </view>
                              </view>
                          </view>
                          <view class="card-template !p-[0]" v-if="orderData.sku_snapshot.goods.form_id">
                              <diy-form ref="diyFormGoodsRef" :form_id="orderData.goods.form_id" :relate_id="orderData.sku_id" :storage_name="'diyFormStorageByGoodsDetail_' + orderData.sku_id" form_border="none"/>
                          </view>
                      </view>
                  </view>
                  <!-- 买家留言 -->
                  <view class="bg-white flex items-center leading-[30rpx] px-[var(--pad-sidebar-m)] mt-[30rpx]" @click="toLeaveMessage" >
                      <view class="text-[28rpx] w-[150rpx] text-[#303133]">买家留言</view>
                      <view class="flex-1 text-[#303133] flex items-center justify-center">
                            <view class="flex-1 w-0 text-right truncate">
                                <text class="text-[28rpx] text-[var(--text-color-light9)]">{{createData.member_remark?createData.member_remark:'请输入留言信息给卖家'}}</text>
                            </view>
                           <text class="ml-auto text-[28rpx] nc-iconfont nc-icon-youV6xx  text-[var(--text-color-light9)]"></text>
                      </view>
                  </view>

              </view>

              <view class="card-template">
                  <view class="title">价格明细</view>
                  <view class="card-template-item">
                      <view class="text-[26rpx] w-[150rpx] leading-[30rpx] text-[#303133]">商品金额</view>
                      <view class="flex-1 w-0 text-right  price-font text-[#333] text-[32rpx]">￥{{ parseFloat(orderData.goods_money).toFixed(2) }}</view>
                  </view>
                  <template v-if="orderData.third_cost_list && orderData.third_cost_list.length" >
                    <view class="card-template-item" v-for="(item, index) in orderData.third_cost_list" :key="index">
                        <view class="text-[26rpx] w-[150rpx] leading-[30rpx] text-[#303133]">{{item.name}}</view>
                        <view class="flex-1 w-0 text-right  price-font text-[#333] text-[32rpx]">￥{{ parseFloat(item.amount).toFixed(2) }}</view>
                    </view>
                  </template>
                  
              </view>
          </view>
          <u-tabbar :fixed="true" :placeholder="true" :safeAreaInsetBottom="true" zIndex="10">
              <view class="flex-1 flex items-center justify-between pl-[30rpx] pr-[20rpx]">
                  <view class="flex items-baseline">
                      <text class="text-[26rpx] text-[#333] leading-[32rpx]">合计：</text>
                      <view class="inline-block">
                          <text class="text-[26rpx] font-500 text-[var(--price-text-color)] price-font leading-[30rpx]">￥</text>
                          <text class="text-[44rpx]  font-500  text-[var(--price-text-color)] price-font leading-[46rpx]">{{ parseFloat(orderData.order_money).toFixed(2).split('.')[0] }}</text>
                          <text class="text-[26rpx]  font-500  text-[var(--price-text-color)] price-font leading-[46rpx]">.{{ parseFloat(orderData.order_money).toFixed(2).split('.')[1] }}</text>
                      </view>
                  </view>
                  <button class="w-[196rpx]  h-[70rpx] font-500 text-[26rpx] leading-[70rpx] !text-[#fff] m-0  rounded-full primary-btn-bg remove-border" hover-class="none" :disabled="calculateLoading" :class="{'opacity-80': calculateLoading}" @click="create">提交订单</button>
              </view>
          </u-tabbar>

      </view>

      <address-list ref="addressRef" @confirm="confirmAddress" back="/addon/pintuan/pages/order/payment" />
      <message-open ref="messageOpenRef" @submit="confirmMessage" :default-message="createData.member_remark" />
      <pay ref="payRef" @close="payClose" :ignore-pay="['friendspay']"/>

  </view>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { pintuanOrderCalculate,createPintuanOrder } from '@/addon/pintuan/api/order'
import { redirect, img, mobileHide } from '@/utils/common'
import addressList from './components/address-list/address-list'
import messageOpen from './components/message-open/message-open.vue'
import { useSubscribeMessage } from '@/hooks/useSubscribeMessage'
import { onShow } from '@dcloudio/uni-app'
import { cloneDeep } from 'lodash-es'
import { topTabar } from '@/utils/topTabbar'
import diyForm from '@/addon/components/diy-form/index.vue'

const topTabarObj = topTabar()
let topTabbarData = topTabarObj.setTopTabbarParam({ title: '待付款订单' })
const createData: any = ref({
  member_remark: '',
  address_id: '',
  // extend_data: {}, // 扩展数据
  form_data: {} // 万能表单数据（商品+待付款订单）
})

const orderData: any = ref(null)

const payRef = ref()
const addressRef = ref()

const createLoading = ref(false)
const calculateLoading = ref(false)
uni.getStorageSync('pintuan0rderCreateData') && Object.assign(createData.value, uni.getStorageSync('pintuan0rderCreateData'))

const diyFormRef: any = ref(null)
const diyFormGoodsRef: any = ref(null)

onShow(() => {

})

// 选择地址之后跳转回来
const selectAddress = uni.getStorageSync('selectAddressCallback')
if (selectAddress) {
  createData.value.address_id = selectAddress.address_id
  uni.removeStorage({ key: 'selectAddressCallback' })
}

/**
* 订单计算
*/
const calculate = (params: any = {}) => {

  const calculateData = Object.assign({}, createData.value, params)
  calculateLoading.value = true
  pintuanOrderCalculate(calculateData).then(({ data }) => {
       orderData.value = cloneDeep(data);
       calculateLoading.value = false

      orderData.value.goods = []; //购买商品
      if (orderData.value.sku_snapshot.goods && Object.values(orderData.value.sku_snapshot.goods).length) {
          Object.values(orderData.value.sku_snapshot.goods).forEach((item: any, index) => {
              orderData.value.goods.push(item);
          })
      }
  }).catch(() => {
      calculateLoading.value = false
  })
}

calculate()

let orderNo = 0


/**
* 订单创建
*/
const create = () => {
  if (!verify() || createLoading.value) return
  if(orderData.value.error.length){
      uni.showToast({ icon: 'none', title: orderData.value.error[0] })
      return;
  }
  if (diyFormGoodsRef.value) {
      let pass = true;
      for (let i = 0; i < diyFormGoodsRef.value.length; i++) {
          if (!diyFormGoodsRef.value[i].verify()) {
              pass = false;
              break;
          }
      }
      if (!pass) return;
  }

  if (diyFormRef.value && !diyFormRef.value.verify()) return;
  createLoading.value = true
    if(createData.value.is_single_buy){
        useSubscribeMessage().request('pintuan_order_pay')
    }else{
        if(createData.value.join_type == 'open_group'){
            useSubscribeMessage().request('pintuan_open_success,pintuan_success,pintuan_fail')
        }else{
            useSubscribeMessage().request('pintuan_join_success,pintuan_success,pintuan_fail')
        }
    }
  

  createData.value.form_data.order = {};
  createData.value.form_data.goods = {};
  if (diyFormGoodsRef.value) {
      createData.value.form_data.order = diyFormGoodsRef.value.getData();
  }
   createData.value.order_key = orderData.value.order_key;
  createPintuanOrder(createData.value).then(({ data }) => {
      orderNo = data.order_no
      if (diyFormRef.value) diyFormRef.value.clearStorage();
      if (diyFormGoodsRef.value) {
          for (let i = 0; i < diyFormGoodsRef.value.length; i++) {
              diyFormGoodsRef.value[i].clearStorage()
          }
      }
      createData.value.form_data = {}
      if (orderData.value.order_money == 0) {
        redirect({ url: '/addon/pintuan/pages/order/detail', param: { order_no: orderNo}, mode: 'redirectTo' })
        // if(createData.value.is_single_buy){
           
        // }else{
        //     redirect({ url: '/addon/pintuan/pages/share', param: { order_no: orderNo }, mode: 'redirectTo' })
        // }
      } else {
        payRef.value?.open(data.trade_type, data.order_id, `/addon/pintuan/pages/order/detail?order_no=${ data.order_no }`)
        // if(createData.value.is_single_buy){
         
        // }else{
        //   payRef.value?.open(data.trade_type, data.order_id, `/addon/pintuan/pages/share?order_no=${ data.order_no }`)
        // }
      }
  }).catch((err) => {
      if (err.code == 401) {
          uni.showToast({ icon: 'none', title: '登录过期，请重新登录' })
          redirect({
              url: '/addon/pintuan/pages/index',
              mode: 'reLaunch'
          });
      }
      createData.value.form_data = {}
      createLoading.value = false
  })
}

/**
* 下单校验
*/
const verify = () => {
  const data = createData.value
  let verify = true
  if (orderData.value.sku_snapshot.goods.is_need_address) {
      if (!orderData.value.address_info || !orderData.value.address_info.id) {
          uni.showToast({ title: '请选择收货地址', icon: 'none' })
          return false
      }
  }
  return verify
}

/**
* 支付弹窗关闭
*/
const payClose = () => {
  redirect({ url: '/addon/pintuan/pages/order/detail', param: { order_no: orderNo }, mode: 'redirectTo' })
}

/**
* 选择地址
*/
const toSelectAddress = () => {
    let data: any = {};
    data.id = orderData.value.address_info.id ||  '';
    data.type = 'address';
    data.delivery = 'express'
    addressRef.value.open(data);
}
 
const confirmAddress = (data: any) => {
  createData.value.address_id = data.address_id
  calculate();
}
const messageOpenRef = ref()
const toLeaveMessage = () => {
  messageOpenRef.value.open();
}
const confirmMessage = (message: string) => {
   createData.value.member_remark = message
}
</script>

<style lang="scss" scoped>
.head-tab {
  .head-tab-item {
      .tab-image {
          left: 50%;
          transform: translateX(-50%);
      }

      &:nth-child(1).active {
          view {
              padding-right: 40rpx;
          }
      }

      &:nth-child(2) {
          .tab-image {
              width: 312rpx;
          }
      }

      &:nth-child(3).active {
          view {
              padding-left: 30rpx;
          }
      }

      &.active {
          view {
              font-weight: bold;
              color: var(--primary-color);
          }
      }

      .tab-img {
          left: 50%;
          transform: translateX(-50%);
      }

  }
}

:deep(.u-alert) {
  padding: 6rpx 16rpx !important;
  display: inline-block !important;
}

.alert-wrap {
  display: inline-block !important;

  :deep(.u-fade-enter-active) {
      display: inline-block !important;
  }
}

.text-ellipsis {
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  overflow: hidden;
}

.line-normal {
  line-height: normal;
}

.bg-color {
  background: linear-gradient(94deg, var(--primary-help-color2) 0%, var(--primary-color) 69%), var(--primary-color);
}

.payment-bottom {
  padding-bottom: calc(20rpx + constant(safe-area-inset-bottom));
  padding-bottom: calc(20rpx + env(safe-area-inset-bottom));
}

.payment-wrap {
  background: linear-gradient(180deg, transparent 0%, transparent 80%, var(--page-bg-color) 100%);
}

.payment-body {
  --pintuan-payment-header-color: #F42612; // 待支付头部颜色
  --pintuan-payment-header-tab-color: #FEEAE9; // 待支付头部颜色
  /*  #ifdef MP  */
  background: linear-gradient(180deg, transparent 0%, transparent 10%, var(--page-bg-color) 30%);
  /*  #endif  */
  /*  #ifdef H5  */
  background: linear-gradient(180deg, transparent 0%, var(--page-bg-color) 25%);
  /*  #endif  */
  &::after {
      content: '';
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      z-index: -1;
      /*  #ifdef MP  */
      height: 560rpx;
      background: linear-gradient(180deg, var(--pintuan-payment-header-color) 20%, var(--page-bg-color) 90%), var(--page-bg-color);
      /*  #endif  */
      /*  #ifdef H5  */
      height: 360rpx;
      background: linear-gradient(180deg, var(--pintuan-payment-header-color) 0%, var(--page-bg-color) 90%), var(--page-bg-color);
      /*  #endif  */
  }
}
</style>
