<template>
    <div v-loading="loading">
        <div class="white-box">
            <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">
                        <el-image style="width: 100px; height: 100px" :src="tool.getArImage(scope.row.COVER, '/files/')" :preview-src-list="[tool.getArImage(scope.row.COVER, '/files/')]"></el-image>
                    </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="Tax Rate" prop="TAX_RATE"><!--税率-->
                    <template slot-scope="scope">
                        <span>{{ Math.round(scope.row.TAX_RATE * 100) / 100 }}</span>
                    </template>
                </el-table-column>

                <el-table-column label="Tax" prop="tax_amount_plus"><!--税额-->
                    <template slot-scope="scope">
                        <span>{{ Math.round(scope.row.tax_amount_plus * 100) / 100 }}</span>
                    </template>
                </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>

            <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}}<!-- 详细地址 -->
                            Recipient Name：{{item.CONSIGNEE}}<!-- 收件人姓名 -->
                            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="box address_box">
                Total Orders：<!-- 订单合计 -->
                <div class="sum">
                    <div class="sum_box">
                        <div>Freight</div><!-- 运费 -->
                        <div>{{ pointFreight }} {{ unit }}</div>
                    </div>
                    <div class="sum_box">
                        <div>Amount Paid</div><!-- 实付金额 -->
                        <div>
                            <span>{{ prefixSign }} {{ pointsSum }} {{ unit }}</span>
                        </div>
                    </div>
                </div>
          </div>

            <div class="">
                <el-button type="danger"  size="small" @click="cancelOrder()">Go Back</el-button>
                <el-button type="primary" size="small" @click="goToAccounts()" :loading="submitButtonStat">Pay</el-button><!--去结算-->
            </div>
        </div>

        <!-- payStack模态框 -->
        <el-dialog title="Pay" v-if="visible" :visible.sync="visible" width="30%" v-loading="payStackLoading" :before-close="handleClose">
            <section>
                <div class="formcontainer">
                    <el-divider></el-divider>
                    <div class="container">
                        <el-form :model="form">
                            <el-form-item label="Email" label-width="100px" required>
                                <el-input v-model="form.email" autocomplete="off"></el-input>
                            </el-form-item>
                            <el-form-item label="Amount" label-width="100px" required>
                                <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"
                :metadata="form.metadata"
                :currency="form.currency"
                :paystackkey="form.publicKey"
                :reference="reference"
                :channels="channels"
                :callback="processPayment"
                :close="processClose"
            >
            <el-button type="primary" size="small">Pay</el-button>
            </paystack>
            <el-button type="danger" size="small" class="cancelButton" @click="handleClose">Cancel</el-button>
    </el-dialog>

        <!-- 倒计时页面 -->
        <el-dialog title="Tips" :visible.sync="payDialog" :show-close="false" width="350px" :close="handleOrderList">
            <el-result icon="success" title="the order is successful">
                <template slot="extra">
                    <span style="color: #008efa; font-size: 30px;">{{ countdown }}</span>
                </template>
            </el-result>
        </el-dialog>
    </div>
</template>

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

