<template>
<view>
<!--group/ptDetail/ptDetail.wxml-->
<view class="banner">
	<image src="/activity/static/activity/images/ptban1.jpg" mode="widthFix"></image>
</view>
<view class="con">
	<view class="info dflex" @tap="goPrcdetail">
		<view class="pinimgs">
			<image :src="actData.acProduc.pic" mode="aspectFit" class="pinimg"></image>
			<view class="tuan">
				<image src="/static/pages/images/tagbg.png"></image>
				<text>{{actData.activityMain.numberPeople}}人团</text>
			</view>
		</view>
		<view class="pininfo flex">
			<view class="proname">{{actData.acProduc.productName}}</view>
			<view class="guige"></view>
			<view class="sta dflex">
				<view class="price"><text>￥</text>{{actData.acProduc.money}}<text class="del" v-if="actData.acProduc.marketPrice!=0&&actData.acProduc.marketPrice>actData.acProduc.money">原价：{{actData.acProduc.marketPrice}}</text></view>
				<!-- <view class="nums">×1</view> -->
			</view>
		</view>
	</view>

	<!-- 0进行中  1标识拼团成功正常结束   2拼团特有状态，此状态下拼团未付款  3失败  4退款成功 -->
	<view v-if="actData.aprList.groupMainP.state==0" class="cantuan bgfff mt20 r10">
		<view class="can-info" v-if="actData.activityMain.numberPeople-actData.aprList.groupList.length<=0">{{actData.aprList.groupMainP.state==1?'拼团完成':'拼团待支付'}}</view>
		<view class="can-info" v-else>还差<text>{{actData.activityMain.numberPeople-actData.aprList.groupList.length}}人</text>成团</view>
		<view class="sheng dflex" v-if="actData.aprList.groupMainP.state==0">
			剩余
			<view class="sheng-time dflex">
				<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>
			</view>
			结束
		</view>
		<view class="can-infos dflex">
			<view v-for="(item, index) in groupList" :key="index" class="li">
				<image v-if="item.uavatar" :src="item.uavatar" mode="aspectFit" class="can-user"></image>
				<text v-if="index==0">团长</text>
				<text v-else>团员</text>
				<image v-if="!item.uavatar" src="/activity/static/activity/images/cha.png" class="can-bg"></image>
			</view>
		</view>
		<view class="can-btn mbglinear" @tap="addGroup" v-if="isJion&&actData.aprList.groupList.length!=actData.activityMain.numberPeople">我要参团</view>
		<button open-type="share" class="can-btn mbglinear" v-if="!isJion">邀请好友参团</button>
		<view class="kai-btn" v-if="actData.whether!=2" @tap="createGroup">我也要开团</view>
	</view>
	<view v-if="actData.aprList.groupMainP.state!=0" class="status bgfff mt20 r10">
		<view v-if="actData.aprList.groupMainP.state==1" class="status-c">
			<image :src="picUrlss+'sqimg3.png'"></image>
			<text>拼团成功啦~</text>
		</view>
		<view v-if="actData.aprList.groupMainP.state==3" class="status-c">
			<image :src="picUrlss+'sqimg2.png'"></image>
			<text>拼团失败，已退款~</text>
		</view>
		<view class="can-infos dflex" v-if="actData.aprList.groupMainP.state!=1">
			<view v-for="(item, index) in groupList" :key="index" class="li">
				<image v-if="item.uavatar" :src="item.uavatar" mode="aspectFit" class="can-user"></image>
				<text v-if="index==0">团长</text>
				<image v-if="!item.uavatar" src="/activity/static/activity/images/cha.png" class="can-bg"></image>
			</view>
		</view>
		<view class="can-btn mbglinear" v-if="isUser" @tap="toOrder">查看订单详情</view>
		<view class="can-btn mbglinear" @tap="goSeept">查看其他拼团</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" @imgtap="chooseImg1"></mp-html>
