<template><page-meta :root-font-size="fontSize+'px'"></page-meta>
    <member-base :show="false" ><view class="div container">
        <view class="div common-header-wrap">
            <view :style="'height:'+navHeight+'px'"></view>
            <view class="common-header-holder"></view>
            <view class="common-header-fixed">
            <title-header />
            <uni-nav-bar title="确认订单" class="common-header" left-icon="back" @clickLeft="goBack()">
            </uni-nav-bar>
        </view>
        </view>
        <view class="div body" v-if="store_final_total_list">
            <view class="div block-wrapper">
                <checkout-address v-if="addAddress" class="address" v-on:onclick="goAddress" :item="store_final_total_list.address_info"></checkout-address>
                <view class="div" v-if="store_final_total_list.if_presell" @click="showPopup('togglePresell')">
                    <flex-line class="menu-item" :is-link="true" :show-border="true">
                        <view class="div">
                            <text class="span left-icon iconfont">&#xe664;</text>
                            <text class="span">支付金额</text>
                        </view>
                        <text class="span" slot="right">{{presell_pay=='1'?'全额支付':'先付定金'}}</text>
                    </flex-line>
                </view>
                <!--付款方式-->
                <view class="div" v-if="store_final_total_list.address_api.allow_offpay==1 && store_final_total_list.ifshow_offpay" @click="showPopup('togglePay')">
                    <flex-line class="menu-item" :is-link="true" :show-border="true">
                        <view class="div">
                            <text class="span left-icon iconfont">&#xe664;</text>
                            <text class="span">付款方式</text>
                        </view>
                        <text class="span" slot="right">{{pay_name}}</text>
                    </flex-line>
                </view>
                <!--发票-->
                <view class="div" @click="goNavigate('/pages/member/invoice/InvoiceList',{isFromCheckout:true,goBackLevel:1,invoice_id:invoice_id,vat_deny:store_final_total_list.vat_deny,params:JSON.stringify(option)})">
                    <flex-line class="menu-item" :is-link="true" :show-border="true">
                        <view class="div">
                            <text class="span left-icon iconfont">&#xe664;</text>
                            <text class="span">发票</text>
                        </view>
                        <text class="span" slot="right">{{invoice_content}}</text>
                    </flex-line>
                </view>
                <!--平台代金券-->
                <view v-if="myMallVoucher != ''"  @click="showPopup('mallvoucherVisible')">
                    <flex-line class="menu-item" :is-link="true" :show-border="true">
                        <view>
                            <text class="left-icon iconfont">&#xe664;</text>
                            <text>平台代金券</text>
                        </view>
                        <text slot="right">{{myMallVoucherprice}}</text>
                    </flex-line>
                </view>
            </view>
            <checkout-store class="section-header" :addressInfo="store_final_total_list.address_info" :payGoodsList="store_final_total_list.pay_goods_list" :finalTotalList="store_final_total_list.store_final_total_list" :addressApi="store_final_total_list.address_api" :storeCartList="store_final_total_list.store_cart_list" :ifshowOffpay="store_final_total_list.ifshow_offpay" @selectVoucher="selectVoucher" @selectChain="selectChain" @changeMessage="changeMessage"></checkout-store>
        </view>
        <view class="div bottom-wrapper" v-if="store_final_total_list && store_final_total_list.limit == false">
            <flex-line v-if="!f_code_check && store_final_total_list.store_cart_list_api[0].goods_list[0].is_goodsfcode==1" class="field-line"><text class="span field-name">F码</text><view class="div field-line-right" slot="right"><input class="field-input" v-model="f_code" placeholder="请填写F码" /><view class="div common-btn ds-button-small" @click="checkfcode">使用</view></view></flex-line>
            <view v-else class="div amount-wrapper">
                <view class="div common-btn ds-button-large" @click="checkout">提交订单</view>
            </view>
        </view>
        <view class="div bottom-wrapper" v-else>
            <view class="div amount-wrapper">
                <view class="div common-btn ds-button-large" >该地区不可购买，请更换收货地区</view>
            </view>
        </view>
        <uni-popup background-color="#fff" ref="togglePay" type="right" >
            <view :style="'width:'+screenWidth+'px'" class="common-popup-wrapper">
            <view class="div common-header-wrap">
                <view :style="'height:'+navHeight+'px'"></view>
                <view class="common-header-holder"></view>
                <view class="common-header-fixed">
                <title-header />
                <uni-nav-bar title="付款方式" class="common-header" left-icon="back" @clickLeft="hidePopup('togglePay')">
                </uni-nav-bar>
            </view>
            </view>
            <view class="div common-popup-content">
				<scroll-view style="position: absolute;top:0;right:0;left:0;bottom:0" scroll-y="true">
                <radio-group @change="radioChange(1,$event)" class='radio-wrapper'>
                  <view class='radio-item' v-for="(item, index) in pay_options" :key="index">
                    <radio :value="item.value" :checked="pay_code==item.value" />
                    <text>{{item.label}}</text>
                  </view>
                </radio-group>
				</scroll-view>
            </view>
        </view>
        </uni-popup>
        <uni-popup background-color="#fff" ref="togglePresell" type="right" >
            <view :style="'width:'+screenWidth+'px'" class="common-popup-wrapper">
            <view class="div common-header-wrap">
                <view :style="'height:'+navHeight+'px'"></view>
                <view class="common-header-holder"></view>
                <view class="common-header-fixed">
                <title-header />
                <uni-nav-bar title="支付金额" class="common-header" left-icon="back" @clickLeft="hidePopup('togglePresell')">
                </uni-nav-bar>
            </view>
            </view>
            <view class="div common-popup-content">
				<scroll-view style="position: absolute;top:0;right:0;left:0;bottom:0" scroll-y="true">
                <radio-group @change="radioChange(2,$event)" class='radio-wrapper'>
                  <view class='radio-item' v-for="(item, index) in presell_options" :key="index">
                    <radio :value="item.value" :checked="presell_pay==item.value" />
                    <text>{{item.label}}</text>
                  </view>
                </radio-group>
                <view class="div desc-text">定金下单后，若非商城或商家责任，定金恕不退还</view>
				</scroll-view>
            </view>
        </view>
        </uni-popup>
        <uni-popup background-color="#fff" ref="mallvoucherVisible" type="right" >
            <view :style="'width:'+screenWidth+'px'" class="common-popup-wrapper">
                <view class="div common-header-wrap">
                    <view :style="'height:'+navHeight+'px'"></view>
                    <view class="common-header-holder"></view>
                    <view class="common-header-fixed">
                    <title-header />
                    <uni-nav-bar title="平台代金券" class="common-header" left-icon="back" @clickLeft="hidePopup('mallvoucherVisible')">
                        <view class="div common-btn btn" slot="right" @click="selectMallVoucher('')">不使用</view>
                    </uni-nav-bar>
                </view>
                </view>
                <view class="div common-popup-content">
                    <scroll-view style="position: absolute;top:0;right:0;left:0;bottom:0" scroll-y="true">
                    <view class="div common-voucher common-voucher02"  v-for="(item,index) in myMallVoucher" :key="item.mallvoucheruser_id" @click="selectMallVoucher(item)">
                        <view class="div par"><view class="p">订单满{{item.mallvoucheruser_limit}}元</view><text class="sub sign">￥</text><text class="span">{{item.mallvoucheruser_price}}</text></view>
                        <view class="div copy">有效期至<view class="p"><br>{{$moment.unix(item.mallvoucheruser_enddate).format('YYYY.MM.DD')}}</view></view>
                        <text class="i"></text>
                    </view>
                    </scroll-view>
                </view>
            </view>
        </uni-popup>
    </view>
