<template>
<view id="spread">
    <view class="spreadpage" v-if="init">
        <view class="content">
            <view class="content-top" :class="erweima.show_agent_tips ? '' : 'hidden'">
                邀请好友，当TA成功下单时，
            </view>
            <view class="content-bottom" :class="erweima.show_agent_tips ? '' : 'hidden'">
                您将获得一笔佣金
            </view>
            <view class="erweima">
                <image mode="widthFix" :src="erweima.agent_mini"></image>
                <view class="btn-box">
					<!-- #ifdef H5 -->
					<view class="save btn" :style="'color: ' + config.mainColor + '; border-color: ' + config.mainColor" v-if="erweima.agent_mini">
					    长按保存图片
					</view>
					<!-- #endif -->
                    <!-- #ifdef APP-PLUS || MP-WEIXIN-->
                    <view class="save btn" :style="'color: ' + config.mainColor + '; border-color: ' + config.mainColor" @tap="down" v-if="erweima.agent_mini">
                        保存图片
                    </view>
                    <!-- #endif -->
                    <!-- #ifdef MP-WEIXIN -->
                    <button class="btn share" :style="'background: ' + config.mainColor" type="warn" open-type="share">立即邀请</button>
                    <!-- #endif -->
					<!-- #ifdef APP-PLUS -->
					<button class="btn share" :style="'background: ' + config.mainColor" type="warn" @click="shareapp">立即邀请</button>
					<!-- #endif -->
					<!-- #ifdef H5 -->
					<button class="btn share" :style="'background: ' + config.mainColor" type="warn" @tap="togglePopup('middle-img')">立即邀请</button>
					<!-- #endif -->
					<!-- @click="shareapp" -->
                </view>
            </view>
        </view>
    </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 alert from "@/components/alert/alert";
import permision from "@/common/js/permission.js"

export default {
  data() {
    return {
      erweima: {},
      config: '',
      init: false,
      is_refused: false,
	  type:0
    };
  },

  onShareAppMessage(res) {
    return {
      title: this.erweima.share_title,
      path: '/pages/user/personal/personal?agent_code=' + this.erweima.agent_code,
      imageUrl: this.erweima.share_img
    };
  },

  onLoad() {
    // 第三方平台配置颜色
    var bgConfig = this.$cookieStorage.get('globalConfig') || '';
    this.setData({
      config: bgConfig
    });
  },
 
  onShow() {
    this.getspread();
  },

  components: {
    alert
  },
  methods: {
	  togglePopup(type) {
	  			this.type = type;
	  },
	  shareapp(){
	  		  var title = this.erweima.share_title;
	  		  var agent_code = this.erweima.agent_code;
			  var imageUrl = this.erweima.share_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/user/user/user?agent_code=' + agent_code,
	  				  				  type:1,
	  				  				  webUrl:'https://guojiang.club'
	  				  			  },
	  				       success: function (res) {
	  				           console.log("success:" + JSON.stringify(res));
	  				       },
	  				       fail: function (err) {
	  				           console.log("fail:" + JSON.stringify(err));
	  				       }
	  				   });
	  			  }
	  		  })
	  		  
	  		 
	  },
    closeAlert() {
      this.setData({
        is_refused: false
      });
    },

    getspread() {
		// #ifdef APP-PLUS || MP-WEIXIN
		let api = 'api/distribution/getMiniShareHomeInfo';
		let share_url = ''
		// #endif
		
		// #ifdef H5
		let api = 'api/distribution/getH5ShareHomeInfo';
		let  origin = window.location.origin;
		let share_url = origin + '/pages/index/index/index';
		// #endif
      this.$http.get({
        api: api,
		data:{
			share_url:share_url
		},
        header: {
          Authorization: this.$cookieStorage.get('user_token')
        }
      }).then(res => {
        if (res.statusCode == 200) {
          res = res.data;

          if (res.status) {
            this.setData({
              erweima: res.data,
              init: true
            });
			// #ifdef H5
				if (this.$wechat && this.$wechat.isWechat()) {  
					var title = this.erweima.share_title;
					var img= this.erweima.share_img;
					var agent_code = this.erweima.agent_code;
					var origin = window.location.origin;
					var path = origin+'/pages/user/personal/personal?agent_code=' + agent_code
					 this.$wechat.share({  
						  title: title,  
						  img:img,
						  desc:'果酱小店'
					},path);  
				} 
			// #endif  
          } else {
            wx.showModal({
              content: '请求失败，请稍后重试',
              showCancel: false
            });
          }
        } else {
          wx.showModal({
            content: '请求失败，请稍后重试',
            showCancel: false
          });
        }
      });
    },

    // 下载图片
    down() {
      if (this.erweima.agent_mini) {
        wx.showLoading({
          title: '正在下载',
          mask: true
        });
        this.$http.dowloadFile({
          api: this.erweima.agent_mini
        }).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)
			 		}
			 		
			 	}
			 })
			  this.requestAndroidPermission(res.tempFilePath);
			  // #endif
           
          } else {
            wx.hideLoading();
            wx.showToast({
              title: '下载图片失败',
              icon: 'none'
            });
          }
        }, err => {});
      }
    },
	//ios app授权
	requestIosPermission(url){
		var result = judgeIosPermission('photoLibrary');
		if(result){
			this.saveImg(url);
		} else{
			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 = "未获得授权";
					 permision.gotoAppPermissionSetting()
	    } else {
	        strStatus = "被永久拒绝权限"
					permision.gotoAppPermissionSetting()
	    }
	},

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

    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 "spread";
</style>
