<template>
<view>
<!--activity/bargain/kjDetail/kjDetail.wxml-->
<view class="banner">
	<image src="/activity/static/activity/images/kjban.jpg" mode="widthFix"></image>
</view>
<view class="con">
	<view class="info dflex" @tap="goPrcdetail">
		<view class="pinimgs">
			<image :src="acProduc.pic" mode="aspectFit" class="pinimg"></image>
		</view>
		<view class="pininfo flex">
			<view class="proname">{{acProduc.productName?acProduc.productName:''}}</view>
			<!-- <view class="guige">规格：15G</view> -->
			<view class="sta dflex">
				<view class="price"><text>￥</text>{{acProduc.money?acProduc.money:0}}<text class="del" v-if="acProduc.orPrice!=0&&acProduc.orPrice>acProduc.money">原价：￥{{acProduc.orPrice?acProduc.orPrice:'0'}}</text></view>
				<!-- <view class="nums">×1</view> -->
			</view>
		</view>
	</view>
	<view class="cantuan bgfff mt20 r10">
		<view class="faqir">
			<image :src="aprList.groupMainP.uavatar"></image>
			<view>{{aprList.groupMainP.unickName}}</view>
			<icon class="icon iconfont iconbaojiaquotation2"></icon><text>我想要这件好物,快来帮我砍一刀吧</text>
			<icon class="icon iconfont iconbaojiaquotation"></icon>
		</view>
		<view class="sheng dflex" v-if="!act.isJieshu || !acProduc.end">
			剩余
			<view class="sheng-time dflex">
				<!-- <block wx:if="acProduc.end">
					<text>{{timer[0]}}</text>
					<text>{{timer[1]}}</text>:
					<text>{{timer[2]}}</text>:
					<text>{{timer[3]}}</text>
				</block> -->
				<!-- <block wx:else> -->
					<block v-if="timer.length==4">
					<block v-if="timer[0] !=0"><text>{{timer[0]}}</text>天</block>
					<text>{{timer[1]}}</text>:
					<text>{{timer[2]}}</text>:
					<text>{{timer[3]}}</text>
				</block>
				<block v-else>
					<text>{{timer[0]}}</text>:
					<text>{{timer[1]}}</text>:
					<text>{{timer[2]}}</text>
				</block>
				<!-- </block> -->
			</view>
			结束
		</view>
		<view v-else class="sheng dflex">已过期</view>
		<view class="can-info">已邀{{participateCount}}人，共砍<text>¥{{bargainingMoney}}，</text>仅差<text>¥{{surplusMoney<=0?'0':surplusMoney}}</text></view>
		<view class="process">
			<view class="ing" :style="'width:' + percent + ';'"></view>
		</view>
		<block v-if="!act.isJieshu">
			<block v-if="isSuccess">
				<view class="can-btn mbglinear" @tap="confirmBuy" v-if="whether == 2&&topay==null">立即购买</view>
				<view class="can-btn mbglinear" @tap="toOrder" v-if="whether == 2&&topay!=null">查看订单详情</view>
				<view class="kai-btn" v-if="whether == 1" @tap="goUrl">我也要发起砍价</view>
			</block>
			<block v-else>
				<block v-if="isKanjia!=1">
					<button @tap="initState" class="can-btn mbglinear" v-if="whether == 2 &&isKanjia!=1">立即砍价</button>
					<view class="can-btn mbglinear" v-if="whether == 1&&isKanjia!=1" @tap="initState">帮TA砍一刀</view>
				</block>
				<block v-else>
					<button open-type="share" class="can-btn mbglinear" v-if="whether == 1">邀请好友帮TA砍价</button>
					<view class="kai-btn" v-if="whether == 1" @tap="goUrl">我也要发起砍价</view>
				</block>
				<button open-type="share" class="can-btn mbglinear" v-if="whether == 2">邀请好友砍价</button>
			</block>
		</block>
		<view v-else class="can-btn end">已过期</view>
	</view>
	<view class="detail bgfff mt20 r10">
		<view class="tab dflex">
			<view :class="'li ' + (currentTab == 0? 'on' : '')" data-current="0" @tap="tab">商品详情</view>
			<view :class="'li ' + (currentTab == 1? 'on' : '')" data-current="1" @tap="tab">砍价亲友团</view>
			<view :class="'li ' + (currentTab == 2? 'on' : '')" data-current="2" @tap="tab">活动规则</view>
		</view>
		<view :class="currentTab == 0? 'show' : 'hide'">
			<mp-html :content="nodes" lazy-load="true"></mp-html>
			<block v-if="diyNodes || diyImgs.length > 0">
				<view class="details">
					<rich-text :nodes="diyNodes" @tap="richImg"></rich-text>
				</view>
				<view class="details">
					<block v-for="(item, index) in diyImgs" :key="index">
						<image class="img" :src="item" mode="widthFix" @tap="chooseImg1" :data-src="item"></image>
					</block>
				</view>
			</block>
		</view>
		<view :class="'friend ' + (currentTab == 1? 'show' : 'hide')">
			<block v-if="aprList.groupList.length > 0">
				<view v-for="(item, index) in aprList.groupList" :key="index" class="li dflex">
					<view class="timg">
						<image :src="item.uavatar" mode="aspectFit"></image>
					</view>
					<view class="name flex">{{item.unickName}}<text>{{item.careatDate}}</text></view>
					<view class="time">帮砍{{item.bargainingAmount}}元</view>
				</view>
			</block>
			<view class="nopeople" v-else>
				<image :src="picUrlss+'sqimg2.png'"></image>
				<text>还没有人帮你砍价，去邀请好友帮忙</text>
			</view>
		</view>
		<view :class="'guize ' + (currentTab == 2? 'show' : 'hide')">
			<rich-text :nodes="activityMain.rule"></rich-text>
		</view>
	</view>
