<template>
    <div style="padding-bottom:50px">
        <!-- <div style="display:flex;align-items:center">   
            <div class="dvied"></div>
            <div style="font-weight: bold;color: #333333;font-size: 18px;margin-left:10px">我的购物车</div>
        </div> -->
        <div style="background: #FFFFFF;border-radius: 4px;"> 
            <div class="cartnum">
                <el-table v-loading="loading" :data="cartdata" ref="multipleTable" @selection-change="handleSelectionChange" border>
                    <el-table-column  type="selection" width="55">
                    </el-table-column>
                    <el-table-column label="商品名称" align="center" key="name" prop="name"  :show-overflow-tooltip="true"/>
                    <el-table-column label="数量" align="center" key="amount" prop="amount" width="220px">
                        <template slot-scope="scope">
                            <el-input-number v-model="scope.row.amount" :min="1" :max="999" label="描述文字"></el-input-number>
                        </template>
                    </el-table-column>
                    <el-table-column label="规格" align="center" key="deliverType" prop="deliverType"  :show-overflow-tooltip="true">
                        <template slot-scope="scope">
                            <span>{{scope.row.deliverType=='License' ? '按月':'按次'}}</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="单价" align="center" key="price" prop="price" >
                        <template slot-scope="scope">
                            <span>{{scope.row.price}}元</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="订单总金额" align="center"  :show-overflow-tooltip="true" width="100px">
                        <template slot-scope="scope">
                            <span>{{scope.row.price * scope.row.amount}}元</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="加入购物车时间" align="center" key="createTime" prop="createTime" width="200px">
                    <template slot-scope="scope">
                        <span>{{parseTime(scope.row.createTime) }}</span>
                    </template>
                    </el-table-column>
                    <el-table-column   label="操作" align="center" width="180"  class-name="small-padding fixed-width" >
                        <template slot-scope="scope">
                            <router-link :to="'/console/mytooldetails?id='+ scope.row.toolId" class="link-type">
                                <el-button  size="mini" type="text"  icon="el-icon-edit">商品详情
                            </el-button>
                            </router-link>
                                <el-button  style="margin-left:10px" size="mini" type="text"  icon="el-icon-remove"  @click="handleRemove(scope.row)">移除
                            </el-button>
                        </template>
                    </el-table-column>
                </el-table>               
                <div class="counter">
                    <p style="font-weight: bold;margin-right:10px">所选商品总金额：
                        <span style='color:#E84C3D'> ￥{{totalFee}}</span>
                    </p>
                    <el-button  @click="multipleRemovetool">移除</el-button>
                    <el-button style="background: #F2A51A;" @click="clearCarttool()">清空购物车</el-button>
                </div>            
                <el-divider></el-divider>
                <div class="payclass">   
                    <p style="font-weight: bold;font-size:19px;margin-right:10px">支付方式：</p>
                    <el-radio v-model="paytype" label="ali">
                        <img src="/assets/personal/zhifubao.png" alt="">
                        <p style="margin-left:15px">支付宝</p>
                    </el-radio>
                    <el-radio v-model="paytype" label="wx">
                         <img src="/assets/personal/weixinzhifu.png" alt="">
                         <p style="margin-left:15px">微信</p>                     
                    </el-radio>
                    <el-button  @click="immediatepay">立即支付</el-button>
                </div>
                        <qrcode value="https://qr.alipay.com/bax06461ioqvmutyhrni55f5"  :options="options" ></qrcode>

                <el-dialog title="" :visible.sync="boxShow" width="600px" :before-close="handleClose" class="qcode">
                    <div style="width:500px;margin:0 auto;text-align:center">
                        <!-- <canvas width="150px" height="150px"></canvas>
                        <div id="qrcode" ref="qrcode"></div> -->
                        <qrcode :value="codeUrl"  :options="options" ></qrcode>
                        <div style="margin-top:20px;font-size: 16px;">扫描微信二维码支付</div>
                    </div>
                </el-dialog>
            </div>
        </div>
    </div>