<!-- 			<view class="details det-text">
				<rich-text :nodes="nodes"></rich-text>
			</view>
			<view class="details">
				<block v-for="(item, index) in imgs" :key="index">
					<image class="img" :src="item" mode="widthFix" @tap="chooseImg1" :data-src="item"></image>
				</block>
			</view> -->
		</view>
		<view :class="'friend ' + (currentTab == 1? 'show' : 'hide')">
			<view v-for="(item, index) in groupList" :key="index" class="li dflex" v-if="item.careatDate">
				<view class="timg">
					<image :src="item.uavatar" mode="aspectFit"></image>
					<text v-if="item.userId==actData.aprList.groupMainP.userId">团长</text>
					<text v-else>团员</text>
				</view>
				<view class="name flex">{{item.unickName}}</view>
				<view class="time">{{item.careatDate}}{{item.userId==actData.aprList.groupMainP.userId?'开团':'参团'}}</view>
			</view>


		</view>
		<view :class="'guize ' + (currentTab == 2? 'show' : 'hide')">
			<rich-text :nodes="actData.activityMain.rule"></rich-text>
		</view>
	</view>
</view>
</view>
</template>

<script>
const app = getApp();
const req = require("../../../utils/request.js");
const utils = require("../../../utils/util.js");
const route = require("../../../utils/route");
import mpHtml from "../../../components/mp-html/components/mp-html/mp-html";
export default {
  data() {
    return {
		picUrlss: req.public.picUrls,
      currentTab: 0,
      isJion: true,
      isGroup: true,
      isUser: false,
      start: false,
      actData: "",
      groupList: "",
      timer: "",
      hideShare: false
    };
  },

  components: {
	  mpHtml
  },
  props: {},
  onLoad: function (options) {
    this.query = options; // this.getBargainPriceDetail();

    // console.log(options);
  },
  onShow: function () {
    // req.redirectIndex()
    req.isLogin().then(success => {});
    this.getBargainPriceDetail();
  },
  onShareAppMessage: function () {
    let merchantId = '';
    let path = '/activity/group/ptDetail/ptDetail?id=' + this.query.id + '&acid=' + this.actData.acProduc.id + '&isShare=' + true;
    // 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, 7, this.actData.acProduc.id + '_' + this.query.id);
    return {
      title: this.actData.aprList.groupMainP.unickName + '邀请您一起拼团：' + this.actData.acProduc.productName,
      imageUrl: this.actData.acProduc.pic,
      path: path
    };
  },
  // onShareTimeline(){
	 //  let merchantId = '';
	 //  let path = '/activity/group/ptDetail/ptDetail?id=' + this.query.id + '&acid=' + this.actData.acProduc.id + '&isShareTimeline=' + true;
	 //  console.log(!req.getStorage('userInfo').id);
	 //  if (!req.getStorage('userInfo').id) {} else {
	 //    path += '&userId=' + req.getStorage('userInfo').id;
	 //  }
	 //  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, 7, this.actData.acProduc.id + '_' + this.query.id);
	 //  return {
	 //    title: this.actData.aprList.groupMainP.unickName + '邀请您一起拼团：' + this.actData.acProduc.productName,
	 //    imageUrl: this.actData.acProduc.pic,
	 //    path: path
	 //  };
  // },
  methods: {
    tab(event) {
      const tabIndex = event.currentTarget.dataset.current;
      if (this.currentTab === tabIndex) return false;
      this.setData({
        currentTab: tabIndex
      });
    },

    //获取平团详情
    getBargainPriceDetail() {
      req.getRequest('/api/activity/groupDetail', {
        id: this.query.id,
        merchantId: this.query.merchantId
      }, data => {
        // console.log(data);
		if(data){
			this.setData({
			  actData: data
			});
			this.initTimer(data.acProduc.nowTime, data.aprList.groupMainP, data.acProduc.endTime);
			var groupList = []; //  groupList.push(data.aprList.groupMainP);
			
			if (data.aprList.groupList) {
			  groupList = groupList.concat(data.aprList.groupList);
			  groupList.forEach(res => {
			    if (res.userId == req.getStorage("userInfo").id) {
			      this.setData({
			        isUser: true
			      });
			    }
			  });
			}
			
			if (groupList.length < data.activityMain.numberPeople) {
			  for (var i = 0; i < data.activityMain.numberPeople - data.count; i++) {
			    // console.log(data.activityMain.numberPeople - data.count);
			    var nullGroup = {};
			    groupList.push(nullGroup);
			  }
			}
			
			// console.log(groupList);
			this.isJionFun(groupList);
			this.setData({
			  groupList: groupList
			}); 
			 this.loadProudct(data.acProduc.productId);
		}
      });
    },

    initTimer(nowdata, group, end) {
      //计时器
      let _ts = this;

      let nowTime = new Date(nowdata.replace(/-/g, '/')).getTime();
      let endTime = new Date(group.endDate.replace(/-/g, '/')).getTime(); // let actend=new Date(end.replace(/-/g, '/')).getTime();
      // let times
      // if(actend-endTime>0){
      //    times = parseInt((endTime - nowTime) / 1000);
      // }else{
      //   times = parseInt((actend - nowTime) / 1000);
      // }

      let times = parseInt((endTime - nowTime) / 1000);
      // console.log(times);
      this.timer = setInterval(() => {
        times--;

        if (times === 0) {
          return false;
        }

        if (times < 0) {
          this.setData({
            isGroup: false
          });
        }

        let n = utils.formatDayTimes(times);

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

     loadProudct(proId) {
      let that = this;
      req.getRequest('/api/product/detail', { id: proId }, data => {
        //富文本图片放大
        var nodes = data.detail;
        // if (nodes) {
        //   if (nodes.indexOf("src") >= 0) {
        //     //正则匹配所有图片路径
        //     var imgs = [];
        //     nodes = nodes.replace(/<img [^>]*src=['"]([^'"]+)[^>]*>/gi, function (match, capture) {
        //       imgs.push(capture);
        //       that.setData({
        //         imgs: imgs
        //       });
        //       return '';
        //     });
        //   }
        // }
        that.setData({ bannerUrls: data.images, pro: data ,nodes: nodes});
      })
    },
    // 活动商品详情
    goPrcdetail() {
      app.globalData.openPage('activity/group/detail/detail?acid=' + this.actData.acProduc.id + '&id=' + this.actData.acProduc.productId);
    },

    //创建拼团
    createGroup() {
      if (this.start) return req.msg('活动已结束');
      req.postRequest('/api/activity/carterActivityPurchaseRecords', {
        acpId: this.actData.aprList.groupMainP.acpId,
        type: 3
      }, res => {
        this.createGroupOrder(res);
      });
    },

    //加入平团
    addGroup() {
      if (this.start) return req.msg('活动已结束');
      if (this.actData.aprList.groupList.length == this.actData.activityMain.numberPeople) return req.msg('该团参与人数已满');
      this.createGroupOrder(this.actData.aprList.id);
    },

    showShare() {
	  // #ifndef H5
      req.isLogin().then(success => {
        if (success) {
          this.setData({
            hideShare: false
          });
        }
      });
	  // #endif
    },

    goSeept() {
      uni.redirectTo({
        url: '/activity/group/index/index'
      });
    },

    createGroupOrder(aprId) {
      // let merchant = req.getStorage('defaultMerchant');
      const params = {
        skuId: this.actData.acProduc.skuId,
        quantity: 1,
        productId: this.actData.acProduc.productId,
        aprId: aprId
      };
	  if (this.query.merchantId) {
	  	params.merchantId = this.query.merchantId;
		if(this.query.shopId){
			params.shopId = this.query.shopId;
		}
	  }
      // if (this.query.merchantId) params.merchantId = this.query.merchantId;
      params.activityId = this.actData.acProduc.id;
      req.postRequest('/api/purchase/direct/buy', params, res => {
        let redirect = '/product/subOrder/subOrder?ids=' + res;
        redirect += '&orderType=' + 4;
        redirect += '&aprId=' + aprId;
        redirect += '&activityId=' + this.actData.acProduc.id;
        redirect += '&pay=' + 1;
		if (params.merchantId) {
			redirect += '&merchantId=' + params.merchantId;
		}
		
		if (params.shopId) {
			redirect += '&shopId=' + params.shopId;
		}
		
        uni.navigateTo({
          url: redirect
        });
      });
    },

    /**判断是否已经参团 */
    isJionFun(groupList) {
      let userInfo = req.getStorage('userInfo');
      groupList.forEach(res => {
        // console.log(res.userId == userInfo.id);
        if (res.userId == userInfo.id) this.setData({
          isJion: false
        });
      }); // console.log(groupList)
    },

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

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