</view>

<view class="mask" @tap="closeLayer" :hidden="isShow"></view>
<view class="kjpop" :hidden="isShow">
	<image src="/static/pages/images/close3.png" class="kjclose" @tap="closeLayer"></image>
	<!-- <image :src="picUrlss+'sqimg2.png'" class="kjimg"></image>砍价了 -->
	<image src="/activity/static/activity/images/kanle1.png" class="kanle1" v-if="whether == 1"></image>
	<!--帮TA砍掉-->
	<image src="/activity/static/activity/images/kanle2.png" class="kanle2" v-if="whether == 2"></image>
	<!--您已砍了-->
	<!-- <image :src="picUrlss+'thsb.png'" class="kjimg"></image> -->
	<!--砍价失败了-->
	<!-- <view class="kjtip" wx:if="{{participate == 1}}">您已经砍过了</view> -->
	<!-- <view class="kjtip">砍价失败了</view> -->
	<view class="kandiao" v-if="whether == 2 && isSuccess">您已经砍到底价了</view>
	<!--砍到底价-->
	<view class="kandiao" v-if="whether == 1">帮TA砍掉<text>{{money}}元</text></view>
	<!--帮TA砍掉-->
	<view class="kandiao" v-if="whether == 2 && !isSuccess">您砍了<text>{{money}}元</text></view>
	<!--帮TA砍掉-->
	<view class="process">
		<view class="ing" :style="'width:' + percent + ';'"></view>
	</view>
	<view class="kjbtn dflex">
		<view class="back" @tap="closeLayer">返回</view>
		<block v-if="whether == 2">
			<view class="ljgm" @tap="confirmBuy" v-if="isSuccess&&topay==null">立即购买</view>
			<view class="ljgm" @tap="toOrder" v-if="isSuccess&&topay!=null">查看订单详情</view>
			<button open-type="share" class="fenx" v-if="!isSuccess">分享给好友</button>
		</block>
		<block v-else>
			<view class="ljgm" @tap="goUrl" v-if="whether == 1">我也要砍价</view>
		</block>
	</view>
