<template>
  <div class="app-container">
    <main id="main">
      <section id="item" class="wow fadeInUp">
        <div class="container">
          <div class="row">
            <a href="javascript:history.go(-1)">测试工具市场</a> &gt; <span>{{tool.name}}</span>
          </div>
<!--          <el-button type="primary" class="btn-blue" size="small"  @click="back" style="float: right">返回</el-button>-->
          <div class="row store">
            <div class="item-pic" ><a style="top:0px;" @click="preview(icon.fileUrl)"> <img :src="icon.fileUrl"></a></div>
            <div class="item-info">
              <h3>{{tool.name}}</h3>
              <p class="index__Feature-list-itemlist-title newline" :title="tool.toolDesc"> {{tool.toolDesc | ellipsis}} </p>
<!--              <form>-->
                <table>
                  <tr>
                    <td>工具价格</td>
                    <td class="price">{{tool.price  | currency('￥')}}</td>
                  </tr>
                  <tr>
                    <td>交付方式</td>
                    <td><span>{{tool.deliverType}}</span></td>
                  </tr>
                  <tr>
                    <td>工具类型</td>
                    <td>
                      <tool-type :type="tool.toolType" style="margin: 0px!important;"></tool-type>
                    </td>
                  </tr>
                  <tr>
                    <td>购买数量</td>
                    <td>
                      <el-input-number v-model="amount" :min="1" :max="999" label="购买数量"></el-input-number>
                    </td>
                  </tr>
                  <tr>
                    <td colspan="2">
                      <button type="submit" class="btn btn-primary" @click="buy">立即购买</button>
                      <button type="submit" class="btn btn-primary btn-yellow" @click="addToShoppingCart">加入购物车</button>
                    </td>
                  </tr>
                </table>
<!--              </form>-->
            </div>
          </div>

          <div class="tab">
            <ul class="store-menu">
              <li @click="setActive('detail')" :class=" activeTab == 'detail' ? 'curr':''"><a href="#a1" @click="goTo('#a1')">商品详情</a></li>
              <li @click="setActive('price')" :class=" activeTab == 'price' ? 'curr':''"><a href="#a2" @click="goTo('#a2')">商品定价</a></li>
              <li @click="setActive('question')" :class=" activeTab == 'question' ? 'curr':''"><a href="#a3" @click="goTo('#a3')">商品问答</a></li>
              <li v-if="tool.deliverType=='License'" @click="setActive('support')" :class=" activeTab == 'support' ? 'curr':''"><a href="#a4" @click="goTo('#a4')">服务与支持</a></li>
            </ul>
            <div class="line"></div>
          </div>

          <div id="con_a_1" class="store-info">
            <p>
              <el-carousel :interval="5000" arrow="always">
                <el-carousel-item v-for="image in detailImages">
                  <a @click="preview(image.fileUrl)">  <img :src="image.fileUrl"></a>
                </el-carousel-item>
              </el-carousel>
            </p>

            <h3 id="a1">产品简介</h3>
            <p>{{tool.toolDesc}}</p>
            <h3>主要功能</h3>
            <div class="store-pro">
              <div v-for="fun in functions">
                <h4>{{fun.title}}</h4>
                <p>{{fun.funDesc}}</p>
              </div>
            </div>
            <h3>技术亮点</h3>
            <div class="store-pro">
              <div v-for="item in highlights">
                <h4>{{item.title}}</h4>
                <p>{{item.funDesc}}</p>
              </div>
            </div>
            <h3 id="a2">商品定价</h3>
            <p class="textarea">{{tool.priceDesc}}</p>
            <h3 id="a3">商品问答</h3>
            <p class="textarea">{{tool.productQA}}</p>
            <h3 id="a4" v-if="tool.deliverType=='License'">服务与支持</h3>
            <p v-if="tool.deliverType=='License'" class="download">下载软件包<a class="btn default" href="javascript:void(-1)" @click="warnBuy">下载</a></p>
            <p v-if="tool.deliverType=='License' && readmeUrl != ''" class="download">下载安装手册<a class="btn default" href="javascript:void(-1)" @click="downloadReadme">下载</a></p>
          </div>
        </div>
      </section>
      <el-backtop :bottom="20">
        <div
          style="{
        height: 100%;
        width: 100%;
        background-color: #f2f5f6;
        box-shadow: 0 0 6px rgba(0,0,0, .12);
        text-align: center;
        line-height: 30px;
        color: #1989fa;
      }"
        >
          top
        </div>
      </el-backtop>
    </main>
    <!-- 添加或修改参数配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body @close="closeBuyDialog()">
      <el-form :model="buyTool" label-width="100px" class="demo-ruleForm">
        <el-form-item label="商品名称">
          {{buyTool.name}}
        </el-form-item>
        <el-form-item label="商品规格">
          {{buyTool.deliverType=='License' ? '按月':'按次'}}
        </el-form-item>
        <el-form-item label="商品价格">
          {{buyTool.price  | currency('￥')}}
        </el-form-item>
        <el-form-item label="购买数量">
          <el-input-number v-model="buyAmount" :min="1" :max="999" label="购买数量"></el-input-number>
        </el-form-item>
        <el-form-item label="交付方式">
          {{buyTool.deliverType}}
        </el-form-item>
        <el-form-item label="应付金额">
          {{buyTool.price * buyAmount | currency('￥')}}
        </el-form-item>
        <el-form-item label="交付方式">
          <el-row>
            <el-col :span="12">
              <el-radio v-model="payType" label="ali">支付宝支付</el-radio>
              <el-radio v-model="payType" label="wx">微信支付</el-radio>
            </el-col>
            <el-col :span="12" v-show="boxShow" style="position:absolute;left:350px;top:-150px;">
              <div style="text-align: center">
                <div id="qrcode" ref="qrcode"></div>
                　　<p>扫描微信二维码支付</p>
              </div>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item>
          <el-button type="danger" @click="pay">立即支付</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <el-image-viewer v-if="imageVisible" :on-close="closeViewer" :url-list="[dialogImageUrl]"  z-index="5000" />
  </div>
