<template>
<view id="collage">
    <view class="white"></view>
    <view class="collage-progress">
        <progress :percent="percent" stroke-width="4" activeColor="#EA4448" backgroundColor="#DBDBDB"></progress>
        <view class="launch active-emj" style="left: 10%">
            <view class="iconfont icon-faqipintuan"></view>
            <view class="text">发起拼团</view>
        </view>
        <view class="invite active-emj" style="left:40%">
            <view class="iconfont icon-yaoqinghaoyou"></view>
            <view class="text">邀请好友参团</view>
        </view>
        <view class="success" :class="showItemDate.status != 0 ? 'active-emj' :''" style="left: 80%">
            <view class="iconfont icon-pintuanchenggong"></view>
            <view class="text">拼团<block v-if="showItemDate.status != 2">成功</block><block v-if="showItemDate.status == 2">失败</block></view>
        </view>
    </view>
    <view class="white b"></view>
    <view class="collage-goods" @tap="jumpDetail" v-if="showItemDate && showItemDate.groupon && showItemDate.groupon.goods">
        <view class="goods-img">
            <image mode="widthFix" :src="showItemDate.groupon.goods.img"></image>
        </view>
        <view class="goods-infomation">
            <view class="info-name">{{showItemDate.groupon.goods.name}}</view>
            <view class="original-cost marg-t">
                <view class="price">¥ {{showItemDate.groupon.goods.sell_price}}
                </view>
                <view class="o-text">单买价</view>
            </view>
            <view class="purchase-cost mar-t bor-c">
                <view class="price bor-c">¥ {{showItemDate.groupon.price}}
                </view>
                <view class="o-text p-text">{{showItemDate.groupon.number}}人团</view>
            </view>
        </view>
    </view>
    <view class="collage-open">
        <view class="open-title">
            <view class="text">开团详情</view>
            <view class="shar">. . .</view>
        </view>
        <view class="open-content" v-if="showItemDate.overdue_status == 0 && showItemDate.status == 0">
            <view class="time-text">
                <view class="iconfont icon-weikaishi"></view>
                <view class="text" v-if="showItemDate.status">已成团，待发货</view>
                <view class="text" v-else>已开团，离成团还差 <view>{{showItemDate.gap_number}}</view>人</view>
            </view>
            <view class="count-down" v-if="endtype == 1">
                剩
                <view class="timedown">
                    <span>{{endTime.hour}}</span>时
                    <span>{{endTime.minute}}</span>分
                    <span>{{endTime.second}}</span>秒
                </view>
               <!-- <group class="my-class" end="{{showItemDate.groupon.ends_at}}" starts="{{showItemDate.groupon.starts_at}}" server="{{showItemMeta.server_time}}" mold="list">

                </group>-->
                自动结束
            </view>
            <view class="count-down" v-if="endtype == 0">
                {{endmessage}}
            </view>
        </view>
        <view class="open-content" v-if="showItemDate.overdue_status == 1 && showItemDate.status == 0">活动已过期</view>
        <view class="open-content" v-if="showItemDate.status == 1">赞！拼团成功</view>
        <view class="open-content" v-if="showItemDate.status == 2">拼团失败</view>

    </view>
    <view class="collage-records">
        <view class="record-title">参团记录</view>
        <view class="record-content">
            <view class="item" v-for="(item, index) in showItemDate.users" :key="index">
                <view class="avatar">
                    <image :src="item.meta.avatar"></image>
                </view>
                <view class="info">
                   <view class="info-top">
                       <span class="name">{{item.meta.nick_name}}</span>
                       <span class="colonel" v-if="item.is_leader">团长</span>
                   </view>
                    <view class="info-bottom">
                        <span>{{item.created_at}} </span>
                        <span v-if="item.is_leader">开团</span>
                        <span v-else>参团</span>
                    </view>
                </view>
            </view>
        </view>
    </view>
    <div class="order-share" v-if="showItemDate.overdue_status == 0">
        <div class="item" @tap="jumpOrder" :style="'background: ' + config.mainColor" v-if="showItemDate.order_no && !showItemDate.is_virtual">
            查看订单详情
        </div>
        <div class="item" @tap="jumpDetail" :style="'background: ' + config.mainColor" v-if="!showItemDate.order_no">
            立即参团
        </div>
        <!-- #ifdef APP-PLUS || MP-WEIXIN -->
        <div class="item look" :style="'color: ' + config.mainColor" @tap="changeShare">
            分享给好友
        </div>
        <!-- #endif -->
		<!-- #ifdef H5 -->
		<div class="item look" :style="'color: ' + config.mainColor"  @tap="togglePopup('middle-img')">
		    分享给好友
		</div>
		<!-- #endif -->
    </div>
    <div class="order-share" v-else>
        <div class="item" :style="'background: ' + config.mainColor" @tap="jumpMore">
            查看更多活动商品
        </div>
        <div class="item look" :style="'color: ' + config.mainColor" @tap="jumpOrder" v-if="showItemDate.order_no">
            查看订单详情
        </div>
    </div>
    <!--弹出分享部分-->
    <view class="maks" :class="show_share ? 'cur' : ''" @tap="changeShare">

    </view>

    <view class="share-box" :class="show_share ? 'cur' : ''">
        <!-- #ifdef MP-WEIXIN -->
        <button class="shaer-item" open-type="share">
            分享给好友
        </button>
        <!-- #endif -->
		<!-- #ifdef APP-PLUS -->
		<button class="shaer-item" @click="shareapp">
		    分享给好友
		</button>
		<!-- #endif -->
        <view class="shaer-item mx-1px-top" @tap="createShareImg">
            生成海报
        </view>
        <view class="shaer-item clear" @tap="changeShare">
            取消
        </view>
    </view>

    <!--弹出分享到朋友圈-->
    <view class="circle-friends" :class="show_friend ? 'cur':''">
       <view class="imgboxs">
           <view class="circle-img">
               <image :src="createImgUrl" mode="widthFix"></image>
           </view>
           <view class="save-img" :style="'background: ' + config.mainColor" @tap="downImg">
               保存图片
           </view>
           <i class="iconfont icon-delete" @tap="getShearImg"></i>
       </view>
    </view>
    <view class="ibrand-author" v-if="author" @tap="jumpAuthor">
        <i class="iconfont icon-dibu"></i>
    </view>
    <!--用户拒绝下载图片授权弹出-->
    <alert :is_refused="is_refused" bind:close="closeAlert"></alert>
	
	<!-- #ifdef H5 -->
		<view >
			<uni-popup :show="type === 'middle-img'" position="top" mode="fixed" @hidePopup="togglePopup('')">
							<view class="uni-center center-box">
								<image style="position: absolute; top: 0;right:0"  @tap="togglePopup('')" class="image" src="/static/ico-share-wechat.png" />
							</view>
			</uni-popup>
		</view>
	<!-- #endif -->