</view>
</view>
</template>

<script>
// activity/bargain/kjDetail/kjDetail.js
const app = getApp();
const req = require("../../../utils/request.js");
const utils = require("../../../utils/util.js");
const route =require("../../../utils/route.js");
import mpHtml from "../../../components/mp-html/components/mp-html/mp-html";
export default {
  data() {
    return {
		picUrlss: req.public.picUrls,
      currentTab: 0,
      isShow: true,
      money: '',
      isSuccess: false,
      isKanjia: '',
      start: false,
      percent: "",
      timer: "",
      merchantId: "",
      topay: ""
    };
  },

  components: {mpHtml},
  props: {},

  async onLoad(options) {
    this.query = options;
    // console.log(options);

    if (options.money) {
      this.setData({
        isShow: false,
        money: options.money
      });
    }

    if (options.isShow) {
      this.setData({
        isShow: true
      });
    }
  },

  async onShow() {
    req.isLogin().then(success => {});
	 this.getData();

    await this.loadProudct();
    this.gettoPay();
  },
  // onShareTimeline(){
	 //  let merchantId = '';
	 //  let path = '/activity/bargain/kjDetail/kjDetail?id=' + this.query.id + '&superiorId=' + this.aprList.groupMainP.userId + '&proid=' + this.query.proid ;
	 //  console.log(!req.getStorage('userInfo').id);
	 //  if (!req.getStorage('userInfo').id) {} else {
	 //    path += '&userId=' + req.getStorage('userInfo').id;
	 //  }
	 //  console.log(this.query.merchantId);
	 //  let shopId = '';
	 //    if (req.getStorage('MERCHANT') && req.getStorage('MERCHANT').id != null) {
	 //      path += '&merchantId=' + req.getStorage('MERCHANT').id;
	 //      merchantId = req.getStorage('MERCHANT').id;
	    	  
	 //      if (req.getStorage('smallShop') && req.getStorage('MERCHANT').id != null) {
	 //        path += '&shopId=' + req.getStorage('smallShop').id;
	 //        shopId = req.getStorage('smallShop').id;
	 //        merchantId = req.getStorage('smallShop').merchantDTO.id;
	 //      }
	 //    }
	  
	 //  console.log(path,"456")
	 //  route.share(1, req.getStorage('userInfo').id, path, merchantId, shopId, 9, this.query.proid + '_' + this.query.id);
	 //  return {
	 //    title: req.getStorage("userInfo").nickName + '邀请您帮忙砍价：' + this.acProduc.productName,
	 //    imageUrl: this.acProduc.pic,
	 //    path: path
	 //  };
  // },

  onShareAppMessage: function () {
	  let merchantId = '';
	  let path = '/activity/bargain/kjDetail/kjDetail?id=' + this.query.id + '&superiorId=' + this.aprList.groupMainP.userId + '&proid=' + this.query.proid ;
	  // console.log(!req.getStorage('userInfo').id);
	  if (!req.getStorage('userInfo').id) {} else {
	    path += '&userId=' + req.getStorage('userInfo').id;
	  }
	  // console.log(this.query.merchantId);
	  let shopId = '';
	    if (req.getStorage('MERCHANT') && req.getStorage('MERCHANT').id != null) {
	      path += '&merchantId=' + req.getStorage('MERCHANT').id;
	      merchantId = req.getStorage('MERCHANT').id;
	    	  
	      if (req.getStorage('smallShop') && req.getStorage('MERCHANT').id != null) {
	        path += '&shopId=' + req.getStorage('smallShop').id;
	        shopId = req.getStorage('smallShop').id;
	        merchantId = req.getStorage('smallShop').merchantDTO.id;
	      }
	    }
	  
	  // console.log(path,"456")
	  route.share(1, req.getStorage('userInfo').id, path, merchantId, shopId, 9, this.query.proid + '_' + this.query.id);
	  return {
	    title: req.getStorage("userInfo").nickName + '邀请您帮忙砍价：' + this.acProduc.productName,
	    imageUrl: this.acProduc.pic,
	    path: path
	  };
	  
    // return {
    //   title: req.getStorage("userInfo").nickName + '邀请您帮忙砍价：' + this.acProduc.productName,
    //   imageUrl: this.acProduc.pic,
    //   path: '/activity/bargain/kjDetail/kjDetail?id=' + this.query.id + '&superiorId=' + this.aprList.groupMainP.userId + '&proid=' + this.query.proid + "&merchantId=" + this.query.merchantId
    // };
  },
  methods: {
    tab(event) {
      const tabIndex = event.currentTarget.dataset.current;
      if (this.currentTab === tabIndex) return false;
      this.setData({
        currentTab: tabIndex
      });
    },

    closeLayer() {
      this.setData({
        isShow: true
      });
    },

    loadProudct() {
      let that = this;
      const query = that.query;
      // console.log(query.id);
      return new Promise((resolve, reject) => {
        req.getRequest('/api/activity/bargainPriceDetail', {
          id: query.id,
          merchantId: query.merchantId
        }, data => {
			if(data){
				data.bargainingMoney = parseFloat(data.bargainingMoney).toFixed(2);
				data.surplusMoney = parseFloat(data.surplusMoney).toFixed(2);
				this.setData(data);
				this.initStates();
				let percent = Math.round(data.bargainingMoney / (data.acProduc.orPrice - data.acProduc.money) * 100) + '%';
				
				if (data.bargainingMoney == (data.acProduc.orPrice * 10000 - data.acProduc.money * 10000) / 10000) {
				  this.setData({
				    isSuccess: true
				  });
				}
				
				this.setData({
				  percent: percent
				});
				this.initTimer(data.acProduc, data.aprList);
			}
          resolve(); // that.getCodeUrl();
        });
      });
    },

    getData() {
      let that = this;
      const query = this.query;
      return new Promise((resolve, reject) => {
        req.getRequest('/api/product/detail', { id: query.proid }, data => {
          // console.log("/api/product/detail")
          var nodes = data.detail;
          that.setData({ bannerUrls: data.images, pro: data, nodes: nodes });
          resolve();
        })
      })
    },
    initTimer(group, list) {
      //计时器
      let _ts = this;

      let nowTime = new Date(group.nowTime.replace(/-/g, '/')).getTime();
      let startTime = new Date(group.createDate.replace(/-/g, '/')).getTime();
      let endTime = new Date(list.endDate.replace(/-/g, '/')).getTime(); 
      let times = parseInt((endTime - nowTime) / 1000);
      this.timer = setInterval(() => {
        times--;

        if (times === 0) {
          //重新加载列表
          _ts.setData({
            'act.end': true
          });

          return false;
        }

        if (times < 0) {
          _ts.setData({
            'act.isJieshu': true
          });
        }

        let n = utils.formatDayTimes(times);

        _ts.setData({
          timer: n.split(/:|天/g)
        });
      }, 1000);

      if (this.start) {
        clearInterval(this.timer);
      }
    },

    goUrl() {
      app.globalData.redirectTab('activity/bargain/index/index?merchantId=' + this.query.merchantId);
    },

    confirmBuy() {
      //直接购买
      if (this.start) return req.msg('活动已结束'); // let merchant = req.getStorage('defaultMerchant');

      if (this.query.merchantId) {
        this.setData({
          merchantId: this.query.merchantId
        });
      } // else{
      //   if (req.getStorage('smallShop')) {
      //     this.setData({ merchant: req.getStorage('smallShop').merchantDTO })
      //     this.setData({ merchantId: req.getStorage('smallShop').merchantDTO.id })
      //   } else if (req.getStorage('MERCHANT')) {
      //     this.setData({ merchantId: req.getStorage('MERCHANT').id })
      //     this.setData({ merchant: req.getStorage('MERCHANT') })
      //   }
      // }


      // console.log(this.acProduc);
      const params = {
        skuId: this.acProduc.skuId,
        quantity: 1,
        productId: this.acProduc.productId,
        activityId: this.acProduc.id,
        aprId: this.query.id
      };

      if (this.query.merchantId) {
        params.merchantId = this.query.merchantId;
      } // if (this.data.merchant && this.data.merchant.type == 5) {
      //   params.shopId = this.data.merchant.id
      // }
      // if (this.data.merchantId) params.merchantId = this.data.merchantId;


      req.postRequest('/api/purchase/direct/buy', params, res => {
        let redirect = '/product/subOrder/subOrder?ids=' + res;
        let orderType = 7; //砍价订单类型

        redirect += '&orderType=' + orderType;
        redirect += '&aprId=' + params.aprId;

        if (params.merchantId) {
          redirect += '&merchantId=' + this.merchantId;
        }

        if (params.shopId) {
          redirect += '&shopId=' + params.shopId;
        }

        uni.navigateTo({
          url: redirect
        });
      });
    },

    initState() {
      //判断是否发起砍价
      req.isLogin().then(success => {});
      let superid = this.query.id;
      let proid = this.acProduc.productId;
      if (this.isStates == 0) return req.msg('活动还未开始'); // if (this.data.isStates == 2) return req.msg('活动已结束');

      if (this.start) return req.msg('活动已结束');
      let param = {
        acpId: this.acProduc.id,
        actId: this.acProduc.actId,
        productId: this.acProduc.productId,
        type: 5,
        initOrPart: 2,
        superiorId: superid
      };
      req.getRequest('/api/activity/participationActivity', param, res => {
        //判断是否帮砍过
        // console.log("/api/activity/participationActivity");

        if (res.state == 1) {
          this.setData({
            isKanjia: res.state,
            isShow: false
          });
          return false;
        }

        let params = {
          acpId: this.acProduc.id,
          type: 5
        };

        if (superid) {
          params.superiorId = superid;
        }

        req.postRequest('/api/activity/carterActivityPurchaseRecords', params, res => {
          if (res) {
            let money = '';
            let id = '';
            if (superid) money = res, id = superid;else id = res;
            this.setData({
              isShow: false,
              money: money
            });
            this.loadProudct(); // wx.redirectTo({ url: '/activity/bargain/kjDetail/kjDetail?id=' + id + '&money=' + money + '&proid=' + proid })
            // app.openPage('activity/bargain/kjDetail/kjDetail?id=' + id + '&money=' + money + '&proid=' + proid)
          }
        });
      });
    },

    initStates() {
      //判断是否发起砍价
      req.isLogin().then(success => {});
      let params = {
        acpId: this.acProduc.id,
        actId: this.acProduc.actId,
        productId: this.acProduc.productId,
        type: 5,
        initOrPart: 2,
        superiorId: this.query.id
      };
      return new Promise((resolve, reject) => {
        req.getRequest('/api/activity/participationActivity', params, res => {
          // console.log("/api/activity/participationActivity");

          if (res.state != 1) {
            this.setData({
              isKanjia: res.state,
              isShow: true
            });
          } else {
            this.setData({
              isKanjia: res.state
            });
          }

          resolve();
        });
      });
    },

    gettoPay() {
      req.postRequest('/api/activity/toPay', {
        aprId: this.query.id,
        type: 5
      }, data => {
        this.setData({
          topay: data
        });
      });
    },

    toOrder() {
      uni.navigateTo({
        url: '/mine/orderDet/orderDet?id=' + this.topay
      });
    },

    // 活动商品详情
    goPrcdetail() {
      app.globalData.openPage('activity/bargain/detail/detail?acid=' + this.acProduc.id + '&id=' + this.acProduc.productId);
    }

  }
};
</script>
<style>
@import "./kjDetail.css";
</style>