<uni-popup background-color="#fff" ref="confirm" type="dialog">
    <uni-popup-dialog :mode="dialog.mode" :title="dialog.title" :content="dialog.content" :placeholder="dialog.content" @confirm="confirmDialog" @close="closeDialog"></uni-popup-dialog>
</uni-popup>
</member-base>
</template>

<script>
import {getFontSize} from '@/util/common'
import TitleHeader from '../../TitleHeader'
import { urlencode } from '@/util/common'
import MemberBase from '../MemberBase'
import { buyStep1, buyStep2, checkFCode } from '../../../api/memberBuy'
import CheckoutAddress from './child/CheckoutAddress'
import CheckoutStore from './child/CheckoutStore'

import flexLine from '../../flexLine'
export default {
  name: 'Step1',
  components:{
    TitleHeader,
    MemberBase,
    flexLine,
    CheckoutAddress,
    CheckoutStore
  },
  computed:{
  fontSize(){
    return getFontSize()
  },
  },
  data(){
    return {
      addAddress:false,
    navHeight: 0,
    dialog:{},
    option:{},
    buy_now:0,
      pintuan_id:0,
      pintuangroup_id:0,
    bargainorder_id:0,
      screenWidth:0,
      presell_pay: '1',
      pay_name: '在线付款',
      pay_code: 'online',
      pay_options: [{
        label: '在线付款',
        value: 'online'
      }, {
        label: '货到付款',
        value: 'offline'
      }],
      presell_options: [{
        label: '全额支付',
        value: '1'
      }, {
        label: '先付定金',
        value: '2'
      }],
      pay_list: { online: '在线付款', offline: '货到付款' },
      hidePay: false,
      f_code: '',
      invoice_id: 0,
      invoice_content: '',
      f_code_check: false,
      cart_id: '',
      store_final_total_list: null,
      message: [],
      chain_goods: [],
      myMallVoucher: [],
      myMallVoucherprice:'不使用',
      mall_voucher_info:'',
    }
  },
  watch: {
    pay_code: function (pay_code) {
      this.pay_name = this.pay_list[pay_code]
      this.hidePopup('togglePay')
      if (pay_code == 'offline' && !this.store_final_total_list.pay_goods_list.online) {
        this.hidePay = true
      } else {
        this.hidePay = false
      }
    }
  },
  onLoad: function (option) {
    this.invoice_id=option.invoice_id ? option.invoice_id : 0
      this.invoice_content=option.invoice_content ? option.invoice_content : ''
      this.cart_id=option.cart_id ? option.cart_id : ''
      this.bargainorder_id=option.bargainorder_id
      this.buy_now=option.buy_now
      this.pintuan_id=option.pintuan_id
      this.pintuangroup_id=option.pintuangroup_id
      this.option=option
  },
  onShow(){
    this.getBuyInfo()
  },
  mounted(){
  
    // #ifdef  MP-WEIXIN
  
    this.navHeight = uni.getMenuButtonBoundingClientRect().height
  
    // #endif
  
    this.screenWidth=uni.getSystemInfoSync().screenWidth
  
  },
  methods:{
    radioChange(i,e){
      switch(i){
        case 1:
        this.pay_code=e.detail.value
        break
        case 2:
        this.presell_pay=e.detail.value
        break
        
      }
      
    },
    closeDialog(){
    },
    confirmDialog(value){
    },
    goNavigate(path,query=false){
      uni.navigateTo({url:path+(query?('?'+urlencode(query)):'')})
    },

    showPopup(id){
      this.$refs[id].open()
    },
    hidePopup(id){
      this.$refs[id].close()
    },
    checkfcode () {
      checkFCode(this.store_final_total_list.store_cart_list_api[0].goods_list[0].goods_commonid, this.f_code).then(res => {
        this.f_code_check = true
      }).catch(function (error) {
        uni.showToast({icon:'none',title: error.message})
      })
    },
    // 获取订单信息
    getBuyInfo () {
      let extra = {}
      if (this.bargainorder_id) {
        extra['bargainorder_id'] = this.bargainorder_id
      }
      buyStep1(
        this.cart_id, this.buy_now ? 0 : 1, this.pintuan_id, this.pintuangroup_id, extra
      ).then((res) => {
        if (res.code === 10000) {
          this.store_final_total_list = res.result
          this.myMallVoucher = res.result.mall_voucher_list
          this.addAddress=true
          if (this.invoice_content) {
            if (!this.store_final_total_list.inv_info.invoice_id) {
              this.invoice_id = 0
              this.invoice_content = this.store_final_total_list.inv_info.invoice_title
            }
          } else {
            this.invoice_content = this.store_final_total_list.inv_info.invoice_title
            if (this.store_final_total_list.inv_info.invoice_id) {
              this.invoice_id = this.store_final_total_list.inv_info.invoice_id
            }
          }
        } else {

        }
      }).catch(function (error) {
        uni.showToast({icon:'none',title: error.message})
      })
    },
    goBack () {
      uni.navigateBack({delta:1})
    },
    selectVoucher (voucherInfo, store_id) {
      this.store_final_total_list.store_cart_list[store_id].store_voucher_info = voucherInfo
    },
    selectMallVoucher (voucherInfo) {
      this.hidePopup('mallvoucherVisible')
      this.mall_voucher_info = voucherInfo
      if(this.mall_voucher_info){
          this.myMallVoucherprice = this.mall_voucher_info.mallvoucheruser_price + '元'
      }else{
          this.myMallVoucherprice = '不使用'
      }
    },
    selectChain (chain,store_id) {
        this.store_final_total_list.store_cart_list[store_id].chain_goods = chain[store_id]
    },

    goAddress () {
      if (this.store_final_total_list.address_info) {
        uni.navigateTo({ url: '/pages/member/address/AddressList' })
      } else {
        this.addAddress=false
        uni.navigateTo({ url: '/pages/member/address/AddressForm'+'?'+urlencode( { action: 'add',isFromCheckout: true,goBackLevel: 2 })})
        
      }
    },
    changeMessage (message, store_id) {
      this.message[store_id] = message
    },
    // 提交订单
    checkout () {
      let ifcart = this.buy_now ? 0 : 1
      let pintuan_id = this.pintuan_id
      let pintuangroup_id = this.pintuangroup_id
      let cart_id = this.cart_id
      let address_id = this.store_final_total_list.address_info ? this.store_final_total_list.address_info.address_id : 0
      let vat_hash = this.store_final_total_list.vat_hash
      let offpay_hash = this.store_final_total_list.address_api.offpay_hash
      let offpay_hash_batch = this.store_final_total_list.address_api.offpay_hash_batch
      let invoice_id = this.invoice_id
      let voucher = null
      let mallvoucher = null
      let chaininfo= null
      let pay_message_temp = []
      let f_code = this.f_code
      let pay_code = this.pay_code
      if (!address_id) {
        this.dialog={content:'您需要先去添加收货地址'}
        this.$refs.confirm.open()
        return
      }

      // 处理格式
      voucher = ''
      let voucher_temp = []
      for (var t in this.store_final_total_list.store_cart_list) {
        voucher_temp.push([this.store_final_total_list.store_cart_list[t].store_voucher_info.vouchertemplate_id + '|' + t + '|' + this.store_final_total_list.store_cart_list[t].store_voucher_info.voucher_price])
      }
      voucher = voucher_temp.join(',')
      
      mallvoucher = '|0.00'
        if(this.mall_voucher_info != ''){
            mallvoucher = this.mall_voucher_info.mallvouchertemplate_id +'|'+this.mall_voucher_info.mallvoucheruser_price
        }
        
      chaininfo = ''
        let chain_temp = []
        for (var t in this.store_final_total_list.store_cart_list) {
            if(this.store_final_total_list.store_cart_list[t].chain_goods){
               chain_temp.push([t + '|' + this.store_final_total_list.store_cart_list[t].chain_goods.chain_id]) 
            }
        }
        chaininfo = chain_temp.join(',')
      
      let i
      for (i in this.store_final_total_list.store_cart_list) {
        let message = this.message[this.store_final_total_list.store_cart_list[i].store_id]
        if (typeof (message) === 'undefined') {
          message = ''
        }
        pay_message_temp.push(this.store_final_total_list.store_cart_list[i].store_id + '|' + message)
      }
      let pay_message = pay_message_temp.join(',')
      let extra = {}
      if (this.bargainorder_id) {
        extra['bargainorder_id'] = this.bargainorder_id
      }
      extra['chain_goods'] = chaininfo
      extra['presell_pay'] = this.presell_pay
      buyStep2(
        ifcart,
        cart_id,
        address_id,
        vat_hash,
        offpay_hash,
        offpay_hash_batch,
        invoice_id,
        voucher,
        mallvoucher,
        pay_message,
        pintuan_id,
        pintuangroup_id,
        f_code,
        pay_code,
        extra
      ).then((res) => {
        // 跳转到支付界面
        let pay_sn = res.result.pay_sn
        uni.redirectTo({ url: '/pages/member/buy/pay'+'?'+urlencode( { pay_sn: pay_sn, pay_type: 'pay_new' } )})
        }).catch(error => {
        this.password = ''
        uni.showToast({icon:'none',title: error.message})
      })
    }

  }
}
</script>