</view>
</template>
<script>
import {pageLogin, getUrl,config,is} from '@/common/js/utils.js';
import Animation from '@/common/js/animation.js';
import seckill from "@/components/seckill/seckill";
import group from "@/components/group/group";
import alert from "@/components/alert/alert";
import permision from "@/common/js/permission.js"

export default {
  data() {
    return {
      show_share: false,
      show_friend: false,
      showItemDate: {},
      percent: 50,
      showItemMeta: {},
      endTime: {
        interval: '',
        day: 0,
        hour: 0,
        minute: 0,
        second: 0,
        count: 0
      },
      timer: '',
      endmessage: '',
      endtype: 0,
      createImgUrl: '',
      config: '',
      author: '',
      is_refused: false,
	  type:0
    };
  },

  //发送给好友
  onShareAppMessage(res) {
    this.changeShare();
    var groupon_item_id = this.showItemDate.id;
    return {
      title: this.showItemDate.groupon.goods.name,
      path: '/pages/store/collage/collage?multi_groupon_item_id=' + groupon_item_id,
      imageUrl: this.showItemDate.groupon.goods.img
    };
  },

  onLoad(e) {
    // 第三方平台配置颜色
    var gbConfig = this.$cookieStorage.get('globalConfig') || '';
    var init = this.$cookieStorage.get('init');
    this.setData({
      config: gbConfig,
      author: init ? init.other_technical_support : ''
    });
	console.log('multi_groupon_item_id',e.multi_groupon_item_id)
    var multi_groupon_item_id = e.multi_groupon_item_id;

    if (e.scene) {
      var scene = decodeURIComponent(e.scene);
      var sceneArr = scene.split(',');

      if (sceneArr.length > 0) {
        multi_groupon_item_id = sceneArr[0];
      }
    }

    if (multi_groupon_item_id) {
      this.showItem(multi_groupon_item_id);
    } else {
      wx.showModal({
        content: '非法进入',
        showCancel: false
      });
    }
	// #ifdef H5
	var token = this.$cookieStorage.get('user_token');
	if(!token){
		var env = {
					 isIPad: /ipad/i.test(window.navigator.userAgent),
					 isIphone: /iphone|ipad|ipod/i.test(window.navigator.userAgent),
					 isWechat: /MicroMessenger/i.test(window.navigator.userAgent)
		}
		
			if(env.isWechat){
				if(e.openid){
					this.$cookieStorage.set('openid',e.openid)
				}
				var openid =  this.$cookieStorage.get('openid') || e.openid;
				if(openid){
					this.postNewQuickLogin(openid);
				} else{
					let origin = window.location.origin;
					var url = origin+'/pages/store/collage/collage?multi_groupon_item_id='+e.multi_groupon_item_id;
					window.location.href = this.$config.GLOBAL.baseUrl+'oauth/wxOauth?redirect_url='+encodeURIComponent(url);
				}
			} else{
				wx.navigateTo({
					url:'/pages/store/collage/collage?multi_groupon_item_id='+e.multi_groupon_item_id
				})
			}
		
	}
	// #endif
  },

  components: {
    seckill,
    group,
    alert
  },
  methods: {
	  postNewQuickLogin(open_id){
	  	wx.showLoading({
	  		title: '正在登录',
	  		mask: true
	  	});
	  	this.$http.post({
	  		api:'api/oauth/newQuickLogin',
	  		data:{
	  			open_id:open_id
	  		}
	  }).then(res=>{
	  		res = res.data;
	  		if(res.status){
	  			if(res.data.access_token){
	  				var access_token = res.data.token_type + ' ' + res.data.access_token;
	  				var expires_in = res.data.expires_in || 315360000; 
	  				this.$cookieStorage.set("user_token", access_token, expires_in);
	  				//如果用户没有绑定手机号
	  				if(res.data.has_bind_mobile == 0){
	  					wx.reLaunch({
	  						url:'/pages/user/bindingphone/bindingphone'
	  					})
	  				}
	  			} else{
	  				wx.showModal({
	  					content: res.message || '请求失败，请重试',
	  					showCancel: false
	  				});
	  				
	  			}
	  			
	  		} else{
	  			wx.showModal({
	  				content: res.message || '请求失败，请重试',
	  				showCancel: false
	  			});
	  		}
	  		wx.hideLoading()
	  	}).catch(rej=>{
	  		wx.showModal({
	  			content: rej.message || '请求失败，请重试',
	  			showCancel: false
	  		});
	  		wx.hideLoading()
	  		
	  	})
	  },
	  togglePopup(type) {
	  			this.type = type;
	  },
	  shareapp(){
	  		  this.changeShare();
			  var groupon_item_id = this.showItemDate.id;
			  var  title =  this.showItemDate.groupon.goods.name;
			  var imageUrl = this.showItemDate.groupon.goods.img;
	  		  uni.getProvider({
	  			  service:'share',
	  			  success:function(res){
	  				  uni.share({
	  				       provider: "weixin",
	  				       scene: "WXSceneSession",
	  				       type: 5,
	  				       title:title,
	  				       imageUrl:imageUrl,
	  				  			  miniProgram:{
	  				  				  id:'gh_72e65196278a',
	  				  				  path:'pages/store/collage/collage?multi_groupon_item_id=' + groupon_item_id,
	  				  				  type:0,
	  				  				  webUrl: 'https://guojiang.club'
	  				  			  },
	  				       success: function (res) {
	  				           console.log("success:" + JSON.stringify(res));
	  				       },
	  				       fail: function (err) {
	  				           console.log("fail:" + JSON.stringify(err));
	  				       }
	  				   });
	  			  }
	  		  })
	  		  
	  		 
	  },
    //弹出分享
    changeShare() {
      this.setData({
        show_share: !this.show_share
      });
    },

    //弹出朋友圈
    getShearImg() {
      this.setData({
        show_friend: !this.show_friend,
        show_share: false
      });
    },

    jumpAuthor() {
      wx.navigateTo({
        url: '/pages/index/author/author'
      });
    },

    //获取拼团详情页数据
    showItem(multi_groupon_item_id) {
      wx.showLoading({
        title: '加载中',
        mask: true
      });
      var token = this.$cookieStorage.get('user_token') || '';
      this.$http.get({
        api: 'api/multiGroupon/showItem',
        header: {
          Authorization: token
        },
        data: {
          multi_groupon_item_id: multi_groupon_item_id
        }
      }).then(res => {
        if (res.statusCode == 200) {
          res = res.data;

          if (res.status) {
            this.setData({
              showItemDate: res.data,
              showItemMeta: res.meta
            });
            this.controlProgress();

            if (this.showItemDate.overdue_status == 0 && this.showItemDate.status == 0) {
              this.setData({
                timer: setInterval(this.countTime, 1000)
              });
            }
			// #ifdef H5
			if (this.$wechat && this.$wechat.isWechat()) {
				var  title =  this.showItemDate.groupon.goods.name;
				var imageUrl = this.showItemDate.groupon.goods.img;
				 this.$wechat.share({  
					  title: title,
					  img:imageUrl,
					  desc:'果酱小店'
					  
				});  
			}  
			// #endif
            /*  timer = setInterval(this.countTime, 1000);*/

          } else {
            wx.showModal({
              content: res.message || '请求数据失败',
              showCancel: false
            });
          }
        } else {
          wx.showModal({
            content: res.message || '请求数据失败',
            showCancel: false
          });
        }

        wx.hideLoading();
      }).catch(rej => {
        wx.hideLoading();
        wx.showModal({
          content: res.message || '请求失败',
          showCancel: false
        });
      });
    },

    //控制进度条颜色
    controlProgress() {
      if (this.showItemDate.status != 0) {
        this.setData({
          percent: 100
        });
      }
    },

    // 发送到朋友圈
    createShareImg() {
      wx.showLoading({
        title: "生成中",
        mask: true
      });
      var token = this.$cookieStorage.get('user_token') || '';
      this.$http.get({
        api: 'api/multiGroupon/createShareImage',
        header: {
          Authorization: token
        },
        data: {
          goods_id: this.showItemDate.multi_groupon_goods_id,
          multi_groupon_item_id: this.showItemDate.id
        }
      }).then(res => {
        if (res.statusCode == 200) {
          res = res.data;

          if (res.status) {
            this.setData({
              createImgUrl: res.data.image
            });
            this.getShearImg();
          } else {
            wx.showModal({
              content: res.message || '请求失败',
              showCancel: false
            });
          }
        } else {
          wx.showModal({
            content: '请求失败',
            showCancel: false
          });
        }

        wx.hideLoading();
        this.changeShare();
      }).catch(rej => {
        wx.showModal({
          content: '内部错误',
          showCancel: false
        });
        wx.hideLoading();
        this.changeShare();
      });
    },

    closeAlert() {
      this.setData({
        is_refused: false
      });
    },

    //下载图片
    downImg() {
      if (this.createImgUrl) {
        wx.showLoading({
          title: '正在下载',
          mask: true
        });
        this.$http.dowloadFile({
          api: this.createImgUrl
        }).then(res => {
          if (res.statusCode == 200) {
            // #ifdef MP-WEIXIN
            wx.getSetting({
              success: ret => {
                //如果之前没有授权
                if (!ret.authSetting['scope.writePhotosAlbum']) {
                  wx.authorize({
                    scope: 'scope.writePhotosAlbum',
                    success: rej => {
                      this.saveImg(res.tempFilePath);
                    },
                    //用户拒绝授权
                    fail: ret => {
                      this.setData({
                        is_refused: true
                      });
                      wx.hideLoading();
                    }
                  });
                } else {
                  this.saveImg(res.tempFilePath);
                }
              }
            });
            // #endif
			// #ifdef APP-PLUS
			var that = this;
			uni.getSystemInfo({
				success(result) {
					if(result.platform == 'android'){
						that.requestAndroidPermission(res.tempFilePath);
					} else if(result.platform == 'ios'){
						that.requestIosPermission(res.tempFilePath)
					}
					
				}
			})
			// #endif
          } else {
            wx.hideLoading();
            wx.showToast({
              title: '下载图片失败',
              icon: 'none'
            });
          }
        }, err => {});
      }
    },
	//ios app权限授权
	requestIosPermission(url){
		var result = permision.judgeIosPermission('photoLibrary');
		if(result){
			this.saveImg(url);
		}else{
			//打开授权，iOS上如果没有调用过的权限，不会出现在权限设置界面。
			permision.gotoAppPermissionSetting()
		}
	},
	//安卓app权限授权
	async requestAndroidPermission(url) {
	    var result = await permision.requestAndroidPermission("android.permission.WRITE_EXTERNAL_STORAGE")
	    var strStatus
	    if (result == 1) {
	        strStatus = "已获得授权";
			this.saveImg(url);
	    } else if (result == 0) { 
	        strStatus = "未获得授权";
					void permision.gotoAppPermissionSetting()
	    } else {
	        strStatus = "被永久拒绝权限"
				  void permision.gotoAppPermissionSetting()
	    }
	},

    //保存图片
    saveImg(path) {
      wx.saveImageToPhotosAlbum({
        filePath: path,
        success: res => {
          wx.hideLoading();
        },
        fail: rej => {
          wx.hideLoading();
          wx.showToast({
            title: '保存图片失败',
            icon: 'none'
          });
        }
      });
    },

    // 倒计时
    countTime() {
      var d = 86400000,
          h = 3600000,
          n = 60000,
          end = this.showItemDate.ends_at,
          server = this.showItemMeta.server_time,
          arr = String(end).split(/\D/),
          newArr = String(server).split(/\D/);
      newArr = newArr.map(Number);
      arr = arr.map(Number);
      var serverTime = new Date(newArr[0], newArr[1] - 1, newArr[2], newArr[3], newArr[4], newArr[5]).getTime();
      var endTime = new Date(arr[0], arr[1] - 1, arr[2], arr[3], arr[4], arr[5]).getTime(); //计算开始时间跟结束时间的差值

      var timeDiff = endTime - serverTime; // 在本地计算倒计时

      var allTime = this.endTime.count + 1000;
      this.setData({
        'endTime.count': allTime
      }); // this.endTime.count += 1000;

      var interval = timeDiff - this.endTime.count;

      if (interval < d) {
        this.setData({
          endtype: 1
        });

        if (interval < 0) {
          //		        	活动结束
          this.showItem(this.showItemDate.id);
          clearInterval(this.timer); // 			this.$emit('end',this.index)
        } else {
          var day = Math.floor(interval / d);
          Math.floor(interval -= day * d);
          var hour = Math.floor(interval / h);
          Math.floor(interval -= hour * h);
          var minute = Math.floor(interval / n);
          var second = Math.floor(interval % n / 1000);
          this.setData({
            'endTime.day': day,
            'endTime.hour': hour,
            'endTime.minute': minute,
            'endTime.second': second
          });
        }
      } else {
        this.setData({
          endmessage: `${arr[1]} 月 ${arr[2]} 日，${arr[3]} : ${arr[4]} 结束`
        });
      }
    },

    jumpDetail() {
      var id = this.showItemDate.groupon.goods.id;
      var item_id = this.showItemDate.id;

      if (this.showItemDate.overdue_status == 0) {
        wx.navigateTo({
          url: '/pages/store/detail/detail?id=' + id + '&groupon_item_id=' + item_id
        });
      } else {
        wx.navigateTo({
          url: '/pages/store/detail/detail?id=' + id
        });
      }
    },

    jumpMore() {
      wx.navigateTo({
        url: '/pages/store/list/list'
      });
    },

    jumpOrder() {
      var order_no = this.showItemDate.order_no;
      wx.navigateTo({
        url: '/pages/order/detail/detail?no=' + order_no
      });
    },

    setData: function (obj) {
      let that = this;
      let keys = [];
      let val, data;
      Object.keys(obj).forEach(function (key) {
        keys = key.split('.');
        val = obj[key];
        data = that.$data;
        keys.forEach(function (key2, index) {
          if (index + 1 == keys.length) {
            that.$set(data, key2, val);
          } else {
            if (!data[key2]) {
              that.$set(data, key2, {});
            }
          }

          data = data[key2];
        });
      });
    }
  },
  computed: {},
  watch: {}
};
</script>
<style rel="stylesheet/less" lang="less">
    @import "collage";
</style>