</template>

<script>
  import alipayImg from '@/assets/images/alipay.jpg';
  import wxpayImg from '@/assets/images/wxpay.jpg';
  import ElImageViewer from 'element-ui/packages/image/src/image-viewer'

  import {getTool, getFunction, queryOrderState} from "@/api/toolInfo/market";
  import {addShoppingCart} from "@/api/my/my";
  import {buyTool, noPayBuy, buyToolByWx} from "@/api/toolInfo/market";
  import ToolType from "../../components/enum/ToolType";
  import ToolInfo from "../../components/ToolInfo";
  import QRCode from 'qrcodejs2'
  import store from "@/store";

  export default {
    name: "MarketDetail",
    components: {ToolInfo, ToolType, ElImageViewer},
    data() {
      return {
        id: '',
        ImgUrl: '',
        title: '订单支付',
        open: false,
        amount: 1,
        buyAmount: 1,
        imageVisible: false,
        dialogImageUrl:'',
        payType: 'ali',
        alipayImg: alipayImg,
        wxpayImg: wxpayImg,
        tool: {},
        buyTool: {},
        detailImages: [],
        icon: {},
        functions: [],
        highlights: [],
        packageUrl:'',
        qrCode: {},
        identification: '',
        codeUrl: undefined,
        orderNumber: '',
        boxShow: false,
        activeTab: 'detail',
        readmeUrl:'',
        scrollTop:0,
        isFix:false
      }
    },
    filters: {
      ellipsis(value) {
        if (!value) return ''
        if (value.length > 100) {
          return value.slice(0, 100) + '...'
        }
        return value
      }
    },
    methods: {
    downloadReadme(){
      const loading = this.$loading({
        lock: true,
        text: '正在下载，请稍后...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      downloadFast(this.readmeUrl, loading);
    },
      setActive(tabName){
        this.activeTab = tabName;
      },
      goTo(id) {
        document.querySelector(id).scrollIntoView({
          behavior: "smooth"
        });
      },
      preview(url){
        this.dialogImageUrl = url;
        this.imageVisible = true;
      },
      closeViewer(){
        this.imageVisible = false;
      },
      handleChange(value) {
        console.log(value);
      },
      addToShoppingCart() {
        addShoppingCart(this.id, this.amount).then(response => {
          this.$notify({
            title: '添加购物车成功',
            message: '',
            align: 'center',
            type: 'success'
          });
          store.commit('SET_CARTCOUNT', response.cartCount);
        })
      },
      buy() {
        this.open = true;
        this.buyTool = this.tool;
        this.buyAmount = this.amount;
      },
      pay() {
        let param = {};
        param.toolId = this.buyTool.toolId
        param.amount = this.buyAmount;
        param.deliverType = this.buyTool.deliverType;
        param.price = this.buyTool.price;
        param.payType = this.payType;
        param.toolType = this.buyTool.toolType;
        if (param.price == 0) { //直接生成支付成功的订单
          noPayBuy(param).then(response => {
            this.$notify({
              title: '支付成功',
              message: '可在我的工具中查看已购买的工具',
              align: 'center',
              type: 'success'
            });
            this.open = false;
          })
        } else {
          if (this.payType == 'ali') {
            param.payType = 'ali';
            //支付宝支付
            // this.$router.push({path: '/buy/alipay', query:{res: data}});
            buyTool(param).then(response => {
              this.apply = response.data;
              // 打开新的页面进行填充html。
              var newWindow = window.open("#", "_blank");
              newWindow.document.write(response.data);
              // this.$nextTick(()=>{
              //   document.forms[0].submit()
              // })
              // this.$notify({
              //   title: '购买成功',
              //   message: '请在我的工具中查看',
              //   align: 'center',
              //   type: 'success'
              // });
            })
            this.open = false;
          } else {
            //微信支付，这里跳转到本文的微信支付模块的3.步骤handelPay方法
            // this.$router.push({path: '/buy/alipay', query:{res: data}});
            param.payType = "wx";
            buyTool(param).then(response => {

              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',             //二维码底色
              })
              this.boxShow = true;
              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.$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)
      },

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


      back() {
        this.$store.dispatch("tagsView/delView", this.$route);
        this.$router.push({path: "/market/market"});
      },
      warnBuy(){
        this.$alert("请您购买后在我的工具下载。")
      },
      closeBuyDialog(){
        if (this.timers) {
          clearInterval(this.timers); //关闭
        }
      },
      scrollToTop(){
        this.scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop;
      }
    },
    beforeDestroy() {
      if (this.timers) {
        clearInterval(this.timers); //关闭
      }
      // window.removeEventListener('scroll',this.scrollToTop);
    },
    // watch: {
    //   scrollTop(newVal, oldVal){
    //    // 判断是否吸顶效果
    //     if (newVal >= 40) {
    //       this.isFix = true
    //     } else {
    //       this.isFix = false
    //     }
    //   }
    // },
    // mounted () {
    //   window.addEventListener('scroll', this.scrollToTop)
    // },
    created() {
      this.id = this.$route.params && this.$route.params.id;
      getTool(this.id).then(response => {
        this.tool = response.tool;
        this.tool.amount = 1;
        this.images = response.fileInfoList;
        for (let index in this.images) {
          if (this.images[index].fileType == 'head')
            this.icon = this.images[index];
          else if (this.images[index].fileType == 'detail') {
            this.detailImages.push(this.images[index]);
          } else if (this.images[index].fileType == 'package'){
            this.packageUrl = this.images[index].fileId;
          }else if (this.images[index].fileType == 'readme'){
            this.readmeUrl = this.images[index].fileId;
          }
        }
        this.functions = response.functionList.filter(function (item) {
          return item.funType == 0;
        })
        this.highlights = response.functionList.filter(function (item) {
          return item.funType == 1;
        })
      })
    }
  }
</script>

<style scoped>
  .el-carousel {
    width: 600px;
  }

  .el-carousel__item img {
    color: #475669;
    font-size: 18px;
    opacity: 0.75;
    line-height: 300px;
    margin: 0;
  }

  .el-carousel__item:nth-child(2n) {
    background-color: #99a9bf;
  }

  .el-carousel__item:nth-child(2n+1) {
    background-color: #d3dce6;
  }
  /*.fix{*/
  /*  position: fixed;*/
  /*  left: 0;*/
  /*  top: 0;*/
  /*  z-index: 3;*/
  /*}*/
</style>
