<template>
  <div>
    <main id="main">
      <section id="cart">
        <div class="container mt30">
          <el-table v-loading="loading" :data="tools" ref="multipleTable" @selection-change="handleSelectionChange">
            <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" :show-overflow-tooltip="true">
              <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" width="100"
                             :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" width="100"
                             :show-overflow-tooltip="true">
              <template slot-scope="scope">
                <span>{{scope.row.price}}元</span>
              </template>
            </el-table-column>
            <el-table-column label="订单总金额" align="center" width="100" :show-overflow-tooltip="true">
              <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="200">
              <template slot-scope="scope">
                <span>{{ parseTime(scope.row.createTime) }}</span>
              </template>
            </el-table-column>
            <el-table-column
              label="操作"
              align="center"
              width="160"
              class-name="small-padding fixed-width"
            >
              <template slot-scope="scope">
                <router-link :to="'/test/tool/detail/'+ scope.row.toolId" class="link-type">
                  <el-button
                    size="mini"
                    type="text"
                    icon="el-icon-edit"
                  >商品详情
                  </el-button>
                </router-link>
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-remove"
                  @click="handleRemove(scope.row)"
                >移除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <div class="counter">
            <p>所选商品总金额：{{totalFee | currency('￥')}}</p>
            <button type="submit" class="btn btn-primary btn-yellow" @click="multipleRemove">移除</button>
            <button type="submit" class="btn btn-primary btn-yellow" @click="clearCart()">清空购物车</button>
          </div>
          <div class="cl"></div>
          <ul>
            <li>
           <input type="radio" v-model="payType" name="payType" value="ali"/> <img src="@/assets/pic/alipay.png"><br><span>支付宝支付</span>
            </li>
            <li>
             <input type="radio" v-model="payType" name="payType" value="wx"/> <img src="@/assets/pic/wechat.png"><br><span>微信支付</span>
            </li>
          </ul>
          <div class="cl"></div>
          <button type="submit" class="btn btn-primary pay" @click="pay">立即支付</button>
          <div v-show="boxShow" class="qcode">
            <p>
              <span style="display: none"><canvas width="150px" height="150px"></canvas></span>
              <span id="qrcode" ref="qrcode"></span>
              <span>扫描微信二维码支付</span>
            </p>
          </div>
        </div>

        </section>
      </main>
  </div>
</template>

<script>
  import {getMyShoppingCart, removeShoppingCart, multipleRemove, clearCart} from "@/api/my/my";
  import {buyTools, noPayMore, queryOrderState} from "@/api/toolInfo/market";
  import alipayImg from '@/assets/images/alipay.jpg';
  import wxpayImg from '@/assets/images/wxpay.jpg';
  import QRCode from 'qrcodejs2'
  import store from "@/store";

  export default {
    name: "MyShoppingCart",
    data() {
      return {
        loading: false,
        payType: 'ali',
        tools: [],
        toolIds: [],
        alipayImg: alipayImg,
        wxpayImg: wxpayImg,
        codeUrl: undefined,
        boxShow: false,
        orderNumber: ''
      }
    },
    created() {
      this.list();
    },
    methods: {
      list() {
        getMyShoppingCart().then(response => {
          this.tools = response.rows;
          this.$nextTick(() => {
            for (let i = 0; i < this.tools.length; i++) {
              this.$refs.multipleTable.toggleRowSelection(this.tools[i])
            }
          })
          store.commit('SET_CARTCOUNT',  this.tools.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);
      },
      multipleRemove() {
        if (this.toolIds.length == 0) {
          this.$alert("请您选择要移除的商品", {dangerouslyUseHTMLString: true});
        } else {
          this.$confirm('确定要移除所选的商品吗？', '提示', {type: 'warning'}).then(
            () => {
              multipleRemove(this.toolIds).then(response => {
                this.list();
              })
            })
        }
      },
      clearCart() {
        this.$confirm('确定要清空购物车吗？', '提示', {type: 'warning'}).then(
          () => {
            clearCart().then(response => {
              this.list();
            })
          })
      },
      pay() {
        let ids = this.toolIds;
        let tools = this.tools;
        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'
              });
              this.list();
            })
          } else {
            if (this.payType == 'ali') {
              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;
                document.getElementById("qrcode").innerHTML = ""; //获取生成二维码后显示的容器的ID
                let self = this
                this.qrCode = new QRCode('qrcode', {
                  width: 150,                     //二维码的宽度
                  height: 150,                    //二维码的高度
                  text: this.codeUrl,            //调用weixincode()方法时后台传的code
                  colorDark: '#000',              //二维码颜色
                  colorLight: '#fff',  //二维码底色
                  textAlign:'center'
                })
                self.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;
              this.list();
              clearInterval(this.timers) //别忘记关闭定时器，否则会一直调这个接口
            }
          })
          if (num == 500) { //这里是判断num++到500的情况下用户还没有支付则自动关闭定时器和二维码
            this.boxShow = false
            clearInterval(this.timers)
          }
        }, 1500)
      },

// 还有一步是最容易被忽略的 跳转页面的时候也应该关闭定时器

      beforeDestroy() {
        if (this.timers) {
          clearInterval(this.timers); //关闭
        }
      }

// 用这个方法监听定时器是否关闭，跳转页面时触发，步骤还是挺繁琐的，不过还是顺利解决

    },
    computed: {
      totalFee: function () {
        let ids = this.toolIds;
        let tools = this.tools;
        if (tools.length == 0)
          return 0;
        else {
          let totalFee = 0;
          for (let i in ids) {
            let tool = tools.filter(function (item) {
              return item.toolId == ids[i];
            })
            if (tool.length != 0)
              totalFee += tool[0].price * tool[0].amount;
          }
          return totalFee;
        }
      }
    }
  }
</script>

<style scoped>
  .buttonContainer {
    margin-top: 5px;
    float: right;
  }
</style>
