const app = getApp();
const commonUtil = require("../../utils/commonUtil");
const dateUtil = require("../../utils/dateUtil");

const {
  wxml,
  style
} = require("./demo.js");
var QQMapWX = require("../../utils/qqmap-wx-jssdk.min.js");
var qqmapsdk;
import {
  customRequest
} from '../../utils/request.js';
Page({
  data: {
    // currCode: '',
    fromBocai: true, // 商家后台职位的判断
    kefuShow: false, // 客服抽屉的显隐
    storeJobId: "",
    iosDialog: false,
    //职位ID
    searchForm: {
      storeJobId: "",
      lng: "",
      lat: "",
    },
    fullScreen: false,
    bclr: "",
    djxx: "",
    currIndex: "1",
    jobDetail: {}, //详情
    wxCode: "",
    pbtm: 0,
    shareTitle: "",
    isCollect: false,
    src: "",
    word: "woca",
    phoneDialog: false,
    isImg: true,
    labelColor: ["#c41d7f", "#096dd9", "#531dab", "#d46b08", "#389e0d", "#08979c", "#cf1322"],
    bgColor: ["#fff0f6", "#e6f7ff", "#f9f0ff", "#fff7e6", "#f6ffed", "#e6fffb", "#fff1f0"],
    wxml: {
      text: "啊啊按",
    },
    addressNew: "",
    citys: "",
    showSexAgeText: "",
    fuWuFei: "",
    isServicePriceShow: true,
    isAgency: true,
    isShareShow: false,
    managerRoleClassify: false, // 管理员权限
    serviceInfo: app.globalData.serviceInfo,
    isMaskShow: false,
    onSiteRemark: "",
    img: "https://matripe-cms.oss-cn-beijing.aliyuncs.com/1shoudan/bg.png",
    canvasImg: "",
    isLoading: true,
    iosDialogTobe: false, // 成为代理弹窗显示
    userInfo: {},
    shareDetailImg: "https://matripe-cms.oss-cn-beijing.aliyuncs.com/1shoudan/share.png",
    posterImg: "",
  },
  showdialog () {
    this.setData({
      iosDialog: true,
    });
  },
  closeDialog () {
    this.setData({
      iosDialog: false,
    });
  },
  onShow () {
    var that = this;
    app.getLoginUserTokenInfo().then(() => {
      that.setData({
        isAgency: app.globalData.loginUserInfo.agencyStatus == 1 ? true : false,
        corpUserFlag: app.globalData.loginUserInfo.corpUserFlag,
        managerRoleClassify: app.globalData.loginUserInfo.managerRoleClassify,
        userInfo: app.globalData.loginUserInfo,
      });
      console.log(this.data.searchForm.storeJobId);
      if (app.globalData.isLogin) {
        that.setData({
          // agencyStatus: app.globalData.agencyStatus,
          userInfo: app.globalData.loginUserInfo,
          isLogin: app.globalData.isLogin,
          isLoading: true,
        });
        that.getCode();
      }
    });
    // this.setData({
    //   isLogin: app.globalData.isLogin,
    //   isLoading: true,
    //   // userInfo:{...app.globalData.loginUserInfo,  agencyStatus:0},
    // });


    // else {
    //   wx.setStorageSync("comeFromPage", "detail");
    //   // wx.setStorageSync("comeFromPageParam", { storeJobId: that.data.searchForm.storeJobId });
    //   wx.navigateTo({
    //     url: "/pages/login/index",
    //   });
    //   return
    //   // this.wxLogin();
    // }
    if (this.data.isSharePage) {
      this.getStoreJobDetailById();

    }


    console.log(that.data.userInfo);
  },
  showphone: function () {
    var that = this;
    wx.makePhoneCall({
      // number: that.data.jobDetail.assistantUserTel + ""
      phoneNumber: that.data.serviceInfo.workPhone || "0371-6611 3723",
    });
  },
  close: function () {
    this.setData({
      phoneDialog: false,
    });
  },
  wxLogin () {
    var that = this;
    wx.login({
      success (res) {
        if (res.code) {
          that.setData({
            wxCode: res.code,
          });
        } else {
          console.log("获取code失败！" + res.errMsg);
        }
      },
    });
  },
  kefu (e) {
    console.log(e);
    console.log('jobDetail', this.data.jobDetail);
    app.vibrateShort()
    // if (this.data.fromBocai) {
    //   if (this.data.jobDetail.customServiceUsers.length > 0) {
    //     this.setData({
    //       kefuShow: true
    //     })
    //   } else {
    //     wx.showToast({
    //       title: '该岗位暂无客服',
    //       icon: 'none',
    //       duration: 2000
    //     })
    //   }


    // } else {
    let url = e.currentTarget.dataset.customServiceUrl
    // console.log('/pages/detail/index?storeJobId' + this.data.searchForm.storeJobId);
    console.log('app.globalData.loginUserInfo.agencyId', app.globalData.loginUserInfo.agencyId);
    if (e.currentTarget.dataset.customServiceUrl != '') {
      wx.openCustomerServiceChat({
        // extInfo: { url: 'https://work.weixin.qq.com/kfid/kfc84d8465f4c633511' },
        extInfo: {
          url: url || 'https://work.weixin.qq.com/kfid/kfc84d8465f4c633511'
        },
        showMessageCard: true,
        sendMessagePath: `/pages/detail/index.html?storeJobId=${this.data.searchForm.storeJobId}&agencyId=${app.globalData.loginUserInfo.agencyId}`,
        // sendMessageImg:'../../assets/images/jbn.png',
        corpId: 'wwc227639d3a136c8d',
        success (res) {
          console.log('res', res);
        },
        fail (err) {
          console.log('err', err);
        }
      })
    } else {
      wx.showToast({
        title: '该岗位暂无客服',
        icon: 'none',
        duration: 2000
      })
    }

    // }

  },
  showImage (e) {
    let resImg = e.currentTarget.dataset.src;
    console.log(this.data.jobDetail.images);
    var imgArr = [];
    this.data.jobDetail.images.forEach((item) => {
      // let regs = /\.(jpg|jpeg|png)(\?.*)?$/;
      //   item.isImg = regs.test(item.url.toLowerCase());
      if (item.isImg) {
        imgArr.push(item.url);
      }
    });
    if (e.currentTarget.dataset.type) {
      imgArr.unshift(resImg);

    }
    console.log(imgArr);
    wx.previewImage({
      current: resImg, // 当前显示图片的http链接
      urls: imgArr,
    });
  },
  showVideo (e) {
    console.log(e);
    console.log(wx.getSystemInfo());
    var that = this;
    this.videoContext = wx.createVideoContext(`${e.target.dataset.id}`, this);
    this.videoContext.requestFullScreen();
    this.videoContext.hideStatusBar();
    this.videoContext.play();
    setTimeout(() => {
      that.setData({
        isShareShow: true,
      });
    }, 500);
  },
  fullScreen (e) {
    console.log(e);
    if (!e.detail.fullScreen) {
      this.setData({
        isShareShow: false,
      });
      this.videoContext.stop();
    }
  },
  shareVideo (e) {
    console.log(e);
    wx.showLoading({
      title: "下载中...",
      mask: true,
    });
    wx.downloadFile({
      url: e.currentTarget.dataset.src, // 下载url
      success (res) {
        // 下载完成后转发
        wx.hideLoading();
        wx.showLoading({
          title: "分享中...",
          mask: true,
        });
        wx.shareVideoMessage({
          videoPath: res.tempFilePath,
          success () {
            wx.hideLoading();
          },
          fail: () => {
            wx.hideLoading();
            wx.showToast({
              title: "分享失败",
            });
          },
        });
      },
      fail: (res) => {
        console.log(res);
        wx.hideLoading();
        wx.showToast({
          title: "下载失败",
        });
      },
    });
  },
  renderToCanvas () {
    const p1 = this.widget.renderToCanvas({
      wxml: wxml(that.data.wxml),
      style
    });
    p1.then((res) => {
      console.log("container", res.layoutBox);
      this.container = res;
      console.log(res);
    });
  },
  extraImage () {
    var that = this;
    // return new Promise(function (resolve, reject) {
    that.widget.renderToCanvas({
      wxml: wxml(that.data.wxml),
      style
    }).then((res1) => {
      const p2 = that.widget.canvasToTempFilePath();
      p2.then((res) => {
        console.log(res);
        that.setData({
          src: res.tempFilePath,
        });
      });
    });
    // });
  },
  onLoad (query) {
    var that = this;
    console.log('app.globalData.loginUserInfo', app.globalData.loginUserInfo);
    qqmapsdk = new QQMapWX({
      key: "5PTBZ-YI7C6-MZGS3-ES7QN-4T5O2-EJFVR",
    });
    // app.globalData.loginUserInfo.agencyStatus = 1

    if (app.globalData.templateList) {
      app.globalData.templateList.forEach((element) => {
        console.log(element);
        if (element.title == "伯才小程序首页海报分享封面") {
          this.setData({
            shareDetailImg: element.img,
          });
          console.log(this.data.shareDetailImg);
        }
      });
    }
    that.setData({
      isAgency: app.globalData.loginUserInfo.agencyStatus == 1 ? true : false,
      corpUserFlag: app.globalData.loginUserInfo.corpUserFlag,
      managerRoleClassify: app.globalData.loginUserInfo.managerRoleClassify,
      userInfo: app.globalData.loginUserInfo,
    });

    that.widget = that.selectComponent(".widget");
    // wx.getSystemInfo({
    //   success: (res) => {
    //     console.log(res);
    //     console.log("手机信息res" + res.model);
    //     let modelmes = res.model;
    //     console.log(modelmes.search("iPhone X"));
    //     if (modelmes.search("iPhone 12 Pro") != -1 || modelmes.search("iPhone X") != -1 || modelmes.search("iPhone XR") != -1 || modelmes.search("iPhone XS max") != -1 || modelmes.search("iPhone 11") != -1) {
    //       that.setData({
    //         pbtm: 40,
    //       });
    //     } else { }
    //   },
    // });
    console.log(query);
    console.log("HHHHHHHHHHHHH" + query.storeJobId);

    if (query.storeJobId) {
      this.data.searchForm.storeJobId = query.storeJobId;
    }
    if (query.agencyId) {
      this.data.searchForm.agencyId = query.agencyId;
    }
    // this.data.wxCode = query.wxCode;
    // this.getLocation();
    // that.setData({
    //     wxCode: that.data.wxCode
    // })
    wx.setStorageSync("storeJobId", query.storeJobId);

    let agencyUserId = query.agencyUserId;
    if (agencyUserId) {
      wx.setStorageSync("storageSyncAgencyUserId", agencyUserId);
      console.log("agencyUserId", agencyUserId);
      app.globalData.isCommission = 1;
    }
    if (query.isSharePage) {
      this.setData({
        isSharePage: true
      })
    }
    console.log(query);
    setTimeout(() => {
      if (app.isNotEmptyCheck(query.scene)) {
        var sceneStr = decodeURIComponent(query.scene);
        var sceneJson = commonUtil.sceneToJson(sceneStr);
        console.log(app.globalData.isLogin);
        console.log("sceneJson===", sceneJson);
        this.data.searchForm.storeJobId = sceneJson.storeJobId;
        this.data.searchForm.agencyId = sceneJson.agencyId || '';
        // this.data.searchForm.jobClassify = sceneJson.jobClassify || 1;
        if (!app.globalData.isLogin) {
          wx.setStorageSync("comeFromPage", "detail");
          // wx.setStorageSync("comeFromPageParam", { storeJobId: that.data.searchForm.storeJobId });
          wx.navigateTo({
            url: "/pages/login/index",
          });
          return
        }
        //扫小程序码携带参数
        // console.log("storeJobId===", this.data.searchForm.storeJobId);
        that.setData({
          fromScene: true,
          isSharePage: true
        })

      }
      this.getStoreJobDetailById();
    }, 100);
  },
  goIndex () {
    wx.switchTab({
      url: '../firstBill/index',
    })
  },
  getCode () {
    var that = this;
    console.log('getCode');
    console.log(this.data.searchForm.storeJobId);
    customRequest('/yishoudan/store/job/qrcode/' + that.data.searchForm.storeJobId, {
      header: 'headers',
      method: 'GET',
      data: {}
    }).then((res) => {
      that.setData({
        currCode: res.data.data.qrcode
      })
    })
    // wx.request({
    //   url: app.globalData.ip + '/yishoudan/store/job/qrcode/' + that.data.searchForm.storeJobId,
    //   header: app.globalData.headers,
    //   method: "GET",
    //   success: function (res) {
    //     console.log(res)
    //     that.setData({
    //       currCode: res.data.data.qrcode
    //     })
    //   }
    // })
  },
  getAgencyInfo (job) {
    var that = this;
    console.log(job);
    console.log("打印基本信息");

    let objAgency = {
      returnFeeDesp: job.returnFeeDesp,
      returnFeeType: job.returnFeeType,
      transferFee: job.transferFee,
      returnFee: job.returnFee != null ? new Number(job.returnFee).toFixed(2) : null,
    };
    let agencyStr = "";
    if (app.isNotEmptyCheck(job.transferFee)) {
      agencyStr = "伯才利润：" + job.transferFee + ";";
    }
    if (job.returnFeeType == 0) {
      agencyStr += `\n服务费：xxx元/时`;
    } else if (job.returnFeeType == 1) {
      agencyStr += `\n服务费：xxx元/天`;
    } else if (job.returnFeeType == 2) {
      agencyStr += `\n服务费：xxx元/月`;
    } else if (job.returnFeeType == 3) {
      agencyStr += `\n服务费：xxx元/次`;
    }
    if (objAgency.returnFee > 0) {
      agencyStr = agencyStr.replace("xxx", objAgency.returnFee);
    } else if (app.isNotEmptyCheck(job.transferFee)) {
      agencyStr = "伯才利润：" + job.transferFee + ";";
    } else {
      agencyStr = "-";
    }
    if (app.isEmptyCheck(objAgency.returnFeeDesp)) {
      // return agencyStr
      that.setData({
        bclr: agencyStr,
      });
    } else {
      that.setData({
        bclr: agencyStr + "\n" + objAgency.returnFeeDesp,
      });
      // return agencyStr + '\n' + objAgency.returnFeeDesp;
    }
  },
  chooseMap (e) {
    var that = this;
    let address = e.currentTarget.dataset.address.record
    let name,
      content,
      lat,
      lng
    if (e.currentTarget.dataset.type == 'interview') {
      name = address.interviewAddr;
      content = address.interviewAddr;
      lat = address.interviewLat - 0;
      lng = address.interviewLng - 0;
    } else {
      name = address.storeAddr;
      content = address.storeAddr;
      lat = address.storeLat - 0;
      lng = address.storeLng - 0;
    }
    console.log('address', address);
    setTimeout(() => {

      wx.openLocation({
        latitude: lat,
        longitude: lng,
        name: name,
        address: content,
        scale: 15,
      });
    }, 200);
  },
  toMapChoice (e) {
    var that = this;
    console.log(e);
    if (e.currentTarget.dataset.address.record.storeLat) {
      try {
        wx.setStorageSync("onSiteRemark", that.data.onSiteRemark);
        wx.setStorageSync("addressList", e.currentTarget.dataset.address);
      } catch (error) {
        console.log(error);
      }
      wx.navigateTo({
        url: "../addressPage/index?jobClassify=" + that.data.searchForm.jobClassify,
      });
    }

  },
  // openMap(e) {
  // 	wx.showLoading({
  // 		title: "加载中",
  // 	});
  // 	console.log(e);
  // 	let address = e.currentTarget.dataset.address;
  // 	let lat = e.currentTarget.dataset.lat;
  // 	var formatted_addresses = "";
  // 	qqmapsdk.reverseGeocoder({
  // 		location: `${e.currentTarget.dataset.lat},${e.currentTarget.dataset.lng}`,
  // 		success: function (res) {
  // 			console.log(res);
  // 			formatted_addresses = res.result.formatted_addresses.recommend;
  // 		},
  // 	});
  // 	console.log(formatted_addresses);
  // 	console.log(lat);
  // 	wx.getLocation({
  // 		type: "gcj02", //返回可以用于wx.openLocation的经纬度
  // 		success(res) {
  // 			wx.openLocation({
  // 				latitude: e.currentTarget.dataset.lat - 0,
  // 				longitude: e.currentTarget.dataset.lng - 0,
  // 				name: formatted_addresses,
  // 				address: address,
  // 				scale: 8,
  // 			});
  // 		},
  // 		complete(res) {
  // 			wx.hideLoading();
  // 			console.log(1123213);
  // 		},
  // 	});
  // },
  changeMenu (e) {
    let currentIndex = parseInt(e.currentTarget.dataset.id);
    this.setData({
      currIndex: e.currentTarget.dataset.id,
    });
  },
  getLocation () {
    var that = this;

    wx.getSetting({
      success: (res) => {
        console.log(res); // res.authSetting.location

        if (res.authSetting.location) {
          wx.getLocation({
            success (res1) {
              console.log("获取位置");
              console.log(res1);

              if (app.isNotEmptyCheck(res1.latitude) && app.isNotEmptyCheck(res1.longitude)) {
                that.data.searchForm.lat = res1.latitude;
                that.data.searchForm.lng = res1.longitude;
              }

              that.getStoreJobDetailById();
            },

            fail () {
              that.getStoreJobDetailById();
            },
          });
        } else {
          that.getStoreJobDetailById();
        }
      },
    }); // my.getLocation({
    //     success(res) {
    //         my.hideLoading();
    //         console.log(res)
    //         that.data.searchForm.lng = res.longitude;
    //         that.data.searchForm.lat = res.latitude;
    //         that.getStoreJobDetailById();
    //     },
    //     fail() {
    //         my.hideLoading();
    //         that.getStoreJobDetailById();
    //     },
    // })
  },
  onShareAppMessage () {
    // return app.sharePageImage()
    var path = commonUtil.getCurrentPageUrlWithArgs();
    if (app.globalData.isLogin && app.globalData.agencyStatus - 0 != 0) {
      //当前用户是代理人
      path += "&agencyUserId=" + app.globalData.loginUserInfo.id;
    }
    var that = this;
    return this.getCanvas('sharePage').then((res) => {
      return {
        title: ' ',
        imageUrl: res.tempFilePath,
        path: path,
        // promise
      };
    });
  },

  // onShareTimeline: function () {
  // 	return {
  // 		title: this.data.shareTitle,
  // 		query: "?storeJobId=" + this.data.storeJobId,
  // 	};
  // },
  getCanvas (shareType) {
    const that = this;

    return new Promise((resolve) => {

      const query = wx.createSelectorQuery();
      query
        .select("#canvasId")
        .fields({
          node: true,
          size: true
        })
        .exec((res) => {
          console.log(res);
          const canvas = res[0].node;
          const ctx = canvas.getContext("2d");
          if (shareType == 'sharePoster') {
            that.setPosterImg(ctx, canvas).then((res) => {
              console.log(res);
              resolve()
            })
          } else if (shareType == 'sharePage') {
            that.setSharePage(ctx, canvas).then((canvas) => {
              console.log(res);
              wx.canvasToTempFilePath({
                canvas: canvas,
                success (res) {
                  console.log("res222", res);
                  resolve(res);
                },
                fail (res) {
                  wx.hideLoading();
                  wx.showToast({
                    title: res.errMsg,
                    icon: "error",
                  });
                },
              });
            })
          }

        });
    });
  },
  /**
  * 处理海报分享的函数
  */
  setPosterImg (ctx, canvas) {
    const that = this;
    var mycenter = 0; //文字左右居中显示
    var myheight = 0; //文字高度
    return new Promise(function (resolve) {
      return new Promise(function (resolve) {

        // 绘制背景图片
        wx.getImageInfo({
          src: that.data.shareDetailImg, //网络图片,如果不行请换一个
          success (res) {
            console.log(res);
            var width = res.width;
            var height = res.height;
            mycenter = width / 2;
            myheight = height;
            canvas.width = width;
            canvas.height = height;
            const img = canvas.createImage();
            console.log(ctx);
            img.src = res.path;
            img.onload = () => {
              ctx.drawImage(img, 0, 0, width, height);
              resolve(true);
            };
          },
        });
      }).then(() => {
        console.log(530);


        //使用：
        new Promise((imgres) => {
          // that.data.checkedList.forEach((item, index) => {
          console.log(587);
          let labelLeft = 0;
          // ctx.arcTo()
          let baseTop, logoLeft, logoSize, titleSize, ageTop, salaryClassifyValueLeft, salaryClassifyValueTop, monthlyPaySize, position, markTop, roundRectHeight, fubiaotiTop, bottomSloganTop, QRSize;
          logoLeft = 56 * 2;
          let baseMiddle = 248 * 2;
          // if (that.data.checkedList.length == 1) {
          baseTop = 2 * 370;
          logoSize = 2 * 96;
          QRSize = 2 * 260;
          titleSize = 2 * 30;
          roundRectHeight = 2 * 260;
          ageTop = 2 * 110;
          salaryClassifyValueLeft = 2 * 176;
          salaryClassifyValueTop = 2 * 54;
          monthlyPaySize = 2 * 24;
          markTop = 2 * 145;
          fubiaotiTop = 2 * 155;
          bottomSloganTop = 2 * 355;

          // roundRect1(ctx, x, y, w, h, r, color)

          commonUtil.roundRect1(ctx, mycenter - 1104 / 2, baseTop - 100, 1104, roundRectHeight, 32, "#fff");
          // roundRect1(ctx, mycenter - 600 / 2, baseTop + 750, 600, 560, 32, "#fff");
          console.log(' that.data.currCode', that.data.currCode);
          wx.getImageInfo({
            // src: "https://matripe-cms.oss-cn-beijing.aliyuncs.com/1shoudan/qrcode.png", //网络图片,如果不行请换一个
            //  src:"https://daotian.matripe.com.cn/image/jobs/4/storeJobId9227.jpg",
            src: app.globalData.ip + that.data.currCode,
            success (res) {
              console.log(res);
              const img = canvas.createImage();
              img.src = res.path;
              img.onload = () => {

                // (ctx, img, bg_x, bg_y, bg_w, bg_h, bg_r)
                // roundRect(ctx, img, mycenter - res.width / 2 - 40, baseTop + 770, QRSize, QRSize, 32);
                commonUtil.roundRect1(ctx, mycenter - 580 / 2, baseTop + 740, 580, 580, 0, "#fff");
                commonUtil.roundRect(ctx, img, mycenter - res.width / 2 - 40, baseTop + 770, QRSize, QRSize, 0);
                // if (index == that.data.checkedList.length - 1) {
                // setTimeout(() => {
                //   imgres();
                // }, 1000);
                // }
                /**
                * 临时
                *
                *
                */
                imgres();

                // wx.getImageInfo({
                //   src: that.data.jobDetail.store.logo, //网络图片,如果不行请换一个
                //   success (res) {
                //     console.log(res);
                //     const img = canvas.createImage();
                //     img.src = res.path;
                //     img.onload = () => {
                //       roundRect(ctx, img, logoLeft, baseTop + 40, logoSize, logoSize, 8);
                //       // if (index == that.data.checkedList.length - 1) {
                //       setTimeout(() => {
                //         imgres();
                //       }, 200);
                //       // }
                //     };
                //   },
                //   fail (err) {
                //     console.log(err);
                //   },
                // });
              };
            },
            fail (err) {
              console.log(err);
            },
          });
          // that.data.jobDetail.record.jobSpecialLabelNames.forEach((item1, index) => {
          //   console.log(item1);
          //   // console.log(ctx.measureText(item1).width);
          //   if (index <= 2) {
          //     fillTextLineBreak(ctx, item1, 60 * 2 + labelLeft, baseTop + markTop + 30 * 2, 400 * 2, 20, "#333", monthlyPaySize); // 标签字符
          //     roundRect1(ctx, 52 * 2 + labelLeft, baseTop + markTop, ctx.measureText(item1).width + 16 * 2, 40 * 2, 2 * 2, "#00000010");
          //     labelLeft += ctx.measureText(item1).width + 32 * 2;
          //   }
          // });

          commonUtil.fillTextLineBreak(ctx, that.data.jobDetail.record.jobName, logoLeft, baseTop, 500 * 2, 20, "#333", titleSize, "600"); // 岗位标题

          commonUtil.fillTextLineBreak(ctx, that.data.jobDetail.record.salaryClassifyValueHaibao, salaryClassifyValueLeft, baseTop + salaryClassifyValueTop, 400 * 2, 20, "#1890ff", titleSize, "600"); // 时薪

          commonUtil.fillTextLineBreak(ctx, that.data.jobDetail.record.monthlyPay, salaryClassifyValueLeft + ctx.measureText(that.data.jobDetail.record.salaryClassifyValueHaibao + " ").width, baseTop + salaryClassifyValueTop, 400 * 2, 20, "#1890ff", monthlyPaySize, "400"); // 月工资
          // .slice(0, 7) + '...'

          commonUtil.fillTextLineBreak(ctx, that.data.citys.length > 9 ? that.data.citys.substring(0, 8) + '...' : that.data.citys, salaryClassifyValueLeft, baseTop + ageTop, 300 * 2, 20, "#333", monthlyPaySize); // 省市

          commonUtil.fillTextLineBreak(ctx, "丨" + that.data.jobDetail.record.age, salaryClassifyValueLeft + ctx.measureText(that.data.citys.length > 7 ? that.data.citys.substring(0, 8) + '...' : that.data.citys,).width, baseTop + ageTop, 300 * 2, 20, "#333", monthlyPaySize); // 年龄

          commonUtil.fillTextLineBreak(ctx, that.data.userInfo.agencyName, mycenter - ctx.measureText(that.data.userInfo.agencyName).width / 2, baseTop - fubiaotiTop, 400 * 2, 20, "#fff", monthlyPaySize, "600"); // 代理名称

          commonUtil.fillTextLineBreak(ctx, "长按查看职位详情", mycenter - ctx.measureText("长按查看职位详情").width / 2, baseTop + bottomSloganTop - 20, 300 * 2, 20, "#fff", monthlyPaySize); // 底部slogan

          commonUtil.fillTextLineBreak(ctx, "好工作  放心干", mycenter - ctx.measureText("好工作  放心干").width / 1.6, baseTop + bottomSloganTop + 700, 500 * 2, 20, "#fff", titleSize); // 底部slogan
          // let src
          // src =  that.data.jobDetail.store.logo.indexOf("https") > -1 ? that.data.jobDetail.store.logo : that.data.jobDetail.store.logo.replace("http", "https")

          // });
          // setTimeout(() => {
          // },500);
        })
          .then(function () {
            wx.canvasToTempFilePath({
              canvas: canvas,
              success (res) {
                console.log(res);
                that.setData({
                  canvasImg: res.tempFilePath,
                });
                resolve(res);
              },
              fail (res) {
                wx.hideLoading();

                wx.showToast({
                  title: res.errMsg,
                  icon: "error",
                });
              },
            });
          })
          .catch((err) => {
            console.log(err);
          });
      });
    });
  },
  /**
  * 处理页面分享的函数
  */
  setSharePage (ctx, canvas) {
    let that = this;

    canvas.width = 750;
    canvas.height = 600;
    let mycenter = canvas.width / 2;
    let labelLeft = 0;
    let baseLeft, logoSize, titleFontSize, mainFontSize, line1, line2, line3, line4, line5, line6, line7, line8;
    baseLeft = 24; // 左侧基准线
    logoSize = 132; // logo尺寸
    mainFontSize = 36; // 内容字体大小
    titleFontSize = 56; // 标题字体大小
    line1 = 68; // 第一行距顶部距离
    line2 = 90;
    line3 = 200;
    line4 = 280;
    line5 = 350;
    line6 = 380;
    line7 = 460;

    // 绘制基础白色背景
    commonUtil.roundRect1(ctx, 0, 0, 750, 600, 0, "#fff");
    return new Promise(function (imgres) {
      // commonUtil.fillTextLineBreak(ctx, that.userInfo.agencyName, baseLeft + 48 + 10, line1 + 35, 400, 48, "#999", mainFontSize - 6, "600"); // 代理名称

      commonUtil.fillTextLineBreak(ctx, that.data.jobDetail.record.jobName, baseLeft, line2, 800, 20, "#000", titleFontSize, "500", "left"); // 岗位标题
      console.log("isLogin", that.data.isLogin);
      // if (that.data.isLogin) {
      console.log("innerLogin", that.data.isLogin);
      // commonUtil.fillTextLineBreak(ctx, "工价", baseLeft + logoSize + 10, line2 + 50, 100, 30, "#ff4400", titleFontSize - 8, "500", "left"); // 工价
      commonUtil.fillTextLineBreak(ctx, that.data.jobDetail.record.salaryClassifyValueHaibao, baseLeft + 10, line3, 400, 40, "#ff4400", titleFontSize + 6, "600", "left"); // 时薪
      commonUtil.fillTextLineBreak(ctx, that.data.jobDetail.record.monthlyPay, 750 - ctx.measureText(that.data.jobDetail.record.monthlyPay).width, line3, 400, 20, "#ff4400", titleFontSize, "400"); // 月工资

      // } else {
      //   console.log("notLogin", that.data.isLogin);
      //   commonUtil.fillTextLineBreak(ctx, "工价登录后查看", baseLeft + logoSize + 10, line3 - 40, 400, 20, "#ff4400", titleFontSize - 6, "400"); // 时薪
      // }
      console.log('that.data.jobDetail.record.jobRequestLabelNames', that.data.jobDetail.record.jobRequestLabelNames);
      if (that.data.jobDetail.record.jobRequestLabelNames && that.data.jobDetail.record.jobRequestLabelNames.length > 0) {
        that.data.jobDetail.record.jobRequestLabelNames.forEach((item1, index) => {
          if (index <= 3) {
            commonUtil.fillTextLineBreak(ctx, item1, baseLeft + labelLeft + 12, line4 + 4, 400, 40, "#666", mainFontSize); // 标签字符
            commonUtil.roundRect1(ctx, baseLeft + labelLeft, line4 - 38, ctx.measureText(item1).width + 24, 56, 8, "#00000012");
            labelLeft += ctx.measureText(item1).width + 32;
            if (index == 3) {
              labelLeft = 0;
            }
          } else if (index > 3 && index <= 6) {
            commonUtil.roundRect1(ctx, baseLeft + labelLeft, line5 - 38, ctx.measureText(item1).width + 24, 56, 8, "#00000012");
            commonUtil.fillTextLineBreak(ctx, item1, baseLeft + labelLeft + 12, line5 + 4, 400, 40, "#666", mainFontSize); // 标签字符
            labelLeft += ctx.measureText(item1).width + 32;
          }
        });
      } else {
        commonUtil.fillTextLineBreak(ctx, '暂无特色', baseLeft + 12, line4 + 4, 400, 40, "#666", mainFontSize); // 标签字符
        commonUtil.roundRect1(ctx, baseLeft, line4 - 38, ctx.measureText('暂无特色').width + 24, 56, 8, "#00000012");
      }

      // 根据标签数量调整宣传标语位置
      // commonUtil.roundRect1(ctx, mycenter - 712 / 2, line6 + (that.data.jobDetail.record.jobSpecialLabelNames.length > 3 ? 0 : -70), 712, 60, 4, "#fff6e8"); // 宣传标语背景
      commonUtil.roundRect1(ctx, mycenter - 712 / 2, line6, 712, 60, 4, "#fff6e8"); // 宣传标语背景

      // 绘制立即咨询
      // 根据标签数量调整立即咨询背景位置
      // commonUtil.roundRect1(ctx, mycenter - 712 / 2, line7 + (that.data.jobDetail.record.jobSpecialLabelNames.length > 3 ? 0 : -70), 712, 100, 4, "#3b80fa"); // 立即咨询背景
      commonUtil.roundRect1(ctx, mycenter - 712 / 2, line7, 712, 100, 4, "#3b80fa"); // 立即咨询背景
      // 根据标签数量调整立即咨询位置
      // commonUtil.fillTextLineBreak(ctx, "立即咨询", mycenter - 24 - ctx.measureText("立即咨询").width / 2, line7 + (that.data.jobDetail.record.jobSpecialLabelNames.length > 3 ? 70 : 0), 300, 120, "#fff", titleFontSize, "500"); // 立即咨询
      commonUtil.fillTextLineBreak(ctx, "立即咨询", mycenter - 24 - ctx.measureText("立即咨询").width / 2, line7 + 65, 300, 120, "#fff", titleFontSize, "500"); // 立即咨询
      // 绘制职位logo
      // console.log("that.data.jobDetail.record.logo", that.data.jobDetail.record.logo);
      // wx.downloadFile({
      //   url: that.data.jobDetail.record.logo,
      //   success (res) {
      //     console.log("draw", res);
      //     const img = canvas.createImage();
      //     img.src = res.tempFilePath;
      //     img.onload = () => {
      //       commonUtil.roundRect(ctx, img, baseLeft, line2, logoSize, logoSize, 8);

      //     };
      //   },
      //   fail (err) {
      //     console.log("logodownloadFile err", err);
      //   },
      // });
      wx.downloadFile({
        url: "https://matripe-cms.oss-cn-beijing.aliyuncs.com/pugongying/goxj2-qpwbo.png",
        success (res) {
          console.log("duihao", res);
          const img1 = canvas.createImage();
          img1.src = res.tempFilePath;
          console.log("img info img", img1);
          img1.onload = (info) => {
            console.log("img info", info);
            let safeMarkPosition = 44;
            // 宣传标语
            ["安全保障", "工资保障", "补贴保障"].forEach((item1, index) => {
              // 根据标签数量调整安全标识位置
              // commonUtil.fillTextLineBreak(ctx, item1, baseLeft + safeMarkPosition, line6 + (that.data.jobDetail.record.jobSpecialLabelNames.length > 3 ? 0 : -70) + 40, 100, 32, "#fca025");
              // commonUtil.roundRect(ctx, img, baseLeft + safeMarkPosition - 36, line6 + (that.data.jobDetail.record.jobSpecialLabelNames.length > 3 ? 0 : -70) + 12, 32, 32, 12);
              commonUtil.fillTextLineBreak(ctx, item1, baseLeft + safeMarkPosition, line6 + 40, 100, 32, "#fca025");
              commonUtil.roundRect(ctx, img1, baseLeft + safeMarkPosition - 36, line6 + 12, 32, 32, 12);
              safeMarkPosition += 130 + ctx.measureText(item1).width;
            });
            setTimeout(() => {
              console.log("success draw");
              imgres(canvas);
            }, 200);
          };
        },
        fail (err) {
          console.log("downloadFile err", err);
        },
      });
    }).catch((err) => {
      console.log("all err", err);
    });
  },
  /**
   * 分享海报生成海报图并转发
   *
   *
   */
  sharePoster () {
    wx.showLoading({
      title: "生成中...",
    });
    this.getCanvas('sharePoster').then((res) => {
      console.log(res);
      wx.hideLoading();
      this.setData({
        posterImg: res.tempFilePath,
        posterShow: true,
      });
    });
    // this.setData({
    // });
  },
  /**
   * 报名人抽屉隐藏
   *
   *
   */
  hidedrawershow (e) {
    console.log(e);
    this.setData({
      [e.detail.type]: false
    })
  },
  hidePoster () {
    this.setData({
      posterShow: false,
    });
  },
  saveToalbum () {
    let that = this;
    wx.saveImageToPhotosAlbum({
      filePath: that.data.posterImg,
      success (res) {
        console.log(res);
        if (res.errMsg == "saveImageToPhotosAlbum:ok") {
          wx.showToast({
            title: "图片已保存",
            icon: "none",
            duration: 1500,
          });
        }
      },
      fail (res) {
        console.log(res);
        wx.showToast({
          title: "图片保存失败",
          icon: "none",
          duration: 1500,
        });
      },
    });
  },
  getStoreJobDetailById () {
    var that = this;
    wx.showLoading({
      title: "加载中...",
    });
    console.log('that.data.searchForm', that.data.searchForm);
    // /yishoudan/store/job/platform/detail/{id}?jobClassify={jobClassify}
    // "/overall/store/job/getStoreJobDetailById?storeJobId="
    // /yishoudan/custom/job/detailV2/{id}  get  新版职位详情
    let url = `/yishoudan/custom/job/detailV2/${that.data.searchForm.storeJobId}`
    // if(that.data.searchForm.jobClassify == 1){
    //   url = `/overall/store/job/getStoreJobDetailById?storeJobId=${that.data.searchForm.storeJobId}`
    // }
    customRequest(url, {
      header: 'headers',
      method: 'get',
      data: that.data.searchForm
    }).then((res) => {
      console.log('新版详情返回：', res);
      if (res.data.status == 200) {
        var result = res.data.data;
        var title = result.record.jobName;
        that.setData({
          shareTitle: title,
          onSiteRemark: result.record.onSiteRemark,
        });

        let regs = /\.(jpg|jpeg|png)(\?.*)?$/;
        // result.images.forEach((item) => {
        //   item.isImg = regs.test(item.url.toLowerCase());
        //   item.url = item.url.replaceAll('http:','https:')
        // });
        result.record.genderRestrict = commonUtil.getGenderByMinAge(result.record);
        // 更新时间

        result.record.update = dateUtil.timeShowXXX2(result.record.updateTime);

        if (app.isNotEmptyCheck(title)) {
          title = result.record.jobName;
        } else {
          title = result.store.aliasName;
        }

        wx.setNavigationBarTitle({
          title,
        });

        result.record.workType = commonUtil.getWorkTypeById(result.record.workTypeMulti);

        if (app.isNotEmptyCheck(result.record.calculationSalaryType)) {
          result.record.calculationSalaryType = result.record.calculationSalaryType.split("#")[0];
        }

        // if (app.isNotEmptyCheck(result.record.jobDesp)) {
        // result.record.jobDesp = result.record.jobDesp.replaceAll("*****", "").split("————————")[0];
        // }

        if (app.isNotEmptyCheck(result.record.paymentSalaryType)) {
          result.record.paymentSalaryType = result.record.paymentSalaryType.split("，");
        }

        if (app.isNotEmptyCheck(result.record.salaryDesp)) {
          result.record.salaryDesp = result.record.salaryDesp.split("；");
        }

        if (app.isNotEmptyCheck(result.record.workDurationDesp)) {
          result.record.workDurationDesp = result.record.workDurationDesp.split("；");
        }

        if (app.isNotEmptyCheck(result.record.probationDesp)) {
          result.record.probationDesp = result.record.probationDesp.split("；");
        }

        if (app.isNotEmptyCheck(result.record.workingLunchDesp)) {
          result.record.workingLunchDesp = result.record.workingLunchDesp.split("；");
        }

        if (app.isNotEmptyCheck(result.record.dormitoryDesp)) {
          result.record.dormitoryDesp = result.record.dormitoryDesp.split("；");
        }
        // result.store.distance = commonUtil.getDistanceName(result.store.distance);
        // if (app.isNotEmptyCheck(result.store.distance)) {
        //   result.store.distance = "丨" + result.store.distance;
        // }

        that.disposeJobListData(result);
        // if (app.isNotEmptyCheck(result.store.logo)) {
        //   result["logo2"] = result.store.logo.replace("http:", "https:");
        //   result.store["logo"] = result.store.logo.indexOf("https") > -1 ? result.store.logo : result.store.logo.replace("http", "https");
        // } else {
        //   result["logo2"] = "";
        // }
        if (app.isNotEmptyCheck(result.record.returnFeeType) || result.record.returnFeeType == "0" || result.record.returnFee == "0") {
          that.setData({
            fuWuFei: commonUtil.getReturnFeeTypeName1ById(result.record.returnFeeType, result.record.returnFee ? result.record.returnFee / 100 : ''),
          });
        }
        console.log(result);
        console.log(commonUtil);
        let citys = commonUtil.setJobInfoPositionv3(result.record.storeAddr);
        // city = city.replace(/,/g, " | ")
        that.data.jobDetail = result
        that.showSexAge();

        // result.record["jobDesp1"] = `\n${result.record.jobName}\n\n一、薪资明细\n${result.record.salaryDetail}\n\n二、招聘要求\n${(that.data.showSexAgeText + '\n' + result.record.workContent) || '-'}\n\n三、其他说明\n${result.record.otherDesp}\n\n四、注意事项\n${result.record.notes}`
        that.setData({
          jobDetail: result,
          isMaskShow: !(result.record.recruitment == "1"),
          citys: citys,
          // addressNew: result.storeDistrict.replace(/,/g, "") + result.store.detailPosition,
        });
        that.data.jobDetail.record["storeName"] = that.data.jobDetail.storeName ? that.data.jobDetail.storeName : that.data.jobDetail.record["storeName"];



        // that.getAgencyInfo(result.record);

        if (app.isEmptyCheck(result.record.handoverInfo)) {
          that.setData({
            djxx: "暂无对接信息",
          });
        } else {
          that.setData({
            djxx: result.record.handoverInfo,
          });
        }
        console.log(that.data.jobDetail);
      }
      wx.hideLoading();
    })
  },

  showSexAge () {
    var that = this;
    var manStr = "";
    var womanStr = "";

    if (app.isNotEmptyCheck(that.data.jobDetail.record.minAgeMan) || app.isNotEmptyCheck(that.data.jobDetail.record.maxAgeMan)) {
      manStr = "男 ";
    }

    if (app.isNotEmptyCheck(that.data.jobDetail.record.minAgeMan)) {
      manStr = manStr + that.data.jobDetail.record.minAgeMan;
    }
    if (app.isNotEmptyCheck(that.data.jobDetail.record.maxAgeMan)) {
      manStr = manStr + "-" + that.data.jobDetail.record.maxAgeMan;
    }

    if (app.isNotEmptyCheck(that.data.jobDetail.record.minAgeWoman) || app.isNotEmptyCheck(that.data.jobDetail.record.maxAgeWoman)) {
      womanStr = "女 ";
    }
    if (app.isNotEmptyCheck(that.data.jobDetail.record.minAgeWoman)) {
      womanStr = womanStr + that.data.jobDetail.record.minAgeWoman;
    }
    if (app.isNotEmptyCheck(that.data.jobDetail.record.maxAgeWoman)) {
      womanStr = womanStr + "-" + that.data.jobDetail.record.maxAgeWoman;
    }

    if (womanStr != "") {
      manStr = manStr + `${manStr == "" ? "" : "；"}` + womanStr;
    }

    that.setData({
      showSexAgeText: manStr + (that.data.jobDetail.record.genderRemark ? "，" + that.data.jobDetail.record.genderRemark : ""),
    });
  },
  /**
   * 处理后台返回的职位列表
   */
  disposeJobListData (jobDetail) {
    var that = this;

    // item["workType"] = commonUtil.getWorkTypeById(
    //     item.workTypeMulti
    // );

    // if (app.isNotEmptyCheck(item.distance)) {
    //     item["distanceKm"] = commonUtil.getDistanceName(
    //         item.distance
    //     );
    // }
    //年龄
    var ageStr = "";
    if (app.isNotEmptyCheck(jobDetail.record.minAge) && app.isNotEmptyCheck(jobDetail.record.maxAge)) {
      ageStr = jobDetail.record.minAge + "-" + jobDetail.record.maxAge + "岁";
    } else if (app.isNotEmptyCheck(jobDetail.record.minAge)) {
      ageStr = jobDetail.record.minAge + "岁以上";
    } else if (app.isNotEmptyCheck(jobDetail.record.maxAge)) {
      ageStr = jobDetail.record.maxAge + "岁以下";
    }
    jobDetail.record["age"] = ageStr;
    //时薪
    // var hourlyPayStr = "";
    var hasHourlyPay = true;
    console.log(jobDetail.record);
    // if (app.isNotEmptyCheck(jobDetail.record.hourlyPay)) {
    // 	hourlyPayStr = jobDetail.record.hourlyPay + "元/小时";
    // 	hasHourlyPay = true;
    // } else if (app.isNotEmptyCheck(jobDetail.record.dayPay)) {
    // 	hourlyPayStr = jobDetail.record.dayPay + "元/日";
    // 	hasHourlyPay = true;
    // } else {
    // 	if (app.isNotEmptyCheck(jobDetail.record.minMonthlyPay) && app.isNotEmptyCheck(jobDetail.record.maxMonthlyPay)) {
    // 		if (jobDetail.record.minMonthlyPay == jobDetail.record.maxMonthlyPay) {
    // 			hourlyPayStr = jobDetail.record.minMonthlyPay;
    // 		} else {
    // 			hourlyPayStr = jobDetail.record.minMonthlyPay + "-" + jobDetail.record.maxMonthlyPay;
    // 		}
    // 	} else if (app.isNotEmptyCheck(jobDetail.record.minMonthlyPay)) {
    // 		hourlyPayStr = jobDetail.record.minMonthlyPay;
    // 	} else if (app.isNotEmptyCheck(jobDetail.record.maxMonthlyPay)) {
    // 		hourlyPayStr = jobDetail.record.maxMonthlyPay;
    // 	}
    // }
    // if (app.isNotEmptyCheck(jobDetail.record.dayPay)){

    // }
    // if (app.isNotEmptyCheck(jobDetail.record.salaryClassify) && app.isNotEmptyCheck(jobDetail.record.salaryClassifyValue)) {

    jobDetail.record["hourlyPay"] = commonUtil.getSalaryClassifyValue(jobDetail.record.salaryClassify, jobDetail.record.salaryClassifyValue);
    jobDetail.record["salaryClassifyValueHaibao"] = commonUtil.getSalaryClassifyValue1(jobDetail.record.salaryClassify, jobDetail.record.salaryClassifyValue);
    // }
    //月薪
    var monthlyPayStr = "";
    if (hasHourlyPay) {
      if (app.isNotEmptyCheck(jobDetail.record.minMonthlyPay) && app.isNotEmptyCheck(jobDetail.record.maxMonthlyPay)) {
        if (jobDetail.record.minMonthlyPay == jobDetail.record.maxMonthlyPay) {
          monthlyPayStr = jobDetail.record.minMonthlyPay / 100;
        } else {
          monthlyPayStr = jobDetail.record.minMonthlyPay / 100 + "-" + jobDetail.record.maxMonthlyPay / 100;
        }
      } else if (app.isNotEmptyCheck(jobDetail.record.minMonthlyPay)) {
        monthlyPayStr = jobDetail.record.minMonthlyPay / 100;
      } else if (app.isNotEmptyCheck(jobDetail.record.maxMonthlyPay)) {
        monthlyPayStr = jobDetail.record.maxMonthlyPay / 100;
      }
    }
    jobDetail.record["monthlyPay"] = monthlyPayStr;
    //地址深圳丨龙岗区丨
    var districtStr = "";
    console.log(jobDetail.storeDistrict);
    if (app.isNotEmptyCheck(jobDetail.storeDistrict)) {
      var districtArr = jobDetail.storeDistrict.split(",");
      if (districtArr.length < 3) {
        districtStr = districtArr[districtArr.length - 1];
      } else {
        districtStr = districtArr[0] + "丨" + districtArr[1];
      }
      //districtStr = districtArr[1] + '丨' + districtArr[2];
    }
    // console.log(districtStr);
    // jobDetail.store["districtStr"] = districtStr;
    jobDetail.record["districtDetail"] = commonUtil.getStoreAddress(jobDetail.storeDistrict, jobDetail.record.detailPosition);

    //职位特色
    if (app.isNotEmptyCheck(jobDetail.record.jobRequestLabelNames)) {
      jobDetail.record["jobRequestLabelNames"] = that.getJobSpecialLabelNamesArray(jobDetail.record.jobRequestLabelNames);
    }
    // if (app.isNotEmptyCheck(jobDetail.record.jobRequestLabelNames)) {
    //   jobDetail.record['jobRequestLabelNames'] = that.getJobRequestLabelNamesArray(jobDetail.record.jobRequestLabelNames);
    // }
  },
  getJobSpecialLabelNamesArray (jobSpecialLabelNames) {
    console.log('getJobSpecialLabelNamesArray', jobSpecialLabelNames);
    if (app.isNotEmptyCheck(jobSpecialLabelNames)) {
      console.log('jobSpecialLabelNames.split(", ")', jobSpecialLabelNames.split(", "));
      return jobSpecialLabelNames.split(", ");
    }
    return [];
  },
  getJobRequestLabelNamesArray (jobRequestLabelNames) {
    console.log(jobRequestLabelNames);
    if (app.isNotEmptyCheck(jobRequestLabelNames)) {
      return jobRequestLabelNames.split(", ");
    }
    return [];
  },
  goSimilar () {
    var that = this;

    console.log(that.data.jobDetail);
    console.log(that.data.jobDetail.record.jobLabelId);

    wx.navigateTo({
      url: "../similar/index?brandId=" + that.data.jobDetail.store.brandId + "&jobLabelId=" + that.data.jobDetail.record.jobLabelId + "&classify=99",
    });
  },
  hideKefu () {
    this.setData({
      kefuShow: false
    })
  },
  makePhoneCall (e) {
    console.log('e', e);
    console.log(1);
    // return
    var that = this;
    wx.makePhoneCall({
      // number: that.data.jobDetail.assistantUserTel + ""
      phoneNumber: e.currentTarget.dataset.tel || "0371-6611 3723",
    });
    // var that = this;

    // let res = wx.getStorageSync({
    //     key: "assistantUserTel"
    // });

    // console.log(res);
    // console.log("缓存获取电话号：" + res.data);

    // if (app.isNotEmptyCheck(res.data)) {
    //     wx.makePhoneCall({
    //         number: res.data
    //     });
    // } else {
    //     wx.request({
    //         url: app.globalData.ip + "/store/job/getOneAssistantUser",
    //         method: "POST",
    //         header: app.globalData.headers,
    //         data: {},
    //         success: function (res) {
    //             console.log(res.data.data.tel);

    //             wx.setStorageSync({
    //                 key: "assistantUserTel",
    //                 data: res.data.data.tel
    //             });

    //             wx.makePhoneCall({
    //                 number: res.data.data.tel + ""
    //             });
    //         }
    //     });
    // }
  },
  textPaste () {
    var that = this;
    wx.setClipboardData({
      // data: that.data.jobDetail.assistantUserWechat,
      data: "16619732648",
      success: function (res) {
        wx.getClipboardData({
          success: function (res) {
            wx.showToast({
              icon: "none",
              title: "已复制微信号,快去添加好友吧",
              duration: 0,
            });
            wx.showModal({
              title: "已复制微信号",
              content: "快去搜索添加经纪人好友吧",
              showCancel: false,
              success (res) {
                if (res.confirm) {
                  console.log("用户点击确定");
                } else if (res.cancel) {
                  console.log("用户点击取消");
                }
              },
            });

            console.log(res.data); // data
          },
        });
      },
    });
  },
  /*collectPaste() {
        var txt;
        var that = this;
        if(!this.data.isCollect){
            that.setData({
                isCollect: true
            })
            txt = '收藏成功'
        }else{
            that.setData({
                isCollect: false
            })
            txt = '取消收藏'
        }
        wx.showToast({
            icon: "none",
            title: txt,
        })
       
    },*/

  goNewEnroll (e) {
    let that = this;
    let argument;
    app.vibrateShort()
    argument = JSON.stringify({
      ...that.data.jobDetail.record,
      jobClassify: this.data.searchForm.jobClassify,
      agencyName: that.data.jobDetail.record.agencyName ? that.data.jobDetail.record.agencyName : that.data.jobDetail.agencyName
    }).replace(/\=|\&/g, "3D");
    console.log('argument', that.data.jobDetail.record);
    if (this.data.isLogin) {
      wx.navigateTo({
        url: `../newEnroll/enroll/index?applyType=1&info=${argument}`,
      });
    } else {
      wx.setStorageSync("comeFromPage", "detail");
      wx.navigateTo({
        url: "../login/index",
      });
    }
    // wx.navigateTo({
    //   url: `../newEnroll/enroll/index?applyType=1&info=${argument}`,
    // });
  },
  emptyMethod () { },

  getPhoneNumber (e) {
    var that = this;
    console.log(e);
    console.log(e.detail.errMsg);
    console.log(that.data.jobDetail.record);
    /*wx.setStorageSync({
            key: "jobDetailStorage",
            data: that.data.jobDetail.record,
        });*/
    wx.setStorageSync("jobDetailStorage", that.data.jobDetail.record);
    // console.log(e);
    // console.log(e.detail.errMsg)
    console.log(e.detail.iv);
    // console.log(e.detail.encryptedData)
    if ("getPhoneNumber:ok" == e.detail.errMsg) {
      //同意
      var iv = e.detail.iv;
      var encryptedData = e.detail.encryptedData;
      wx.checkSession({
        success () {
          //session_key 未过期，并且在本生命周期一直有效
          customRequest("/getWechatTel", {
            header: 'headers',
            method: 'GET',
            data: {
              code: that.data.wxCode,
              iv: iv,
              encryptedData: encryptedData,
              type: "yishoudan",
            }
          }).then((res) => {
            app.globalData.openId = res.data.data.openId;
            let promise = app.setLoginUserTokenInfo(res.data.data.phoneNumber, null);
            var collected = e.currentTarget.dataset.collected;

            console.log(that.data.isAgency);
            if (collected) {
              promise.then((res) => {
                that.setData({
                  isLogin: app.globalData.isLogin,
                });
                that.doCollected(collected, e.currentTarget.dataset.jobid);
              });
            } else {
              /*wx.navigateTo({
                              url: "../enroll/index?applyType=1&tel=" + res.data.data.phoneNumber
                          });*/
              promise.then((res) => {
                let argument;
                argument = JSON.stringify(that.data.jobDetail.record).replace(/\=|\&/g, "3D");
                wx.navigateTo({
                  url: `../newEnroll/enroll/index?applyType=1&info=${argument}`,
                });
              });
            }
            promise.then(() => {
              console.log(app.globalData.loginUserInfo.agencyStatus);
              that.setData({
                isAgency: app.globalData.loginUserInfo.agencyStatus == 1 ? true : false,
              });
            });
            // wx.navigateTo({
            //     url: "../enroll/index?applyType=1&tel=" + res.data.data.phoneNumber
            // });
          })
          // wx.request({
          //   url: app.globalData.ip + "/getWechatTel",
          //   data: {
          //     code: that.data.wxCode,
          //     iv: iv,
          //     encryptedData: encryptedData,
          //     type: "yishoudan",
          //   },
          //   success: function (res) {
          //     console.log(res);
          //     app.globalData.openId = res.data.data.openId;
          //     let promise = app.setLoginUserTokenInfo(res.data.data.phoneNumber, null);
          //     var collected = e.currentTarget.dataset.collected;

          //     console.log(that.data.isAgency);
          //     if (collected) {
          //       promise.then((res) => {
          //         that.setData({
          //           isLogin: app.globalData.isLogin,
          //         });
          //         that.doCollected(collected, e.currentTarget.dataset.jobid);
          //       });
          //     } else {
          //       /*wx.navigateTo({
          //                       url: "../enroll/index?applyType=1&tel=" + res.data.data.phoneNumber
          //                   });*/
          //       promise.then((res) => {
          //         let argument;
          //         argument = JSON.stringify(that.data.jobDetail.record).replace(/\=|\&/g, "3D");
          //         wx.navigateTo({
          //           url: `../newEnroll/enroll/index?applyType=1&info=${argument}`,
          //         });
          //       });
          //     }
          //     promise.then(() => {
          //       console.log(app.globalData.loginUserInfo.agencyStatus);
          //       that.setData({
          //         isAgency: app.globalData.loginUserInfo.agencyStatus == 1 ? true : false,
          //       });
          //     });
          //     // wx.navigateTo({
          //     //     url: "../enroll/index?applyType=1&tel=" + res.data.data.phoneNumber
          //     // });
          //   },
          //   fail: function (res) {
          //     console.log("获取用户手机号错误");
          //   },
          // });
        },
        fail () {
          // session_key 已经失效，需要重新执行登录流程
          wx.login({
            success (res) {
              if (res.code) {
                console.log(res.code);
                //发起网络请求
                customRequest("/getWechatTel", {
                  header: 'headers',
                  method: 'GET',
                  data: {
                    code: res.code,
                    iv: iv,
                    encryptedData: encryptedData,
                    type: "yishoudan",
                  }
                }).then((res) => {
                  let promise = app.setLoginUserTokenInfo(res.data.data.phoneNumber, null);

                  var collected = e.currentTarget.dataset.collected;
                  if (collected) {
                    promise.then((res) => {
                      that.setData({
                        isLogin: app.globalData.isLogin,
                      });
                      that.doCollected(collected, e.currentTarget.dataset.jobid);
                    });
                  } else {
                    promise.then((res) => {
                      let argument;
                      argument = JSON.stringify(that.data.jobDetail.record).replace(/\=|\&/g, "3D");
                      wx.navigateTo({
                        url: `../newEnroll/enroll/index?applyType=1&info=${argument}`,
                      });
                    });
                  }
                  promise.then(() => {
                    console.log(app.globalData.loginUserInfo.agencyStatus);
                    that.setData({
                      isAgency: app.globalData.loginUserInfo.agencyStatus == 1 ? true : false,
                    });
                  });
                })
                // wx.request({
                //   url: app.globalData.ip + "/getWechatTel",
                //   data: {
                //     code: res.code,
                //     iv: iv,
                //     encryptedData: encryptedData,
                //     type: "yishoudan",
                //   },
                //   success: function (res) {
                //     console.log(res);

                //     let promise = app.setLoginUserTokenInfo(res.data.data.phoneNumber, null);

                //     var collected = e.currentTarget.dataset.collected;
                //     if (collected) {
                //       promise.then((res) => {
                //         that.setData({
                //           isLogin: app.globalData.isLogin,
                //         });
                //         that.doCollected(collected, e.currentTarget.dataset.jobid);
                //       });
                //     } else {
                //       promise.then((res) => {
                //         let argument;
                //         argument = JSON.stringify(that.data.jobDetail.record).replace(/\=|\&/g, "3D");
                //         wx.navigateTo({
                //           url: `../newEnroll/enroll/index?applyType=1&info=${argument}`,
                //         });
                //       });
                //     }
                //     promise.then(() => {
                //       console.log(app.globalData.loginUserInfo.agencyStatus);
                //       that.setData({
                //         isAgency: app.globalData.loginUserInfo.agencyStatus == 1 ? true : false,
                //       });
                //     });
                //   },
                //   fail: function (res) {
                //     console.log("获取用户手机号错误");
                //   },
                // });
              } else {
                console.log("获取手机号失败！" + res.errMsg);
              }
            },
          });
        },
      });
    } else {
      //拒绝
      var collected = e.currentTarget.dataset.collected;
      if (collected) {
        try {
          wx.setStorageSync("comeFromPage", "detail");
          wx.setStorageSync("comeFromPageParam", {
            storeJobId: that.data.searchForm.storeJobId
          });
        } catch (e) {
          console.log("detail-页面跳转，设置参数错误：", e);
        }
        wx.navigateTo({
          url: "/pages/login/index",
        });
      } else {
        wx.navigateTo({
          //url: "../enroll/index?applyType=1&tel=" + res.data.data.phoneNumber
          url: "../enroll/index?applyType=1",
        });
      }
    }
    return false;
  },
  setCopy (e) {
    var that = this;
    var contentInfo;
    const query = wx.createSelectorQuery().in(this);
    query
      .select(".contactInfo")
      .boundingClientRect(function (res) {
        let data = e.currentTarget.dataset.content + res.dataset.info
        app.copyFun(data)
      })
      .exec();
  },
  getJobName (e) {
    let data = e.currentTarget.dataset.content
    app.copyFun(data)
  },
  changeContact () {
    console.log(2123);
    wx.navigateTo({
      url: `/pages/configAnnunciate/index`,
    });
  },
  collectPaste (e) {
    console.log(1);
    var txt;
    var that = this;
    var collected = e.currentTarget.dataset.collected;
    var storeJobId = e.currentTarget.dataset.jobid;
    if (this.data.isLogin) {
      that.doCollected(collected, storeJobId);
    } else {
      wx.setStorageSync("comeFromPage", "detail");
      wx.navigateTo({
        url: "../login/index",
      });
    }
    // console.log(collected);
    // if(!this.data.isCollect){
    //     that.setData({
    //         isCollect: true,
    //         collectTxt:'已收藏'
    //     })
    //     txt = '收藏成功'
    // }else{
    //     that.setData({
    //         isCollect: false,
    //         collectTxt:'收藏'
    //     })
    // }
  },
  doCollected (collected, storeJobId) {
    var that = this;
    var url = "/user/collect/job/add";
    if (collected - 1 == 0) {
      url = "/user/collect/job/remove";
    }
    // console.log(app.globalData.headers);
    //发起网络请求
    customRequest(url, {
      header: 'headers',
      method: 'GET',
      data: {
        storeJobId: storeJobId,
        jobClassify: that.data.searchForm.jobClassify
      }
    }).then((res) => {
      var txt;
      if (collected - 1 == 0) {
        //取消收藏
        that.data.jobDetail.record.collected = 2;
        txt = "取消收藏";
      } else {
        //收藏
        that.data.jobDetail.record.collected = 1;
        txt = "收藏成功";
      }
      var pages = getCurrentPages();
      var prevPage = pages[pages.length - 2]; // 上一个页面
      if (prevPage) {
        if (prevPage.data.choiceCollect == 0) {
          prevPage.data.recordList.forEach((item) => {
            console.log(item);
            if (item.id == storeJobId) {
              item.collected = that.data.jobDetail.record.collected;
            }
          });
          prevPage.setData({
            recordList: prevPage.data.recordList,
          });
        }
      }

      that.setData({
        jobDetail: that.data.jobDetail,
        isLogin: app.globalData.isLogin,
      });
      console.log(that.data.jobDetail);
      wx.showToast({
        icon: "none",
        title: txt,
      });
    })
    // wx.request({
    //   url: app.globalData.ip + url,
    //   data: {
    //     storeJobId: storeJobId,
    //   },
    //   header: app.globalData.headers,
    //   method: "GET",
    //   success: function (res) {
    //     var txt;
    //     if (collected - 1 == 0) {
    //       //取消收藏
    //       that.data.jobDetail.record.collected = 2;
    //       txt = "取消收藏";
    //     } else {
    //       //收藏
    //       that.data.jobDetail.record.collected = 1;
    //       txt = "收藏成功";
    //     }
    //     var pages = getCurrentPages();
    //     var prevPage = pages[pages.length - 2]; // 上一个页面
    //     if (prevPage) {
    //       if (prevPage.data.choiceCollect == 0) {
    //         prevPage.data.recordList.forEach((item) => {
    //           console.log(item);
    //           if (item.id == storeJobId) {
    //             item.collected = that.data.jobDetail.record.collected;
    //           }
    //         });
    //         prevPage.setData({
    //           recordList: prevPage.data.recordList,
    //         });
    //       }
    //     }

    //     that.setData({
    //       jobDetail: that.data.jobDetail,
    //       isLogin: app.globalData.isLogin,
    //     });
    //     console.log(that.data.jobDetail);
    //     wx.showToast({
    //       icon: "none",
    //       title: txt,
    //     });
    //   },
    //   fail: function (res) {
    //     console.log("操作失败");
    //   },
    // });
  },
  toggleprice (type) {
    console.log(type);
    if (type.target.dataset.index == 1) {
      this.setData({
        isServicePriceShow: false,
      });
    } else {
      this.setData({
        isServicePriceShow: true,
      });
    }
  },
  imageLoad () {
    this.setData({
      isLoading: false,
    });
  },
  /**
   * 阻止滑动穿透
   *
   *
   */
  modalMove () {
    return false;
  },
  showTobe () {
    this.setData({
      iosDialogTobe: true,
    });
  },
  closeTobe () {
    this.setData({
      iosDialogTobe: false,
    });
  },
  showTobeToast () {
    wx.showModal({
      content: '抱歉，您需先成为伯才代理以获得使用权限。',
      // content: that.data.bclr,
      contentColor: "#ccc",
      confirmColor: "#1890ff",
      confirmText: "确定",
      showCancel: false,
      success (res) {

      },
    });
  },
  showFee () {
    let that = this
    // if (!this.data.isAgency) return false
    console.log('that.data.bclr', that.data.bclr);
    let content, title
    if (that.data.jobDetail.record.returnFeeDesp && (that.data.jobDetail.record.picked || that.data.corpUserFlag)) {
      title = that.data.isAgency ? '佣金: ' + that.data.fuWuFei : ''
      content = that.data.isAgency ? that.data.jobDetail.record.returnFeeDesp : '抱歉，您需先成为伯才代理以获得使用权限。'

    } else {
      title = '详询客服'
      content = '因三方项目政策变动太快，详情请咨询客服。页面左下角点击“联系客服”直接联系我哟~'
    }
    wx.showModal({
      title,
      content,
      contentColor: "#ccc",
      confirmColor: "#1890ff",
      confirmText: "确定",
      showCancel: false,
      success (res) {

      },
    });
  }
});