<style scoped lang="scss">
    .common-header{
        .btn{background: #000;color: #fff;box-shadow: 0px 2px 4px #d2d2d2;}
    }
    .block-wrapper{background: #fff;padding:0 $pageSpace}
    .container {
        display: flex;
        flex-direction: column;
        justify-content: flex-start;
        align-items: stretch;
    }
    .header {
        height: 2.2rem;
        color: #48505d;
        font-size:$h1;
        background-color: #fff;
        padding: 0.1rem 0;
        border-bottom: 1px solid #e8eaed;
    }
    .body {
        display: flex;
        flex-direction: column;
        justify-content: flex-start;
        align-items: stretch;
        margin-bottom:4rem;
    }
    .address {
    }
    .goods {
        height: 4.5rem;
    }
    .item {
        height: 2.5rem;
    }
    .section-header {
        margin-top: 0.4rem;
    }
    .section-footer {
        margin-bottom: 0.4rem;
    }
    .comment {
        height: 7.25rem;
    }
    .desc {
        background-color: #fff;
        display: flex;
        flex-direction: column;
        justify-content: flex-start;
        align-items: stretch;
        padding-top: 0.5rem;
        padding-bottom: 0.5rem;
    }
    .desc-item {
        height: 1.5rem;
    }
    .bottom-wrapper {
        z-index: 1;
        background: #fff;
        position: fixed;
        left: 0;
        right: 0;
        bottom: 0;
        padding:.5rem 0;
        display: flex;
        flex-direction: row;
        justify-content: flex-start;
        align-items: stretch;
    }
    .amount-wrapper {
        flex: 1;
        background-color: #fff;
        margin:0 $pageSpace;
    }
    .amount {
        flex: 1;
        font-size:$h2;
        color: $primaryColor;
        text-align: right;
        padding-right: 0.75rem;
    }
    .submit {
        width: 7.5rem;
        height: 2.5rem;
        border-radius: 0;
    }
    .left-icon{float:left;font-size:$h1;margin-right:0.2rem;}
    .desc-text{font-size:$subFontSize;color: #999;padding:1rem}
	.radio-wrapper{
		display: block;
		padding: 0 $pageSpace;
		.radio-item{
			padding: .5rem 0;
			border-bottom: 1px dashed #f5f5f5;
		}
	}
    .common-voucher{margin:0.5rem auto}
</style>