export default{
    name: 'ba-shopping-cart',
    data: function () {
        return {
            tool: tool,
            loading: true,
            goods: [],
            payList: [],
            pointsSum: '',
            cashSum: '',
            freight: '',
            pointFreight: '',
            freeShipping: '',
            goodsId: '',
            goodsNum: '',
            payPassword: '',
            submitButtonStat: false,
            prefixSign: '₦',
            unit: 'NGN',
            sn: '',
            orderType: '',
            payDialog: false,
            countdown: 5,
            visible: false,
            payType: 'pay_stack',
            payStackLoading: false,
            channels: ["card", "bank", "ussd", "qr"], // eft(南非)  mobile_money(加纳)
            form: {
                publicKey: PAY_STACK_PUBLIC_KEY,
                currency: PAY_STACK_CURRENCY,
                firstname: userInfo.userName(),
                lastname: '',
                email: userInfo.userEmail(),
                amount: 0, // kobo
                orderSn: '',
                metadata: {
                    cart_id: this.sn,
                    custom_fields: [
                        {
                            display_name: 'orderSn',
                            variable_name: 'orderSn',
                            value: this.sn,
                        },
                        {
                          display_name: 'orderType',
                          variable_name: 'orderType',
                          value: 'baOrder'
                        },
                    ]
            },
          },
            regionData: store.state.regionInfo.regionData,
            addressId: '100000000000000000',
            all_address: [],
        }
    },
    components: {
        paystack
    },
    created() {
        // 加载sessionStorage中推送的商品
        let option = sessionStorage.getItem('order_goods');
        // 加载购物车
        this.getShowCart();
        if (option) {
            let pageGoodsList = JSON.parse(option);
            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.tax_amount_plus = Math.round((pageData.member_price - pageData.member_price / (1 + pageData.TAX_RATE / 100)) * pageData.chose_num * 100) / 100;
                        this.goods.push(pageData)
                    }
                })
            }
            // 计算价格
          this.getSumMoney();
        }
    },
    computed: {
        // PayStack混淆串
        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: {
        // 取消订单
        cancelOrder() {
            history.go(-1)
        },
        // 设置运费
        setFreight() {
            // 如果地址为自提，则运费为0
            this.pointFreight = (this.addressId === '100000000000000000') ? Number(0) : Number(this.freight);
        },
        // 表格合并
        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() {
            this.submitButtonStat = true
            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 = {
                    goodsId: this.goodsId,
                    goodsNum: this.goodsNum,
                    payPassword: this.payPassword,
                    email: this.form.email,
                    addressId: this.addressId,
                    address: this.address,
                };

                // PayStack支付
                return network.postData('shop/ba-sure-approach-order', params).then(response => {
                    this.submitButtonStat = false;
                    this.form.orderSn = response.SN;
                    this.form.amount = this.cashSum;
                    this.form.metadata.custom_fields[0].value = response.SN;
                    this.visible = true;
                }).catch(_ => {
                    this.submitButtonStat = false;
                });
            }).catch(_ => {
                this.submitButtonStat = false;
            });
        },
        // 计算价格
        getSumMoney () {
            let cash_plus_sum = [];
            let goodsId = [];
            let goodsNum = [];
            let choseNum = 0;
            this.goods.map(item => {
                choseNum = Number(item.chose_num);
                if (choseNum > 0) {
                    cash_plus_sum.push(item.SELL_PRICE * choseNum * (item.DISCOUNT / 100));
                    goodsId.push(item.ID);
                    goodsNum.push(choseNum);
                }
            })
            this.goodsNum = goodsNum;
            this.goodsId = goodsId;
            // 增加运费
            let payAmount = tool.sum(cash_plus_sum);
            // 设置运费
            this.setFreight();
            // 商品总价大于预定值,免运费
            this.pointFreight = (this.pointFreight > 0) ? ((payAmount >= this.freeShipping) ? 0 : this.freight) : 0
            // 计算总价
            this.pointsSum = this.cashSum = this.form.amount = tool.formatPrice(tool.sum(cash_plus_sum) + this.pointFreight) ;
        },
        // 展示购物车信息
        getShowCart () {
            network.getData('shop/ba-shopping-cart', {}).then(response => {
                this.loading = false;
                // 免运费阈值
                this.freeShipping = response.freeShipping;
                // 运费
                this.freight = response.freight;
                // 收货地址
                this.all_address = response.allAddress;
                this.all_address.map((item, index) => {
                    if (item.IS_DEFAULT === 1) {
                        this.addressId = item.ID
                    }
                })
            }).catch(_ => {
                this.loading = false;
            })
        },
        // 选择收货地址
        choseAddress (addressId) {
            this.addressId = addressId;
            // 设置运费
            this.setFreight()
            // 计算价格
            this.getSumMoney()
        },
        // 关闭支付回调
        handleClose() {
            let _this = this
            _this.$confirm('Confirm to close?').then(_ => {
                return network.postData('shop/ba-delete-approach-order', { orderSn: this.form.orderSn }).then(_ => {
                    // 关闭支付模态框
                    _this.visible = false
                    // 关闭购物车页面,返回到订单列表页
                    sessionStorage.setItem('order_goods', null)
                    this.$router.push({path: `/shop/ba-product-list`})
                })
            }).catch(_ => {
                // 关闭支付模态框
                _this.visible = false
                // 关闭购物车页面,返回到订单列表页
                sessionStorage.setItem('order_goods', null)
                this.$router.push({path: `/shop/ba-product-list`})
            })
        },
        // 支付成功回调
        processPayment() {
            // 关闭支付页面
            this.visible = false
            this.payStackLoading = false
            // 显示支付成功模态框
            this.payDialog = true;
            // 启动支付成功倒计时
            this.handleCountdown()
        },
        // 关闭支付回调
        processClose () {
            // 关闭支付模态框
            this.visible = false
            // 关闭购物车页面,返回到订单列表页
            sessionStorage.removeItem('order_goods')
            this.$router.push({path: `/shop/ba-product-list`})
        },
        // 倒计时结束跳转
        handleOrderList () {
            this.$router.push({path: `/shop/ba-order-list`})
        },
        // 启动倒计时
        handleCountdown () {
            // 创建定时器
            setInterval(() => {
                // 每隔1秒把time的值减一，赋值给span标签
                this.countdown--
                if (this.countdown === 0) {
                    // 倒计时结束,跳转到订单列表
                    this.$router.push({path: `/shop/ba-order-list`});
                }
            }, 1000)
        },
    },
}
</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>
