var ut = require("../../../../utils/util.js"),
  e = require("../../../../utils/common.js"),
  a = require("../../../../utils/wxParse/wxParse.js"),
  s = getApp(),
  i = s.request,
  o = s.globalData.setting,
  os = o;
  var regeneratorRuntime = require('../../../../utils/runtime.js');

Page({
  data: {
    //activity_type:1,//活动类型 商家1 阶梯2 会员3
    p_status:1,//会员团的详细情况 1是正在行  2是成功  3失败
    sf_length: 1,//人数大于5

    erweima:false,
    meng:false,
    zk:true,
    stoid: o.stoid,
    hiddenName: true,
    teamlist:null,
    teamgroup:null,
    goods:null,//商品数据
    pindGoods: null,//拼单数据
    imageurl: o.imghost,
    pay_f:0,//支付是否成功
    order_sn:"",//订单编号
    canvasHidden:false,  //画画版
    screenWidth:0,

    pd_xx: 0, //弹框
    max_num:0,//最低成团人数
    min_price:0,//最低价格
    is_show:0,//加载完才显示

    share_img_localpath:"",  //分享图片的本地图片
    share_ewm_localpath: "", //分享的二维码本地图片
    share_head:"",           //分享头像的本地图片

    iurl:os.imghost,
    ct_price:0,//阶梯团成团价格
      sf_arr:null,

  },
  onLoad: function (t) {
      wx.setNavigationBarTitle({ title: "拼团订单",})
      var that=this; 
	    var th=this;
      //获取用户设备信息，屏幕宽度
      wx.getSystemInfo({
         success: res => {
            that.setData({ screenWidth: res.screenWidth })
         }
       })
      var pay_f = t.payf, order_sn = t.ordersn;
      this.setData({ pay_f: pay_f, order_sn: order_sn});
      this.init(order_sn);
	  
	  //-- 自定义海报 --
	  getApp().request.promiseGet("/api/weshop/goods/poster/page",{	
	  	data:{store_id:os.stoid, type:1, is_use:1 }
	  }).then(res=>{
	  	if(res.data.code==0 && res.data.data && res.data.data.pageData && res.data.data.pageData[0] ){
	 		
	  		var poster_data=res.data.data.pageData[0];
	  		var json_str=poster_data.jsonStr;	  		
	  		if(json_str){
	  			var json_data=JSON.parse(json_str);		
	  			if(json_data.bg_img){
	  				
	  				//-- 把图片那到本地 --
	  				wx.getImageInfo({
	  				  src:json_data.bg_img,
	  				  success: function(res) {
	  				    var path= res.path;
	  					th.setData({share_b_img:path})
	  				  },
	  				  fail: function(res) {}
	  				});
	  			}			  					
	  			th.setData({poster:json_data})					  							
	  		}			
	  	}
	  })


      getApp().getConfig(function (e) {
          th.setData({sto_sele_name_1: e.store_name})
      })
      getApp().getConfig2(function(e) {
          var json_d = JSON.parse(e.switch_list);
          th.setData({ bconfig: e,sys_switch:json_d});
      })

  },
  onShow:function () {
      getApp().check_can_share(this);
  },

  //关闭展开列表
  click:function(e){
    this.setData({
      hiddenName: !this.data.hiddenName,
      zk: !this.data.zk,
    })
  },
  //打开收起拼团列表
  czk:function(e){
    this.setData({
      zk:!this.data.zk,
      hiddenName: !this.data.hiddenName,
    })
  },
 //打开蒙板提示
  cmeng:function(e){
    this.setData({
      meng:!this.data.meng,
    })
  },

  //关闭蒙板提示
  cmc:function(e){
    this.setData({
      meng: !this.data.meng,
    })
  },
//打开二维码提示
  cerweima:function(e){
    this.setData({
      meng: !this.data.meng,
      erweima: !this.data.erweima,
    })
  },

  cerc:function(e){
    this.setData({
      erweima: !this.data.erweima,
      meng: !this.data.meng,
    })
  },

  async init( order_sn) {
     
        wx.showLoading();

        var goods_id = 0,//商品ID,
        pageteam=null,//
        original_img=null ,//商品图片
        order=null,//订单编号
        service_list=null,  //服务卡崇拜
        id = 0,//团购id
        pt_listno = "",//团编号
        pt_prom_id = 0, //活动id
        ee = this,
        team_id = 0,//活动id
        ordertx=[],//头像图片
        share_img=null,//分享图片
        teamlist=null,//活动表
        teamgroup=null,//活動从表
        max_num=0,//最低价格时的成团人数
        p_status=1;

      //--如果商家团的时候,这个要改---
      await  getApp().request.promisePost("/api/weshop/rechargeServicelist/vipAutoTuan", {
          data: {orderSn:order_sn,storeId:os.stoid }
      })

      await  getApp().request.promiseGet("/api/weshop/recharge/get/"+os.stoid+"/"+order_sn, {
      }).then(rs1=>{
          if(rs1.data.code==0){
              order=rs1.data.data;
          }
      })


    //获取order信息根据订单编号order_sn
    await getApp().request.promiseGet("/api/weshop/rechargeServicelist/page", {
      data: { store_id: os.stoid, order_id: order.order_id,}
    }).then(res => {
        service_list = res.data.data.pageData[0];
        pt_prom_id = service_list.prom_id;
        pt_listno = service_list.pt_listno;
    })

    if (this.data.payf || service_list.pt_status == 3) p_status = 3;  //失败
    if (service_list.pt_status == 2 || service_list.pt_status == 4 || service_list.pt_status == 5)
       p_status = 2;  //成功
    if (service_list.pt_status < 2 && !this.data.payf)
       p_status = 1; //正在进行
    if ( service_list.pt_status == 6)   p_status = 4; //支付尾款失败

    //多少人参团头像
    await getApp().request.promiseGet("/api/weshop/rechargeServicelist/pagePtList", {
      data: { store_id: o.stoid, pt_listno: pt_listno, }
    }).then(res => {
      ordertx = res.data.data.pageData;
    })

    var min_price=0;
    //获取活动表的信息根据活动pt_prom_id
    await getApp().request.promiseGet("/api/weshop/teamlist/get/" + os.stoid + "/" + pt_prom_id, {
      data: { }
    }).then(res => {
      if(res.data.code==0){
        teamlist=res.data.data;
        ee.data.prom_act=teamlist;
        ee.setData({
          teamlist:teamlist
        });
        var nt =ut.gettimestamp();
        teamlist.status=0;
     
         if (nt >= teamlist.start_time) teamlist.status = 1;
          goods_id = res.data.data.goods_id;
          id = res.data.data.id;
          share_img = ee.data.imageurl + res.data.data.share_imgurl;

           //----------查看阶梯团------------
          if (teamlist.ct_rylist != "" && teamlist.ct_rylist != null && teamlist.ct_rylist != undefined){
            var ct_rylist = JSON.parse(teamlist.ct_rylist);
            var max=0; var pri=0;

            ct_rylist.forEach(function (val,ind) {
              if(val.rynum>max){
                  max=val.rynum;
                   pri = val.price;
              }
            })
            max_num=max;
            min_price=pri;

          }
		  
        }

		//-- 商品地址 --
		original_img = ee.data.imageurl+ service_list.img_url,
		ee.setData({goods: service_list,image: original_img,})

		  
    })


      //因为主表没有pt_status这个字段
      order.pt_status=service_list.pt_status;
      order.is_zsorder=service_list.is_zsorder;

      //只装5个
      var ordertx2=[],sf_num=0,ct_nun=teamlist.ct_num;

      if(max_num){
         ct_nun=parseInt(max_num);
         if (ordertx && ct_nun < ordertx.length) ct_nun = ordertx.length;
      }

      if(ct_nun>5) ct_nun=5;
      for(var i=0;i<ct_nun;i++){
          if (ordertx && i >= ordertx.length) sf_num++
          else
            ordertx2.push(ordertx[i]);
      }



    //获取活动从表信息team_id:305暂时
    await getApp().request.promiseGet("/api/weshop/teamgroup/page" , {
      data: { store_id: os.stoid, listno: pt_listno, team_id: pt_prom_id }
    }).then(res => {
        teamgroup = res.data.data.pageData[0];
        if (teamgroup){
			     var buy_start_date = ut.formatTime(teamgroup.buy_start_date, "yyyy-MM-dd hh:mm:ss");
		    		teamgroup.buy_start_date=buy_start_date;
        }
    })

      var head=[];
      if(teamgroup.is_xuni_ct)  {
          head=teamgroup.xuni_head_id.split(",");
          order.is_xuni_ct=1;

          this.setData({head:head,});
      }



      var sf_arr=[];
      for (var i=0;i<sf_num;i++){

          if(teamgroup.is_xuni_ct){
              sf_arr.push(head[i]);
          }else {

              sf_arr.push(i);
          }
      }

         //获取团的价格
        var ct_price = 0, num_0 = ordertx.length;
        if (teamlist.kttype == 3 && teamlist.ct_rylist){

            var js_data = JSON.parse(teamlist.ct_rylist);
            js_data.forEach(function (val,ind) {
                if (num_0<=val.rynum && ct_price==0){
                    ct_price=val.price;
                }
             })
            if(ct_price==0)  ct_price=min_price;

            //-- 字符要改成json --
            ee.data.prom_act.ct_rylist=js_data
        }

    //获取大家都在团信息
    getApp().request.promiseGet("/api/weshop/teamlist/pageteam/1?store_id="+ os.stoid +"&is_end=0&is_show=1" , {
      data:{page:1,pageSize:2}
    }).then(res => {
		if(res.data.code==0 && res.data.data && res.data.data.pageData && res.data.data.pageData.length>0){
			pageteam = res.data.data.pageData;
			ee.setData({pageteam: pageteam,})  
		}
	        
    })

    //--当是成团的时候的操作--
    if(order.pt_status==2 || order.pt_status==4 || order.pt_status==5){
      //-- 设置值 --
      ee.setData({
        ordertx2: ordertx2, ordertx: ordertx, teamlist: teamlist, teamgroup: teamgroup, min_price: min_price,
            order: order,  share_img: share_img,max_num:max_num,
             pindGoods: teamlist,is_show:1,  zk:false,
            hiddenName: false, ct_price:ct_price,p_status:p_status,sf_arr:sf_arr});

             //--是否支付了尾款--
             if(order.pt_status==4 || order.pt_status==5){
                  ee.setData({is_pay_wk:1});
             }
    }else{
      console.log("239什么鬼", teamlist);
        //设置值
      ee.setData({
        ordertx2: ordertx2, ordertx: ordertx, teamlist: teamlist, teamgroup: teamgroup,
        order: order, p_status: p_status, min_price:min_price,
          share_img: share_img, max_num: max_num, pindGoods: teamlist, is_show: 1,
           ct_price: ct_price, p_status: p_status,sf_arr:sf_arr});
    }

    wx.hideLoading();

    wx.setNavigationBarTitle({
      title: "拼团详情",
    })
  
    ee.countDown2();

    //获取分享图片的本地地址
    var path2 = os.imghost + teamlist.share_imgurl;
    wx.getImageInfo({
      src: path2,
      success: function (res) {
        //res.path是网络图片的本地地址
        ee.data.share_img_localpath = res.path;
      },
      fail: function (res) {
        //失败回调
      }
    });


  },
  //---小于10的格式化函数----
  timeFormat(param) {
    return param < 10 ? '0' + param : param;
  },
  countDown2() {
        var th = this;
        // 获取当前时间，同时得到活动结束时间数组
        var newTime = ut.gettimestamp();
        var o = this.data.teamgroup;
		if(!o) return false;
				
        var endTime = o.kt_end_time;
        if (o.status == 0) endTime = o.start_time;

        //看一下，是否要支付尾款
        if(o.team_type==3 && th.data.goods.pt_status==2){
            endTime = o.wk_end_time;
        }
   
        let obj = null;
        // 如果活动未结束，对时间进行处理
        if (endTime - newTime > 0) {
          let time = (endTime - newTime);
          // 获取天、时、分、秒
          let day = parseInt(time / (60 * 60 * 24));
          let hou = parseInt(time % (60 * 60 * 24) / 3600);
          let min = parseInt(time % (60 * 60 * 24) % 3600 / 60);
          let sec = parseInt(time % (60 * 60 * 24) % 3600 % 60);
          obj = {
            day: this.timeFormat(day),
            hou: this.timeFormat(hou),
            min: this.timeFormat(min),
            sec: this.timeFormat(sec)
          }
        } else {
          //活动已结束，全部设置为'00'
          obj = {
            day: '00',
            hou: '00',
            min: '00',
            sec: '00'
          }
        }
        var txt = "pindGoods.djs";
        th.setData({
          obj: obj
        });
        setTimeout(th.countDown2, 1000);
  },

   //--定义的保存图片方法，分享团---
  saveImageToPhotosAlbum: function () {
        //类型  0普通商品 1秒杀商品  2商家和会员团  3阶梯团
        var type=1;
        if(this.data.teamlist.kttype==3) type=2;

        wx.showLoading({ title: '生成中...', })
        var that = this, th = that;
        //设置画板显示，才能开始绘图
        that.setData({
            canvasHidden: true,
        })

        if(this.data.share_hidden) {
          this.setData({
              share_hidden: false,
          });
        };

        var app = getApp();
        var unit = that.data.screenWidth / 750 * 1.35;
        var scene=th.data.teamgroup.id;
        var goods_id=th.data.teamlist.goods_id;
        var user_id=getApp().globalData.user_id?getApp().globalData.user_id:0;
        if(user_id>0){
           scene+="_"+user_id;
        }
        if(goods_id !==""){
          scene+="_"+goods_id;
        }

        //二微码
        var path3 = os.url+ "/api/wx/open/app/user/getWeAppEwm/"+
           os.stoid+"?sceneValue="+scene+"&pageValue=packageA/pages/serviceCard_pd/team_show/team_show";

           console.log(path3,6000);

        //读取文件成功则OK--
        wx.getImageInfo({
            src: path3,
            success:function (res) {
              console.log(res,5000);
                //回调写法
                th.get_head_temp(th.get_goods_temp,function () {
                    var vpath = res.path;
                    var context = wx.createCanvasContext('share');


                    //先画背景
                    var pg_path = "../../../../images/share/share_bg.png";
					//-- 如果有自定义海报的时候，判断背景的图片 --
					if(th.data.share_b_img){
						pg_path=th.data.share_b_img;
					}

					var share_title=th.data.teamlist.share_title;
					if(!share_title)
                        share_title=th.data.teamlist.title;

                    var act_time='';
                    if (!th.data.share_b_img){ // 如果是普通商品，绘制新海报
                        th.drawPoster(context, unit, th.data.share_img_localpath, vpath, type);
                    } else {

                        context.drawImage(pg_path, 0, 0, 554 * unit, 899 * unit);

                        let nick=app.globalData.userInfo?app.globalData.userInfo.nickname:'';
                        //-- 是自定义海报的情况下 --
                        if (th.data.poster && parseInt(th.data.poster.style) == 2) {
                            //在线上分享人的情况下
                            if (parseInt(th.data.poster.show_headpic)) {
                                //获取坐标
                                var x = parseFloat(th.data.poster.head_x) * 2;
                                var y = parseFloat(th.data.poster.head_y) * 2;
                                var x1 = (x + 90) * unit;
                                var y1 = (y + 50) * unit;
                                //--昵称---
                                context.setFontSize(24 * unit)
                                context.setFillStyle("black")
                                context.fillText(nick, x1, y1);
                                var width = 24 * nick.length * unit + 4 * unit;
                                //强烈推荐 改许程
                                var tj_path = "../../../../images/share/q_tj.png";
                                context.drawImage(tj_path, x1 + width, y1 - 22 * unit, 85 * unit, 30 * unit);
                                context.setFontSize(16 * unit)
                                context.setLineJoin('round'); //交点设置成圆角
                                context.setFillStyle("white")
                                context.fillText('强烈推荐', x1 + width + 8 * unit, y1 - 1 * unit);
                            }

                        } else {
                            //--昵称---
                            context.setFontSize(24 * unit)
                            context.setFillStyle("black")
                            context.fillText(nick, 152 * unit, 76 * unit);
                            var width = 24 * nick.length * unit + 2 * unit;
                            //强烈推荐
                            var tj_path = "../../../../images/share/q_tj.png";
                            context.drawImage(tj_path, 152 * unit + width, 54 * unit, 110 * unit, 30 * unit);
                            context.setFontSize(18 * unit)
                            context.setFillStyle("white")
                            context.fillText('强烈推荐', 152 * unit + width + 20 * unit, 76 * unit);
                        }


                        //---产品名称---
                        context.setFontSize(21.3 * unit);
                        context.setFillStyle("black");

                        th.draw_Text(context,share_title,
                            38 * unit, 180 * unit, 200 * unit, 279 * unit, unit);
                        //------产品的价格-------
                        context.setFontSize(24 * unit)
                        context.setFillStyle("red")

                        var pri0 = th.data.teamlist.price;
                        pri0=parseFloat(pri0).toFixed(2);
                        var wd1=th.data.screenWidth-ut.measureText(pri0, 31 * unit)-25;
                        context.fillText("￥", wd1-15, 180 * unit);
                        context.setFontSize(31 * unit)
                        context.fillText(pri0, wd1, 180 * unit);

                        //---市场价划掉---
                        context.setFillStyle("gray")
                        context.setFontSize(22 * unit)
                        pri0= "￥" + parseFloat(th.data.goods.market_price).toFixed(2);
                        var wd2=th.data.screenWidth-ut.measureText(pri0, 22 * unit)-25;
                        context.fillText(pri0, wd2, 210 * unit);

                        context.setStrokeStyle('gray')
                        context.setLineWidth(1 * unit)
                        context.moveTo(wd2-5, 204 * unit)
                        context.lineTo(wd2+ut.measureText(pri0, 22 * unit)+5, 204 * unit)
                        context.stroke();
                        console.log(th.data.share_img_localpath);


                        //---中间大图---
                        context.drawImage(th.data.share_img_localpath, 68 * unit, 242 * unit, 410 * unit, 410 * unit);

                        var g_ct=th.data.teamlist.ct_num-th.data.ordertx.length;
                        var wz= "";
                        if(g_ct>0)  wz="还差"+g_ct+"人成团，";
                        else{
                            g_ct= th.data.max_num -th.data.ordertx.length;
                            if(g_ct>0){
                                wz="还差"+g_ct+"人享最低优惠，";
                            }else{
                                wz="已享受最优惠，";
                            }
                        }

                        //-------大图后面就不一样了-----------
                        switch (type) {
                            case 1://会员团和商家团的展示
                                //---画线---
                                context.setLineWidth(1 * unit)
                                context.moveTo(32 * unit, 670 * unit)
                                context.lineTo(520 * unit, 670 * unit)
                                context.stroke();

                                //---文字---
                                context.setFontSize(22 * unit)
                                context.setFillStyle("black")
                                context.fillText("好物拼起来,拼拼更划算", 40 * unit, 726 * unit);

                                //绘制成团图片
                                var ct_img ="../../../../images/share/ct_num.png";
                                context.drawImage(ct_img, 40 * unit, 740 * unit, 120 * unit, 30 * unit);
                                var ct_num = th.data.teamlist.ct_num;
                                context.setFontSize(14 * unit)

                                context.setFillStyle("red")
                                if(ct_num<10){
                                    context.fillText(ct_num+"人拼团", 92 * unit, 760 * unit);
                                }else{
                                    context.fillText(ct_num+"人拼团", 86 * unit, 760 * unit);
                                }
                                context.setFontSize(22 * unit)
                                context.fillText("已拼"+th.data.teamlist.buy_num+"份", 166 * unit, 763 * unit);
                                context.setFillStyle("gray")
                                context.fillText(wz+"快来和我一起拼团吧！", 40 * unit, 826 * unit);
                                context.setFillStyle("black")

                                context.setFontSize(22 * unit)
                                context.fillText("长按识别二维码，立即参团", 40 * unit, 856 * unit);
                                //---二维吗图---
                                //-- 自定义海报 --
                                if(th.data.poster){
                                    var erm_x= parseFloat(th.data.poster.ewm_x)*2;
                                    var erm_y= parseFloat(th.data.poster.ewm_y)*2;
                                    context.drawImage(vpath, erm_x * unit, erm_y * unit, 120 * unit, 120 * unit);
                                }else{
                                    //---二维吗图---
                                    context.drawImage(vpath, 420 * unit, 726 * unit, 120 * unit, 120 * unit);
                                }
                                break
                            case 2://阶梯团的展示
                                //---画线---
                                context.setLineWidth(1 * unit)
                                context.moveTo(32 * unit, 670 * unit)
                                context.lineTo(520 * unit, 670 * unit)
                                context.stroke();
                                //---文字---
                                context.setFontSize(22 * unit)
                                context.setFillStyle("black")
                                context.fillText("好物拼起来,拼拼更划算", 40 * unit, 726 * unit);
                                //---绘制中间阶梯的价格---
                                var list= JSON.parse(th.data.teamlist.ct_rylist);
                                for(var i=0; i<list.length;i++){
                                    var item=list[i];
                                    var wi=i*90*unit;
                                    context.setFontSize(16 * unit)
                                    context.setFillStyle("red")
                                    context.fillText("￥", 40 * unit+wi, 756 * unit);
                                    context.setFontSize(22 * unit)
                                    var pri=parseFloat(item.price).toFixed(2);
                                    context.fillText(pri, 56 * unit+wi, 756 * unit);
                                    context.setFillStyle("gray")
                                    context.fillText("满"+item.rynum+"人", 40 * unit+wi, 786 * unit);
                                }

                                //----------------下面部分----------------
                                context.setFillStyle("gray")
                                context.fillText(wz+"快来和我一起拼团吧！", 40 * unit, 830 * unit);
                                context.setFillStyle("black")
                                context.setFontSize(22 * unit)

                                context.fillText("长按识别二维码，立即参团", 40 * unit, 860 * unit);
                                //---二维吗图---
                                //-- 自定义海报 --
                                if(th.data.poster){
                                    var erm_x= parseFloat(th.data.poster.ewm_x)*2;
                                    var erm_y= parseFloat(th.data.poster.ewm_y)*2;
                                    context.drawImage(vpath, erm_x * unit, erm_y * unit, 120 * unit, 120 * unit);
                                }else{
                                    //---二维吗图---
                                    context.drawImage(vpath, 420 * unit, 726 * unit, 120 * unit, 120 * unit);
                                }
                                break
                        }

                        //--- 如果是自定义海报的时候 ---
                        if(th.data.poster && parseInt(th.data.poster.style)==2){

                            //如果显示会员信息的话
                            if(parseInt(th.data.poster.show_headpic)){
                                //获取坐标
                                var x= parseFloat(th.data.poster.head_x)*2;
                                var y=parseFloat(th.data.poster.head_y)*2;
                                //---绘制圆形要放在最后----
                                context.save();
                                context.beginPath();
                                var h_x = x* unit;
                                var h_y = y * unit;
                                var h_r = 40 * unit;
                                var cx = h_x + h_r;
                                var cy = h_y + h_r;
                                context.arc(cx, cy, h_r, 0, Math.PI * 2, false);
                                context.closePath();
                                context.fill();
                                context.clip();
                                context.drawImage(th.data.share_head, h_x, h_y, h_r * 2, h_r * 2);
                                context.restore();
                            }

                        }else{
                            //---绘制圆形要放在最后----
                            context.save();
                            context.beginPath();
                            var h_x = 60 * unit;
                            var h_y = 24 * unit;
                            var h_r = 40 * unit;
                            var cx = h_x + h_r;
                            var cy = h_y + h_r;
                            context.arc(cx, cy, h_r, 0, Math.PI * 2, false);
                            context.closePath();
                            context.fill();
                            context.clip();
                            context.drawImage(th.data.share_head, h_x, h_y, h_r * 2, h_r * 2);
                            context.restore();
                        }
                    }

                    //把画板内容绘制成图片，并回调 画板图片路径
                    context.draw(false, function () {
                        setTimeout(function () {
                            wx.canvasToTempFilePath({
                                x: 0, y: 0,
                                width: 750,
                                height: 1217,
                                destWidth: 750 * 750 / that.data.screenWidth,
                                destHeight: 1217 * 750 / that.data.screenWidth,
                                canvasId: 'share',
                                success: function (res) {

                                    that.setData({
                                        shareImgPath: res.tempFilePath, canvasHidden: false,
                                    })
                                    if (!res.tempFilePath) {
                                        wx.showModal({
                                            title: '提示',
                                            content: '图片绘制中，请稍后重试',
                                            showCancel: false
                                        })
                                        return false;
                                    }

                                    // wx.previewImage({
                                    //     //将图片预览出来
                                    //     urls: [that.data.shareImgPath]
                                    // });

                                    that.setData({
                                        showPoster: true,
                                    });

                                    wx.hideLoading();
                                }
                            })
                        },500)
                    });
                });
            }
        });
    },


  //文本换行 参数：1、canvas对象，2、文本 3、距离左侧的距离 4、距离顶部的距离 5、6、文本的宽度
  draw_Text: function (ctx, str, leftWidth, initHeight, titleHeight, canvasWidth, unit) {
    var lineWidth = 0;
    var lastSubStrIndex = 0; //每次开始截取的字符串的索引
    var han = 0;
    for (let i = 0; i < str.length; i++) {
      if (han == 2) return;
   
      //lineWidth += ctx.measureText(str[i]).width;
      lineWidth += ut.measureText(str[i], 21.3 * unit);

      if (lineWidth > canvasWidth) {
        han++;
        if (han == 2)
          ctx.fillText(str.substring(lastSubStrIndex, i) + '...', leftWidth, initHeight); //绘制截取部分
        else
          ctx.fillText(str.substring(lastSubStrIndex, i), leftWidth, initHeight);

        initHeight += 22; //22为字体的高度
        lineWidth = 0;
        lastSubStrIndex = i;
        titleHeight += 20;
      }
      if (i == str.length - 1) { //绘制剩余部分
        ctx.fillText(str.substring(lastSubStrIndex, i + 1), leftWidth, initHeight);
      }
    }
  },  

  //c点击打开拼团弹窗
  cpd: function() {
    console.log("heheh");
    this.setData({  pd_xx: 1,})
  },

  //点击关闭拼团弹窗
  close_pt_xx: function() {
    this.setData({ pd_xx: 0, })
  },

  go_goodsinfo:function (e) {
     var index=e.currentTarget.dataset.index;
     var item=this.data.pageteam[index];
     var gid=item.goods_id;
     var url="/pages/goods/goodsInfo/goodsInfo?goods_id="+gid+"&prom_id="+item.id+"&prom_type=6";
     if(item.goods_type==1){
         url="/packageA/pages/serviceCard_pd/goodsInfo/goodsInfo?goods_id="+gid+"&prom_id="+item.id+"&prom_type=6";
     }
     getApp().goto(url);     //跳到非tabbar页
  },

    gohome:function () {
        getApp().goto("/pages/index/index/index");
    },

    //--获取头像的本地缓存,回调写法--
    get_head_temp:function (tt,func) {
        var ee=this;
        if(ee.data.share_head){
            tt(func);
            return false;
        }
        //---获取分享图片的本地地址,头像和商品图片----
        var path2 = getApp().globalData.userInfo?getApp().globalData.userInfo.head_pic:'';
        if(path2==""){
            ee.data.share_head ="../../../../images/share/hui_hear_pic.png";
            tt(func);
        }else {
            path2=path2.replace("http://thirdwx.qlogo.cn","https://wx.qlogo.cn");
            path2=path2.replace("https://thirdwx.qlogo.cn","https://wx.qlogo.cn");
            wx.getImageInfo({
                src: path2,
                success: function (res) {
                    //res.path是网络图片的本地地址
                    ee.data.share_head = res.path;
                    tt(func);;
                },
                fail: function (res) {
                    ee.data.share_head = "../../../../images/share/hui_hear_pic.png"; //分享的图片不能用网络的
                    tt(func);
                }
            });
        }
    },

    //--获取商品图片的本地缓存，回调写法--
    get_goods_temp:function (tt) {
        var ee=this;
        if(ee.data.share_img_localpath) {
            tt();
            return false;
        }
        var path2 = os.imghost + ee.data.teamlist.share_imgurl;
        //获取商品是分享图信息
        wx.getImageInfo({
            src:  path2,
            success: function (res) {
                //res.path是网络图片的本地地址
                ee.data.share_img_localpath = res.path;
                tt();
            },
            fail: function (res) {
                //获取默认空白图
                wx.getImageInfo({
                    src:os.imghost+'/miniapp/images/default_g_img.gif',
                    success: function(res) {
                        ee.data.share_img_localpath = res.path; //分享的图片不能用网络的
                        tt();
                    }
                })
            }
        });
    },


    //跳转到支付尾款
    go_pay_wk:function(){
      var url = "/packageA/pages/serviceCard_pd/cart_wk/cart_wk?order_id=" + this.data.order.order_id;
      getApp().goto(url);
    },

    img_show_err:function(e){
        var err_img = e.currentTarget.dataset.err;
        var ob={};
        ob[err_img] = this.data.iurl + "/miniapp/images/default_g_img.gif";
        this.setData(ob);
        
    },

    //------ 分享配置 --------
    onShareAppMessage: function (e) {
        getApp().globalData.no_clear=1;
        var th=this;
        var scene=this.data.teamgroup.id;
        var goods_id=this.data.teamlist.goods_id;
        var url="/packageA/pages/serviceCard_pd/team_show/team_show?tg_id="+scene+"&goods_id="+goods_id;
        //--分享图片--
        var img=th.data.iurl+th.data.teamlist.share_imgurl;
        //--把会员分享出去--
        if(getApp().globalData.user_id){
            if(url.indexOf("?")>0)
                url+="&first_leader="+getApp().globalData.user_id;
            else
                url+="?first_leader="+getApp().globalData.user_id;
        }
        // console.log('url+++++>>>>>', url, th.data.teamlist.title);

        var share_title=th.data.teamlist.title;
        if(th.data.teamlist.share_title){
            share_title=th.data.teamlist.share_title;
        }
        return {
            path:url,
            title: share_title,
            imageUrl: img,
        }
    },
		
		clickShare() {
            // if(!getApp().globalData.user_id){
            //     getApp().goto("/packageE/pages/togoin/togoin");
            //     return false;
            // }
			this.setData({
				share_hidden: true,
			});
		},
		
		send() {
			this.setData({
				share_hidden:false,
			});
		},
		
		cancel() {
			this.setData({
				share_hidden:false,
			});
		},


    closePoster() {
        this.setData({
            showPoster: false,
        });
    },


    // 保存图片到手机
    savePic() {
        console.log('保存图片');
        var self = this;
        // 获取用户的当前设置，返回值中有小程序已经向用户请求过的权限
        this.getSetting().then((res) => {
            // 判断用户是否授权了保存到相册的权限，如果没有发起授权
            if (!res.authSetting['scope.writePhotosAlbum']) {
                this.authorize().then(() => {
                    // 同意授权后保存下载文件
                    this.saveImage(self.data.shareImgPath)
                        .then(() => {
                            self.setData({
                                showPoster: false
                            });
                        });
                })
            } else {
                // 如果已经授权，保存下载文件
                this.saveImage(self.data.shareImgPath)
                    .then(() => {
                        self.setData({
                            showPoster: false
                        });
                    });
            }

        })
    },


    // 保存图片到系统相册
    saveImage(saveUrl) {
        var self = this;
        return new Promise((resolve, reject) => {
            wx.saveImageToPhotosAlbum({
                filePath: saveUrl,
                success: (res) => {
                    wx.showToast({
                        title: '保存成功',
                        duration: 1000,
                    });
                    self.setData({
                        showPlaybill: 'true'
                    });
                    resolve();
                },
                fail: () => {
                    wx.showToast({
                        title: '保存失败',
                        duration: 1000,
                    });
                }
            })
        })
    },

    // 获取用户已经授予了哪些权限
    getSetting() {
        return new Promise((resolve, reject) => {
            wx.getSetting({
                success: res => {
                    resolve(res)
                }
            })
        })
    },

    // 发起首次授权请求
    authorize() {
        // isFirst 用来记录是否为首次发起授权，
        // 如果首次授权拒绝后，isFirst赋值为1
        let isFirst = wx.getStorageSync('isFirst') || 0;
        return new Promise((resolve, reject) => {
            wx.authorize({
                scope: 'scope.writePhotosAlbum',
                // 同意授权
                success: () => {
                    resolve();
                },
                // 拒绝授权,这里是用户拒绝授权后的回调
                fail: res => {
                    if(isFirst === 0) {
                        wx.setStorageSync('isFirst', 1);
                        wx.showToast({
                            title: '保存失败',
                            icon: 'none',
                            duration: 1000
                        })
                    } else {
                        this.showModal();
                    }
                    console.log('拒绝授权');
                    reject();
                }
            })
        })
    },


    go_to:function (e) {
        var url=e.currentTarget.dataset.url;
        getApp().goto(url);
    },

    //-- 先版绘制 --img 是中间的大图
    drawPoster(context, unit, img, vpath, type) {

        var self=this;

        // 1.灰色背景
        context.setFillStyle('#f2f1f6');
        context.rect(0, 0, 554 * unit, 899 * unit);
        context.fill();

        // 2.商城名称
        let shopName = this.data.sto_sele_name_1;
        context.setTextAlign('center');
        context.setFontSize(26 * unit);
        context.setFillStyle('black');
        context.fillText(shopName, 277 * unit, 60 * unit);

        if(getApp().globalData.userInfo) {
            // 3.推荐来源
            let fromText = `来自${getApp().globalData.userInfo.nickname}的推荐`;
            context.setTextAlign('center');
            context.setFontSize(22 * unit);
            context.setFillStyle('#96959a');
            context.fillText(fromText, 277 * unit, 105 * unit);
        }

        // 4.海报背景
        context.setFillStyle('white');
        context.fillRect(37 * unit, 157 * unit, 480 * unit, 673 * unit);

        // 5.商品图片
        // 图片的x坐标
        let bg_x = 37 * unit
        // 图片的y坐标
        let bg_y = 157 * unit
        // 图片宽度
        let bg_w = 480 * unit
        // 图片高度
        let bg_h = 474 * unit
        // 图片圆角
        let bg_r = 4

        // 绘制海报背景图片圆角
        context.save()
        context.beginPath()
        context.arc(bg_x + bg_r, bg_y + bg_r, bg_r, Math.PI, Math.PI * 1.5)
        context.arc(bg_x + bg_w - bg_r, bg_y + bg_r, bg_r, Math.PI * 1.5, Math.PI * 2)
        context.arc(bg_x + bg_w, bg_y + bg_h, bg_r, 0, Math.PI * 0.5)
        context.arc(bg_x, bg_y + bg_h, 0, Math.PI * 0.5, Math.PI)
        context.clip()
        context.drawImage(img, bg_x, bg_y, bg_w, bg_h);
        context.restore();

        // 6.强烈推荐
        let src = '';
        context.beginPath();


        if (type == 1) { // 商家和会员团
            src = '../../../../images/share/ct_num.png';
            context.drawImage(src, 54 * unit, 648 * unit, 120 * unit, 30 * unit);
            context.setTextAlign('left');

            let ct_num = self.data.prom_act.ct_num;
            context.setFontSize(16 * unit)
            context.font = 'normal';
            context.setFillStyle("red")
            if (ct_num < 10) {
                context.fillText(ct_num + "人拼团", 100 * unit, 670 * unit);
            } else {
                context.fillText(ct_num + "人拼团", 96 * unit, 670 * unit);
            }
            context.setFontSize(22 * unit)
            context.fillText("已拼" + self.data.prom_act.buy_num + "份", 186 * unit, 672 * unit);




        }

        if (type == 2) { // 阶梯团
            let list = self.data.prom_act.ct_rylist;
            for (let i = 0; i < list.length; i++) {
                let item = list[i];
                let wi = i * 90 * unit;
                context.font = 'normal';
                context.setTextAlign('left');
                context.setFontSize(16 * unit)
                context.setFillStyle("red")
                context.fillText("￥", 50 * unit + wi, 680 * unit);
                context.setFontSize(22 * unit)
                let pri = parseFloat(item.price).toFixed(2);
                context.fillText(pri, 66 * unit + wi, 680 * unit);


                context.setFillStyle("gray")
                context.fillText("满" + item.rynum + "人", 50 * unit + wi, 716 * unit);
            }


            var wp=  52 * unit;
            var hp=755 * unit
            self.draw_pos_price(context,wp,hp,this.data.goods.show_price,unit);
        }

        // 7.商品价格
        if (type != 2) {
            let price = this.data.teamlist.price;
            price = parseFloat(price).toFixed(2);
            context.setFontSize(32 * unit);
            context.setFillStyle('#DE1117');

            context.fillText('￥' + price, 54 * unit, 735 * unit);
            var wp= 62 * unit+ut.measureText('￥' + price, 32 * unit);
            var hp=735 * unit
            this.draw_pos_price(context,wp,hp,this.data.goods.show_price,unit);
        }

        // 8.商品标题
        context.setFontSize(20 * unit);
        context.setFillStyle('#898989');
        getApp().draw_Text(context, this.data.goods.service_name, 54 * unit, 800 * unit, 240 * unit, 280 * unit, unit, 1);
        // 9.小程序码
        context.drawImage(vpath, 375 * unit, 660 * unit, 120 * unit, 120 * unit);
        context.setFontSize(16 * unit);
        context.setFillStyle('#777');
        context.fillText('长按识别二维码', 378 * unit, 810 * unit);

        // 10.竖线
        context.beginPath();
        context.setFillStyle('#eee');
        context.rect(354 * unit, 670 * unit, 1 * unit, 130 * unit);
        context.fill();
    },

    //---市场价划掉---
    draw_pos_price(context,w,h,market_price,unit){

        if(!this.data.sys_switch) return false;
        if(!this.data.sys_switch.is_retail_price) return false;
        context.setFillStyle("gray")
        context.setFontSize(22 * unit)
        var pri0 = "￥" + market_price.toFixed(2);
        context.fillText(pri0, w, h);

        var c_h=h-6;
        context.setStrokeStyle('gray');
        context.setLineWidth(1 * unit);
        context.moveTo(w - 5, c_h);
        context.lineTo(w + ut.measureText(pri0, 22 * unit) + 5, c_h);
        context.stroke();

    },

})

