<template>
  <div>
      <div v-loading="loading">
          <div class="white-box">
              <div class="table">
                  <el-table
                    :data="goods"
                    style="width: 100%"
                    show-summary
                    :summary-method="getSummaries">
                     <el-table-column label="Product Name" prop="GOODS_NAME"><!--商品名称-->
                    </el-table-column>

                    <el-table-column label="Product picture" ><!--图片-->
                        <template slot-scope="scope">
                            <img :src="scope.row.COVER" alt="" style="width:100%">
                        </template>
                    </el-table-column>

                    <el-table-column label="Product price" prop="member_price"><!--商品价格-->
                        <template slot-scope="scope">
                            <span>{{ Math.round(scope.row.member_price * 100) / 100 }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="Member BV" prop="member_pv" v-if="category_type === 1"><!--会员PV-->
                        <template slot-scope="scope">
                            <span>{{ Math.round(scope.row.member_pv * 100) / 100 }}</span>
                        </template>
                    </el-table-column>
<!--                    <el-table-column label="库存" prop="STORE_NUMS">-->
<!--                    </el-table-column>-->

                    <el-table-column label="Quantity" prop="chose_num"><!--数量-->

                    </el-table-column>
                    <el-table-column label="Total Amount" prop="member_price_plus"><!--合计金额-->
                        <template slot-scope="scope">
                            <span>{{ Math.round(scope.row.member_price_plus * 100) / 100 }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="Total BV" prop="member_pv_plus" v-if="category_type === 1"><!--合计PV-->
                        <template slot-scope="scope">
                            <span>{{ Math.round(scope.row.member_pv_plus * 100) / 100 }}</span>
                        </template>
                    </el-table-column>
                  </el-table>
              </div>
              <div class="address_box">
                Please select the shipping address：	<!--  请选择收货地址 -->
                <el-radio-group v-model="addressId" @change='choseAddress'>
                    <div v-for="(item , index) in all_address" :key='index' class="address">
                        <el-radio :label="item.ID" >
                          Full address：{{item.ADDRESS}} {{item.CITY_NAME}} {{item.LGA_NAME}} {{item.PROVINCE_NAME}}  &nbsp;&nbsp;&nbsp;&nbsp;
                          <!-- 详细地址 -->  &nbsp;&nbsp;
                          <!-- 收件人姓名 -->  Recipient name：{{item.CONSIGNEE}}&nbsp;&nbsp;&nbsp;&nbsp;
                           <!-- 手机号码 --> Phone number：{{item.MOBILE}}
                        </el-radio>
                    </div>
                    <div class="address">
                      <el-radio label="100000000000000000">Self Pick-up</el-radio><!--自提-->
                    </div>
                </el-radio-group>
              </div>
              <div class="address_box">
                Please select payment method：<!-- 请选择支付方式 -->
                <el-radio-group v-model="payType" @change='chosePayType'>
                    <div v-for="(item, index) in payList" :key='index' class="address">
                        <el-radio :label="item.label">{{ item.name }}</el-radio>
                    </div>
                </el-radio-group>
              </div>

              <div class="box address_box">
                Total orders：<!-- 订单合计 -->
                  <div class="sum">
                    <div class="sum_box" v-if="category_type === 1">
                        <div>Freight</div><!-- 运费 -->
                        <div><span v-if="category_type === 1">{{ prefixSign }}</span> {{ payType === "cash" ? freight : pointFreight }} <span v-if="category_type === 1">{{ unit }}</span></div>
                    </div>
                    <div class="sum_box">
                        <div>Amount paid</div><!-- 实付金额 -->
                        <div><span v-if="category_type === 1">{{ prefixSign }}</span> {{ payType === "cash" ? cashSum : pointsSum }} <span v-if="category_type === 1">{{ unit }}</span></div>
                    </div>
                  </div>
              </div>

              <div class="box address_box">
                Account Balance：	<!-- 账户余额 -->
                <div class="sum">
                    <div v-if="category_type === 1">
<!--                        <div class="sum_box">-->
<!--                            <div>账户积分</div>-->
<!--                            <div>{{ balance.points }}</div>-->
<!--                        </div>-->
                        <div class="sum_box">
                            <div>Account Balance</div><!-- 账户余额 -->
                            <div>$ {{ balance.cash }} US</div>
                        </div>
                        <div class="sum_box">
                            <div>Exchange points</div><!-- 兑换点数 -->
                            <div>{{ balance.exchange }}</div>
                        </div>
                    </div>

                    <div v-if="category_type === 4">
                        <div class="sum_box">
                            <div>Travel bonus</div><!-- 旅游积分 -->
                            <div>{{ balance.travel_points }}</div>
                        </div>
                    </div>

                    <div v-if="category_type === 5">
                        <div class="sum_box">
                            <div>Car bonus</div><!-- 名车积分 -->
                            <div>{{ balance.car_points }}</div>
                        </div>
                    </div>

                    <div v-if="category_type === 6">
                        <div class="sum_box">
                            <div>House bonus</div><!-- 豪宅积分 -->
                            <div>{{ balance.house_points }}</div>
  			</div>
                        </div>
                    </div>
                </div>

                <div>
                    <el-button type="primary" @click="goToAccounts()" :loading="submitButtonStat">Settle accounts</el-button><!--去结算-->
                </div>
              </div>
          </div>

        <el-dialog title="订单支付" v-if="visible" :visible.sync="visible" width="30%" v-loading="payStackLoading" :before-close="handleClose">
            <section>
                <h1>Lorem Ipsum Dolor Sit Amet</h1>
                <div class="formcontainer">
                    <el-divider></el-divider>
                    <div class="container">
                        <el-form :model="form">
                            <el-form-item label="Email" label-width="120px">
                                <el-input v-model="form.email" autocomplete="off" readonly></el-input>
                            </el-form-item>
                            <el-form-item label="Amount" label-width="120px">
                                <el-input v-model="form.amount" autocomplete="off" readonly></el-input>
                            </el-form-item>
                        </el-form>
                    </div>
                </div>
            </section>

            <paystack
                :firstname="form.firstname"
                :lastname="form.lastname"
                :amount="form.amount * 100"
                :email="form.email"
                :currency="form.currency"
                :paystackkey="form.publicKey"
                :reference="reference"
                :callback="processPayment"
                :close="processClose"
            >
                <el-button type="primary" size="small">支 付</el-button>
            </paystack>
        </el-dialog>
    </div>
</template>

<script>
 import network from '@/utils/network'
 import tool from '@/utils/tool'
 import userInfo from '@/utils/userInfo'
 import { PAY_STACK_PUBLIC_KEY, PAY_STACK_CURRENCY } from '@/utils/config'
 import paystack from 'vue-paystack'

    export default{
        name:'order',
        data(){
            return{
                loading: true,
                goods:[],
                payList:[],
                all_address:[],
                balance:{},
                addressId:'',
                payType:'',
                payTypeId: '',
                pointsSum:'',
                cashSum:'',
                freight:'',
                pointFreight:'',
                goodsId:'',
                goodsNum:'',
                payPassword:'',
                submitButtonStat:false,
                category_type: '',
                prefixSign: '$',
                unit: 'US',

                visible: false,
                payStackLoading: false,
                form: {
                    publicKey: PAY_STACK_PUBLIC_KEY,
                    currency: PAY_STACK_CURRENCY,
                    firstname: userInfo.userName(),
                    lastname: '',
                    email: userInfo.userEmail(),
                    amount: 0,  // kobo
                    orderSn: '',
                },
            }
        },
        components: {
            paystack
        },
        created(){
            let option= sessionStorage.getItem('order_goods');
            this.category_type = parseInt(sessionStorage.getItem('category_type'))
            this.getShowCart();
            if(option){
                let pageGoodsList=JSON.parse(option);
                // console.log(pageGoodsList);
                let pageList;
                for( let i in pageGoodsList ) {
                    pageList =  pageGoodsList[i];
                    if (!pageList) continue;

                    pageList.map((pageData, index)=>{
                        if( Number(pageData.chose_num) > 0 ) {
                            let discount = pageData.DISCOUNT / 100;
                            pageData.member_price = Math.round(pageData.SELL_PRICE * discount * 100) / 100;
                            pageData.member_price_plus = Math.round(pageData.SELL_PRICE * Number(pageData.chose_num) * discount * 100) / 100;

                            pageData.member_pv = Math.round(pageData.PRICE_PV * discount * 100) / 100;
                            pageData.member_pv_plus = Math.round(pageData.PRICE_PV * Number(pageData.chose_num) * discount * 100) / 100;

                            this.goods.push(pageData)
                        }
                    })
                }

                this.getSumMoney();
            }
        },
        computed: {
            reference() {
                let text = "";
                let possible =
                    "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
                for (let i = 0; i < 10; i++)
                    text += possible.charAt(Math.floor(Math.random() * possible.length));
                return text;
            }
        },
        methods:{
            setFreight(){
              if(this.addressId=='100000000000000000'){//如果地址为自提，则运费为0
                this.pointFreight = this.freight = 0;
              }
            },
            getSummaries(param) {
              const { columns, data } = param;
              const sums = [];
              columns.forEach((column, index) => {
                if (index === 0) {
                  sums[index] = 'Total';// 合计
                  return;
                }
                const values = data.map(item => Number(item[column.property]));
                if ((!values.every(value => isNaN(value))) && [4, 5, 6].includes(index)) {
                  sums[index] = values.reduce((prev, curr) => {
                    const value = Number(curr);
                    if (!isNaN(value)) {
                      return Math.round((prev + curr) * 100) / 100;
                    } else {
                      return Math.round(prev * 100) / 100;
                    }
                  }, 0);
                }
              });

              return sums;
            },
            goToAccounts(){
                let amountBalance = 0
                // 前置判断余额是否够支付
                if (this.category_type === 1) {
                    if (this.payType === 'cash') {
                        amountBalance = this.balance.cash
                    } else if (this.payType === 'exchange') {
                        amountBalance = this.balance.exchange
                    }
                    // amountBalance = (this.payType === 'cash') ? this.balance.cash : this.balance.exchange
                } else if (this.category_type === 4) {
                    amountBalance = this.balance.travel_points
                } else if (this.category_type === 5) {
                    amountBalance = this.balance.car_points
                } else if (this.category_type === 6) {
                    amountBalance = this.balance.house_points
                }

                // 提示信息
                let tips = 'Balance' //余额
                if (this.payType !== 'cash' && this.payType !== 'pay_stack') {
                    let payObj = this.payList.find((item) => {
                        return item.label === this.payType
                    })
                    tips = (payObj.length <= 0) ? '' : payObj.name
                }

                // 余额是否充足
                if ((amountBalance > 0) && (this.payType !== 'pay_stack') && ((amountBalance - this.cashSum) < 0)) {
                    let tips = this.payList[this.payType] ? this.payList[this.payType].label : 'Balance'
                    this.$message({
                        message: tips + ' insufficient, unable to buy products', // 不足，无法购买商品
                        type: 'error'
                    })
                    this.submitButtonStat = false
                    return false
                }

                this.submitButtonStat = true
                // let path = 'sure-order'
                this.$prompt('Please enter your payment password', 'Hint', {//'请输入支付密码', '提示'
                    confirmButtonText: 'Confirm',//确定
                    cancelButtonText: 'Cancel',//取消
                    inputType: 'password',
                    inputPattern: /\S+/,
                    inputErrorMessage: 'Please enter your payment password'//请输入支付密码
                }).then(({value}) => {
                    this.payPassword = value
                    let params = {
                        addressId: this.addressId,
                        payType: this.payType,
                        goodsId: this.goodsId,
                        goodsNum: this.goodsNum,
                        payPassword: this.payPassword,
                        email: this.form.email,
                    }
                    return network.postData('shop/sure-order', params).then((response) => {
                        this.submitButtonStat = false

                        // PayStack支付
                        if (this.payType === 'pay_stack') {
                            this.form.orderSn = response.SN
                            this.form.amount = this.cashSum
                            this.visible = true
                        } else {
                            // 非PayStack支付
                            this.$router.go(-1)
                            this.$router.push({path: `/shop/order-list`})
                        }
                    }).catch((response) => {
                        this.submitButtonStat = true
                    })
                }).catch(() => {
                    this.submitButtonStat = false
                })
            },
            getSumMoney(){
                // let points_plus_sum=[];
                let cash_plus_sum=[];
                let goodsId=[];
                let goodsNum=[];
                let choseNum = 0;
                this.goods.map((item,index)=>{
                    choseNum = Number(item.chose_num);
                    if( choseNum > 0 ) {
                        // points_plus_sum.push(item.SELL_PRICE * choseNum);
                        cash_plus_sum.push(item.SELL_PRICE * choseNum*(item.DISCOUNT/100));
                        goodsId.push(item.ID);
                        goodsNum.push(choseNum);
                    }
                })
                this.goodsNum=goodsNum;
                this.goodsId=goodsId;
                //增加运费03-12yuan
                let payAmount = tool.sum(cash_plus_sum);
                // let payPointAmount = tool.sum(points_plus_sum);

                // 只有普通商品有运费
                if (this.category_type === 1) {
                    if(payAmount>=300){
                        this.pointFreight = this.freight = 0;
                    }else{
                        this.pointFreight = this.freight = 15;
                    }
                    this.setFreight();
                }
                // if(payPointAmount>=300){
                //     this.pointFreight = 0;
                // }else{
                //     this.pointFreight = 15;
                // }
                //console.log('points_plus_sum',points_plus_sum);
                //console.log('cash_plus_sum',cash_plus_sum);
                // this.pointsSum=tool.formatPrice(tool.sum(points_plus_sum) + this.pointFreight);
              this.pointsSum = this.cashSum = this.form.amount = tool.formatPrice(tool.sum(cash_plus_sum) + this.freight) ;
            },
            getShowCart(){
                network.getData('shop/show-cart', { categoryType: this.categoryType })
                .then(response => {
                    this.loading = false
                    // 收货地址
                    this.all_address = response.allAddress;
                    this.all_address.map((item,index)=>{
                        if(item.IS_DEFAULT==1){
                            this.addressId = item.ID
                        }
                    })
                    // 账户
                    this.balance = response.userBalance

                    // 支付方式
                    for (let item of response.sellType) {
                        if (item.id === this.category_type) {
                            this.payList = item.sell_type
                            break
                        }
                    }

                    // 支付方式的第一项默认选中
                    this.payType = this.payList[0]
                })
            },
            // 切换支付方式
            chosePayType(type) {
                this.payType = type
            },
            choseAddress(addressId){
              this.getSumMoney()
            },
            // 关闭支付回调
            handleClose(done) {
                this.$confirm('确认关闭？').then(_ => done()).catch(_ => {});
            },
            // 支付成功回调
            processPayment(response) {
                // 支付失败
                if (response.status !== 'success') {
                    this.$message({
                        message: 'Success!',
                        type: 'error'
                    })
                    return false
                }

                this.payStackLoading = true
                // 支付成功,更新订单
                return network.postData('shop/verify-order', { sn: this.form.orderSn, remark: response }).then(_ => {
                    this.$message({
                        message: 'Success!',
                        type: 'success'
                    })

                    this.visible = false
                    this.payStackLoading = false
                    this.$router.go(-1)
                    this.$router.push({path: `/shop/order-list`})
                }).catch((err) => {
                    this.$message({
                        message: err,
                        type: 'error'
                    })
                    this.payStackLoading = false
                    return false
                })
            },
            // 关闭支付回调
            processClose() {
                this.visible = false
            }
        }
    }
</script>

<style scoped>
.address{
    /* height: 3rem; */
    line-height: 3.5rem;

}
.address_box{
     border-bottom: 1px solid #e3e3e3;
}
.sum{
    display: inline-block;
}
.box{
    margin: 1rem 0;
    display: flex;
    justify-content: flex-start;
    align-items: center;
    padding-bottom: 1rem;
}
.sum_box{
    display: flex;
    margin-left: 1rem;
}
.sum_box > div{
    line-height: 2rem;
}
.sum_box > div:nth-child(1){
    margin-right: 1rem;
}
.payButton {
    border: none;
    padding: 0;
}
</style>