</template>
<script>
    import {getMyShoppingCart, removeShoppingCart, multipleRemove, clearCart} from "@/api/my/my";
    import {buyTools, noPayMore, queryOrderState} from "@/api/toolInfo/market";
    import VueQrcode from "@xkeshi/vue-qrcode";
    import {mapGetters} from "vuex";
    // import QRCode from 'qrcodejs2'
    import store from "@/store";
    export default{
        data(){
            return{
                loading:false,
                boxShow:false,  
                cartdata:[],
                totalFee:'',
                paytype:'ali',
                toolIds: [],//勾选的工具
                orderNumber:'',//订单id
                codeUrl:'',
                options: { size: 150},
            }
        },
        mounted(){
            if(this.token){
                this.list();
            }
        },
        components:{
            'qrcode': VueQrcode,
        },
        computed: {
            ...mapGetters(['token'])
        },

        methods:{
            list() {
                getMyShoppingCart().then(response => {
                    this.cartdata = response.rows;
                    //默认都选中
                    // this.$nextTick(() => {
                    //     for (let i = 0; i < this.cartdata.length; i++) {
                    //         this.$refs.multipleTable.toggleRowSelection(this.cartdata[i])
                    //     }
                    // })
                    store.commit('SET_CARTCOUNT', this.cartdata.length);
                })
            },
            // 每一行移除功能
            handleRemove(row) {
                this.$confirm('确定要从购物车中移除吗？', '提示', {type: 'warning'}).then( () => {
                    removeShoppingCart(row.toolId).then(response => {
                        this.$notify({
                            title: '从购物车删除成功',
                            message: '',
                            align: 'center',
                            type: 'success'
                        });
                        this.list();
                    });
                })
            },
            //勾选的方法
            handleSelectionChange(selection){
                this.toolIds = selection.map(item => item.toolId);
            },
            //总移除商品按钮
            multipleRemovetool() {
                if (this.toolIds.length == 0) {
                    this.$alert("请您选择要移除的商品", {dangerouslyUseHTMLString: true});
                } else {
                    this.$confirm('确定要移除所选的商品吗？', '提示', {type: 'warning'}).then(() => {
                        multipleRemove(this.toolIds).then(response => {
                            this.list();
                        })
                    })
                }
            },
            //清空购物车
            clearCarttool() {
                this.$confirm('确定要清空购物车吗？', '提示', {type: 'warning'}).then(() => {
                    clearCart().then(response => {
                        this.list();
                    })
                })
            },
            //关闭支付弹窗
            handleClose(){
                this.boxShow=false;
                clearInterval(this.timers);
            },
            // 立即支付
            immediatepay(){

                let ids = this.toolIds;
                let tools = this.cartdata;
                if (ids.length == 0) {
                    this.$alert("请您选择要购买的商品", {dangerouslyUseHTMLString: true});
                    return;
                } else {
                    let totalFee = 0;
                    let toolArr = [];
                    for (let i in ids) {
                        let tool = tools.filter(function (item) {
                            return item.toolId == ids[i];
                        })
                        let param = {};
                        param.toolId = tool[0].toolId;
                        param.amount = tool[0].amount;
                        param.deliverType = tool[0].deliverType;
                        param.price = tool[0].price;
                        param.payType = this.paytype;
                        param.toolType = tool[0].toolType;
                        totalFee = totalFee + tool[0].price;
                        toolArr.push(param);
                    }
                    if (totalFee == 0) {
                        noPayMore(toolArr).then(response => {
                            this.$notify({
                                title: '支付成功',
                                message: '可在我的工具中查看已购买的工具',
                                align: 'center',
                                type: 'success'
                            });
                            setTimeout(() => {
                                this.$router.push('/console/mytools')
                            },1000);
                            this.list();
                        })
                    } else {
                        if (this.paytype == 'ali') {
                            // return;
                            buyTools(toolArr).then(response => {
                                // 打开新的页面进行填充html。
                                var newWindow = window.open("#", "_blank");
                                newWindow.document.write(response.data);
                                this.list();
                            })
                        } else {
                            buyTools(toolArr).then(response => {
                                this.boxShow = true;
                                this.codeUrl = response.code_url;
                                this.orderNumber = response.out_trade_no;
                                // let self = this
                                this.getOrderstate() //生成二维码的时候调用监听支付是否成功的方法
                            })
                        }
                    }
                }
            },
            getOrderstate() {
                let self = this;
                let num = 0
                self.timers = setInterval(() => { //创建一个全局的定时器
                    num++;
                    queryOrderState(this.orderNumber).then(res => {
                        if (res.data == true) { //判断 如果data.data==true就是订单支付成功
                            this.$notify({
                                title: '支付成功',
                                message: '可在我的工具中查看已购买的工具',
                                align: 'center',
                                type: 'success'
                            });
                            this.boxShow = false;
                            setTimeout(() => {
                                this.$router.push('/console/mytools')
                            },1000);
                            // this.$store.dispatch("tagsView/delView", this.$route);
                            // this.$router.push({path: "/market/market"});
                            clearInterval(this.timers) //别忘记关闭定时器，否则会一直调这个接口
                        }
                    })
                    if (num == 500) { //这里是判断num++到500的情况下用户还没有支付则自动关闭定时器和二维码
                        this.boxShow = false
                        clearInterval(this.timers)
                    }
                }, 1500)
            },
        },

    }
</script>
<style scoped>
    .dvied{
        width: 4px;
        height: 18px;
        background: #0066EB;
    }
    .cartnum>>>.el-table th{
        background-color:#F7F7F7;
        color:#666666;
        text-align:center;
    }
    .cartnum>>>.el-table td{
        text-align:center;
        background-color:#FFFFFF;
        color:#333333;
        height:60px;
    }
    .cartnum>>>.el-table--border th{
        border-right:#F7F7F7
    }
    .counter{
        display:flex;
        margin-left:70%;
        align-items: center;
        margin-top:30px;
    }
    .counter>>>.el-button{
        /* width: 80px; */
        height: 36px;
        background: #0066EB;
        border-radius: 4px;
        color:#FFFFFF
    }
    .payclass{
        width:620px;
        margin:0 auto;
        text-align:center;
        display:flex;
        align-items: center;
    }
    .payclass>>>.el-button{
        width: 130px;
        height: 36px;
        background: #F84C43;
        border-radius: 4px;
        color:#FFFFFF
    }
    .payclass>>>.el-radio{
        display:flex;
        align-items: center;
    }
    .payclass>>>.el-radio__label{
        display:flex;
        align-items: center;
    }
</style>