import {
  getPositionDetail,
  positionApply,
  groupApply,
  groupList,
  saveFavoritePosition,
  saveTask
} from '../../services/index.js'
import {
  imgServerUrl,
  imgServerUrl_new
} from '../../config/config.js'
import {
  showToast
} from '../../utils/tips.js'

const WxParse = require('../../plugins/wxParse/wxParse.js');
import Poster from '../../components/wxa-plugin-canvas/poster/poster';
const app = getApp();

Page({
  data: {
    hasShare: true,
    imgServerUrl: imgServerUrl,
    imgServerUrl_new: imgServerUrl_new,
    hpPositionId: 0,
    positionCategory: -1, //0：全职 1：兼职 2：入职奖励 3：高薪急聘 4：拼团岗位 5：福利岗位 8:自发布全职 9：自发布兼职
    isShowList: false,
    clearTimer: false,
    comScale: '',
    comType: '',
    myFormat: ['天', '时', '分', '秒'],
    authMask: false,
    detailArray: [],
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    detailIndex: 0, //详情指引
    isApply: false,
    storeAction: [],
    showJoinPt: false, //显示加入拼工
    showAllPt: false, //显示所有拼工
    allPtList: [],
    leftTime: 0,
    isEnd: 0, //岗位是否已结束0：未结束；1：结束
    myGroupId: '', //我的拼团id
    groupId: '', //拼团id
    inviteUser_id: '', //拼团邀请人
    isFarovite: false, //是否收藏
    maxReward: 0, //入职最高奖励
    minReward: 0, //入职最低奖励
    isLogin: false,
    showShare: false,
    shareImg: '',
  },
  onLoad: function (options) {
    if (options.scene) {
      const _data = this.getQuery(options.scene);
      this.setData({
        hpPositionId: _data.pd,
        positionCategory: _data.pc || 0,
      })
      return
    }
    if (options.query) {
      this.setData({
        hpPositionId: options.query.pd,
        positionCategory: options.query.pc || 0,
      })
      return
    }
    this.setData({
      hpPositionId: options.hpPositionId || options.pd,
      positionCategory: options.cate || options.pc || 0,
    })
  },
  onShow: function () {
    var userId = wx.getStorageSync("user_id");
    var userToken = wx.getStorageSync("user_token");
    var memberId = wx.getStorageSync("member_id");
    var isLogin = false;
    if (userId && memberId) {
      isLogin = true;
      app.globalData.userId = userId;
      app.globalData.userToken = userToken;
      app.globalData.memberId = memberId;
    }
    this.setData({
      isLogin: isLogin
    })
    this.fetchData();
    // this.fetchPtList();
  },

  onShareAppMessage: function () {
    // 调用分享接口  task_id 10代表转发
    saveTask({
      user_id: wx.getStorageSync('user_id'),
      user_token: wx.getStorageSync('user_token'),
      member_id: wx.getStorageSync('member_id'),
      task_id: 10
    })
    this.setData({
      showShare: false
    })
    return {
      title: this.data.postitionDetail.positionName,
      path: '/pages/detail/index?pc=' + this.data.positionCategory + '&pd=' + this.data.hpPositionId,
      imageUrl: this.data.imgServerUrl + '/images/happyjob/detail_share.jpg'
    }
  },
  getQuery(data) {
    const _data = decodeURIComponent(data);
    const json = _data.split('&').reduce((json, val, key) => {
      const arr = val.split('=');
      json[arr[0]] = arr[1];
      return json
    }, {})
    return json
  },
  toCompanyDesc() {
    wx.setStorage({
      key: 'CompanyDesc',
      data: this.data.postitionDetail.hpCompany.companyDescription,
      success: function (res) {
        wx.navigateTo({
          url: '/pages/company-desc/company-desc'
        })
      }
    })
  },
  toBusDetail() {
    wx.setStorage({
      key: 'BusDetail',
      data: this.data.postitionDetail.busDetail,
      success: function (res) {
        wx.navigateTo({
          url: '/pages/bus-detail/bus-detail'
        })
      }
    })
  },
  creatBlock() {
    let arr = [this.data.postitionDetail.accommodation, this.data.postitionDetail.socialSecurity, this.data.postitionDetail.workDinner, this.data.postitionDetail.regularBus, '']
    if (this.data.postitionDetail.specialWelfare) {
      arr = this.data.postitionDetail.specialWelfare.split(',').concat(arr)
    }
    arr.push(this.data.postitionDetail.settlementMethod);
    return arr.filter(val => !!val)
  },
  // getTime(start, end) {
  //   if (!start || !end) {
  //     return ''
  //   }
  //   let _start = start.replace(/-/g, '/');
  //   let _end = end.replace(/-/g, '/');

  //   let _start_time = new Date(_start);
  //   let _end_time = new Date(_end);

  //   var month = _start_time.getMonth() + 1;
  //   var day = _start_time.getDate();


  //   return [_start_time.getMonth() + 1, _start_time.getDate()].map(this.formatNumber).join('-') + ' 至 ' + [_end_time.getMonth() + 1, _end_time.getDate()].map(this.formatNumber).join('-');


  // },
  // formatNumber(n) {
  //   n = n.toString()
  //   return n[1] ? n : '0' + n
  // },
  onCreatePoster() {
    Poster.create();
  },
  onPosterSuccess(e) {
    var detail = e.detail;
    this.setData({
      shareImg: detail,
      showShare: true
    })
    wx.hideLoading()
  },
  onPosterFail(err) {
    wx.hideLoading()
    console.error(err);
  },
  share() {

    let blocks = [];
    let block = [];
    let y = 598;
    let _arr = this.creatBlock();
    let bg = this.data.positionCategory == 5 ? imgServerUrl + '/images/happyjob/share-fuli.jpeg' : imgServerUrl + '/images/happyjob/share_img_fulltime.jpeg';
    let posterConfig = {
      width: 908,
      height: 1502,
      debug: false,
      blocks,
      texts: [{
        x: 146,
        y,
        width: 600,
        text: this.data.postitionDetail.positionName,
        fontSize: 62,
        color: '#333333',
        zIndex: 2,
      },
      {
        x: 504,
        y: 1234,
        text: '一站式求职平台',
        fontSize: 34,
        // fontWight:'500',
        color: '#666666',
        zIndex: 2,
      }
      ],
      images: [{
        width: 908,
        height: 1502,
        x: 0,
        y: 0,
        url: bg,
        zIndex: 1,
      }, {
        width: 264,
        height: 264,
        x: 158,
        y: 1030,
        url: `${this.data.qrcodeUrl}`,
        zIndex: 3
      }],
    }
    if (this.data.postitionDetail.hpCompany) {
      y += 61;
      posterConfig.texts.push({
        x: 146,
        y,
        width: 600,
        text: this.data.postitionDetail.hpCompany ? this.data.postitionDetail.hpCompany.companyName : '',
        fontSize: 32,
        color: '#666666',
        zIndex: 2,
      })
    }
    if (this.data.postitionDetail.salary || this.data.postitionDetail.totalSalary || this.data.postitionDetail.basicSalary) {
      y += 80;
      posterConfig.texts.push({
        x: 146,
        y,
        text: this.data.postitionDetail.salary || this.data.postitionDetail.totalSalary || this.data.postitionDetail.basicSalary,
        fontSize: 62,
        // fontWight:'500',
        color: '#FE7235',
        zIndex: 2,
      })
    }
    if (_arr.length) {
      y += 35;
      _arr.forEach(val => {
        block.push({
          y,
          height: 76,
          paddingLeft: 30,
          borderWidth: 2,
          borderColor: '#0177FF',
          borderRadius: 10,
          marginLeft: 24,
          text: {
            text: val,
            fontSize: 38,
            color: '#0177FF',
            baseLine: 'middle'
          },
          zIndex: 2,
        })
      })
      blocks.push({
        x: 146,
        y,
        height: 76,
        width: 542,
        block,
        beyond: {
          y: 770,
          width: 56,
          height: 56,
          zIndex: 3,
          text: {
            text: '...',
            fontSize: 38,
            color: '#0177FF',
            baseLine: 'middle'
          },
        },
        zIndex: 2,
      })
    }
    if (this.data.postitionDetail.maleReward || this.data.postitionDetail.femaleReward || this.data.postitionDetail.platformAllowance || this.data.maxReward) {
      y += 112;
      let text = `入职最高奖励${this.data.postitionDetail.maleReward ? `男 ${this.data.postitionDetail.maleReward}` : ''}  ${this.data.postitionDetail.femaleReward ? `女${this.data.postitionDetail.femaleReward}` : ''} ${this.data.postitionDetail.platformAllowance ? `+${this.data.postitionDetail.platformAllowance || ''}` : ''}`;
      blocks.push({
        x: 146,
        y,
        height: 42,
        // fontWight:'500',
        text: {
          text: `${text.trim() === '入职最高奖励' ? `${this.data.maxReward ? `拼团成功最高可得${this.data.maxReward}` : ''}` : `${text} ${this.data.maxReward ? `拼团成功最高可得${this.data.maxReward}` : ''}`} `,
          fontSize: 26,
          color: '#fff',
          baseLine: 'middle'

        },
        paddingLeft: 15,
        backgroundColor: '#FE7235',
        borderRadius: 10,
        zIndex: 2,
      })
    }
    this.setData({
      posterConfig
    }, _ => {
      this.onCreatePoster()
    })

  },
  cloaseShare() {
    this.setData({
      showShare: false
    })
  },
  saveShareImg() {
    wx.saveImageToPhotosAlbum({
      filePath: this.data.shareImg,
      success: (res) => {
        showToast('已保存到相册,快去分享吧！');
        this.setData({
          showShare: false
        })
      },
      fail(err) {
        showToast('请授权保存到相册')
        that.setData({
          hasAuth: false
        })
      }
    })
  },
  //获取岗位详情
  fetchData() {
    let paramsObj = {
      position_category: this.data.positionCategory,
      id: this.data.hpPositionId,
      member_id: app.globalData.memberId
    }
    Object.assign(paramsObj);
    getPositionDetail(paramsObj).then(data => {
      let postitionDetail = {};
      let groupLessList = {};
      var leftTime = 0;
      var myGroupId = '';
      switch (this.data.positionCategory) {
        case "0":
          postitionDetail = data.data.hpFulltimePosition
          break;
        case "1":
          postitionDetail = data.data.hpParttimePosition
          break;
        case "2":
          postitionDetail = data.data.hpRewardPosition
          break;
        case "3":
          postitionDetail = data.data.hpGoodmoneyPosition
          break;
        case "4":
          postitionDetail = data.data.hpGroupPosition;
          leftTime = data.data.hpGroupPosition.groupEndTime;
          groupLessList = data.data.groupLessList;
          myGroupId = data.data.myGroupId;
          var maxReward;
          var minReward;
          var femaleReward = data.data.hpGroupPosition.femaleReward;
          var maleReward = data.data.hpGroupPosition.maleReward;
          var fiveGroupCashback = data.data.hpGroupPosition.fiveGroupCashback;
          var threeGroupCashback = data.data.hpGroupPosition.threeGroupCashback;
          var hasReward = data.data.hpGroupPosition.hasReward;
          if (hasReward == 1) {
            if (maleReward >= femaleReward) {
              maxReward = fiveGroupCashback + maleReward;
              minReward = femaleReward;
            } else {
              maxReward = fiveGroupCashback + femaleReward;
              minReward = maleReward;
            }
          } else {
            maxReward = fiveGroupCashback;
            minReward = 0;
          }
          this.setData({
            maxReward: maxReward,
            minReward: minReward
          })
          break;
        case "5":
          postitionDetail = data.data.hpWelfarePosition
          break;
        case "8":
          postitionDetail = data.data.hpFulltimePosition
          break;
        case "9":
          postitionDetail = data.data.hpParttimePosition
          break;
      }
      if (data.data.isEnd == 1) {
        this.setData({
          isEnd: data.data.isEnd
        })
      } else {
        console.log("该岗位未结束")
      }
      this.setData({
        postitionDetail: postitionDetail,
        isApply: data.data.isApply,
        leftTime: leftTime,
        storeAction: groupLessList,
        myGroupId: myGroupId,
        isFarovite: data.data.isFarovite,
        qrcodeUrl: data.data.qrcodeUrl
      })
      //富文本转义
      var detailArray = [];
      if (postitionDetail.hpWelfarePositionDetailList != null && postitionDetail.hpWelfarePositionDetailList.length > 0) {
        for (var i = 0; i < postitionDetail.hpWelfarePositionDetailList.length; i++) {
          var ss = WxParse.wxParse('positionDetail', 'html', postitionDetail.hpWelfarePositionDetailList[i].positionDetail, this);
          detailArray.push(ss);
        }
        this.setData({
          detailArray: detailArray
        })
      }
      //富文本转义
      if (postitionDetail.applyCondition) {
        WxParse.wxParse('applyCondition', 'html', postitionDetail.applyCondition, this);
      }
      // this.getNodePos();
    })
  },

  //获取所有拼工列表
  fetchPtList() {
    if (this.data.isEnd == 1) {
      showToast('拼团已结束')
      return false
    }
    let paramsObj = {
      positionCategory: this.data.positionCategory,
      positionId: this.data.hpPositionId,
    }
    Object.assign(paramsObj);
    groupList(paramsObj).then(data => {
      this.setData({
        allPtList: data.data.groupList
      })
    })
  },

  //申请工作
  applyJob(e) {
    var self = this;
    if (!self.data.isLogin) {
      wx.navigateTo({
        url: '/pages/login/login',
      })
      return;
    }
    wx.showModal({
      title: '提示',
      content: '确定投递简历吗?',
      success: function (res) {
        if (res.confirm) {
          let {
            formId
          } = e.detail;
          let paramsObj = {
            positionCategory: self.data.positionCategory,
            positionId: self.data.hpPositionId,
            user_id: app.globalData.userId,
            user_token: app.globalData.userToken,
            member_id: app.globalData.memberId
          }
          Object.assign(paramsObj);
          positionApply(paramsObj).then(data => {
            showToast('申请职位成功', 'success')
            setTimeout(function () {
              wx.navigateBack();
            }, 2000)
          }).catch(data => {
            //没有简历
            if (data.errcode == 1015) {
              showToast(data.errmsg);
              wx.navigateTo({
                url: '/pages/user-info/user-info',
              })
            }
          })
          // 上报投递岗位订阅消息
          wx.aldPushSubscribeMessage({
            eventId: '5e57819c599957a85868aacc',
          });
        } else if (res.cancel) {

        }
      }
    })
  },

  //申请开团
  applyPt(e) {
    var self = this;
    if (!self.data.isLogin) {
      wx.navigateTo({
        url: '/pages/login/login',
      })
      return;
    }
    wx.showModal({
      title: '提示',
      content: '确定提交开团申请吗?',
      success: function (res) {
        if (res.confirm) {
          let {
            formId
          } = e.detail;
          let paramsObj = {
            // groupId: self.data.groupId,
            // inviteUser_id: self.data.inviteUser_id,
            positionCategory: self.data.positionCategory,
            positionId: self.data.hpPositionId,
            user_id: app.globalData.userId,
            user_token: app.globalData.userToken,
            member_id: app.globalData.memberId
          }
          Object.assign(paramsObj);
          groupApply(paramsObj).then(data => {
            var hpPositionGroupId = data.data.hpApplyPosition.groupId
            showToast("开团成功");
            wx.navigateTo({
              url: '../pt-detail/index?gd=' + hpPositionGroupId + '&pc=' + self.data.positionCategory + '&pd=' + self.data.hpPositionId,
            })
          }).catch(data => {
            //没有简历
            if (data.errcode == 1015) {
              showToast(data.errmsg);
              wx.navigateTo({
                url: '/pages/user-info/user-info',
              })
            }
          })
        } else if (res.cancel) {

        }
      }
    })
  },

  //我的拼团
  myApply() {
    var self = this;
    if (!self.data.isLogin) {
      wx.navigateTo({
        url: '/pages/login/login',
      })
      return;
    }
    wx.navigateTo({
      url: '../pt-detail/index?gd=' + self.data.myGroupId + '&pc=' + self.data.positionCategory + '&pd=' + self.data.hpPositionId,
    })
  },

  //拨打手机号
  phoneCall() {
    if (this.data.postitionDetail.contactPhone) {
      wx.makePhoneCall({
        phoneNumber: this.data.postitionDetail.contactPhone,
        success: function (data) {
          console.log(data)
        },
        fail: function (data) {
          console.log(data)
        }
      })
    } else {
      showToast('暂无手机号')
    }
  },
  //查看线路
  toRoadsLine() {
    wx.navigateTo({
      url: '../roadsLine/index',
    })
  },
  // 获取公司规模描述
  getComScale(lower, high) {

    if (!lower || lower == 0) {
      return high + '人以下'
    }
    if (!high || high == 0) {
      return lower + '人以上'
    }
    return lower + '-' + high + '人'
  },
  //获取位置
  getNodePos() {
    if (this.data.positionCategory != 5) {
      var query = wx.createSelectorQuery()
      query.select('#base').boundingClientRect()
      query.select('#require').boundingClientRect()
      query.select('#otherWelfare').boundingClientRect()
      query.select('#jieshao').boundingClientRect()
      var that = this;
      query.exec(function (res) {
        that.setData({
          basePos: res[0].top - 40,
          requirePos: res[1].top - 40,
          otherWelfarePos: res[2].top - 40,
          jieshaoPos: res[3].top - 40
        })
      })
    }
  },
  //距离页面滚动
  goDeatil: function (e) {
    var index = e.currentTarget.dataset.index;
    this.setData({
      detailIndex: index
    })
    let top = e.currentTarget.dataset.top
    wx.pageScrollTo({
      scrollTop: top,
      duration: 0
    })
  },

  // 加入拼工
  joinPt(e) {
    var index = e.currentTarget.dataset.index;
    this.setData({
      showAllPt: false,
      showJoinPt: true,
      joinPtList: this.data.storeAction[index]
    })
  },

  // 加入拼工(所有拼工)
  joinPt_1(e) {
    var index = e.currentTarget.dataset.index;
    this.setData({
      showAllPt: false,
      showJoinPt: true,
      joinPtList: this.data.storeAction[index]
    })
  },

  hideJoinPt() {
    this.setData({
      showJoinPt: false
    })
  },
  cancelPt() {
    this.setData({
      showJoinPt: false
    })
  },

  //加入拼工，进入拼工详情
  confirmPt(e) {
    var self = this;
    if (!self.data.isLogin) {
      self.setData({
        showJoinPt: false
      })
      wx.navigateTo({
        url: '/pages/login/login',
      })
      return;
    }
    var groupId = e.currentTarget.dataset.groupid;
    self.setData({
      showJoinPt: false
    })
    wx.navigateTo({
      url: '../pt-detail/index?gd=' + groupId + '&pc=' + self.data.positionCategory + '&pd=' + self.data.hpPositionId,
    })
  },

  // 所有拼工
  allPt(e) {
    if (this.data.storeAction.length > 0) {
      this.setData({
        showAllPt: true
      })
    } else {
      showToast("拼工都已经完成啦，您可以申请开团哦！")
    }
  },
  hideAllPt() {
    this.setData({
      showAllPt: false
    })
  },

  hideAuth() {
    this.setData({
      authMask: false
    })
  },
  submitInfo(e) {
    console.log('form发生了submit事件，事件数据为：', e)
  },
  toPt() {
    wx.navigateTo({
      url: '../document/pt'
    })
  },
  toFanxian() {
    wx.navigateTo({
      url: '../document/fanxian'
    })
  },

  imageLoad() {
    var that = this
    var query = wx.createSelectorQuery()
    query.select('.wel_top').boundingClientRect()
    query.exec(function (res) {
      that.setData({
        swiperH: res[0].height
      })
    })
  },
  onError(err) {
    app.aldstat.sendEvent('报错', {
      'err': err
    });
  },
  //跳转工作地址列表
  toaddressdetail() {
    wx.setStorageSync("addressList", this.data.postitionDetail.hpPositionAddressList);
    wx.navigateTo({
      url: '../address/index',
    })
  },
  //收藏岗位
  favourate() {
    var self = this;
    if (!self.data.isLogin) {
      wx.navigateTo({
        url: '/pages/login/login',
      })
      return;
    }
    var isFavorite = self.data.isFarovite ? 0 : 1;
    let paramsObj = {
      positionCategory: self.data.positionCategory,
      positionId: self.data.hpPositionId,
      user_id: app.globalData.userId,
      user_token: app.globalData.userToken,
      isFavorite: isFavorite,
      member_id: app.globalData.memberId
    }
    Object.assign(paramsObj);
    saveFavoritePosition(paramsObj).then(data => {
      if (data.data.isFavorite) {
        showToast('收藏成功');
        // 上报收藏订阅消息
        wx.aldPushSubscribeMessage({
          eventId: '5ea25b7f7739104342928e98',
        });
      } else {
        showToast('取消收藏');
      }
      self.setData({
        isFarovite: data.data.isFavorite
      })
    })
  },
  callPhone() {
    wx.makePhoneCall({
      phoneNumber: '4006900099',
    })
  }
})