// pages/extendProduct/extendProduct.js
const app = getApp()
const wxService = require('../../utils/wxService')
const utils = require('../../utils/util')
const envInfo = require('../../config/index').envInfo
import { Integer } from '../../utils/integerDigitalConvertion'
const { memberId, member } = wx.getStorageSync('_baseUserInfo')

wxService.page({

  /**
   * 页面的初始数据
   */
  data: {
    currentTab: 0,
    isAllSelect: false,
    showShareModal:false,
    showCardModal: false,
    totalPages:0,
    myTotalPages:0,
    currentShareContent: null,
    pageNo:1,
    pageNum: 1,
    pageSize: 10,
    extendProList:[],
    myExtendList:[],
    noMoreFlag: false,
    myShareCount:'',
    extendProBanner: '',
    scene: '', //触点参数
    proData : []
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let memberId = options.memberId;
    if (memberId){
      let tentacleInfo = {
        content: '推广商品',
        tentacleId: memberId,
        title: '推广商品',
        contentType: app.globalData.contants.SHARE_TYPE.PRODUCTS_PROMOTION,
        type: 3// 1:门店,2:员工(暂时不做),3:会员,4:第三方外部渠道,5:智能营销
      };

      this.generatePointObject(tentacleInfo);
    }
  },

  // 点击切换
  clickTab: function (e) {
    const { current } = e.target.dataset
    if (this.data.currentTab == current) {
      return false;
    } else {
      this.setData({
        currentTab: current,
        myExtendList: [],  // 清空数据
        // invalidCouponList: [],
      })
    }
    // 可使用
    if (current == 0) {
      wx.showShareMenu()
      this.setData({
        pageNo: 1
      })
      this.getExtendProList(this.data.pageNo,10)
    } else if (current == 1) {
      // 我的推广
      wx.hideShareMenu();
      this.getMyShareCount()
      this.setData({
        pageNum: 1
      })
      this.getMyExtendOrderList(this.data.pageNum,10)
    }
  },

  // 选择商品
  selectPro(e){
    let proData = []
    let extendProList = this.data.extendProList
    var index = e.currentTarget.dataset.index
    if (extendProList[index].isSelect) {
      extendProList[index].isSelect = false
    } else {
      extendProList[index].isSelect = true
    }
    this.setData({
      extendProList: extendProList
    })
    for (var i in extendProList) {
      if (extendProList[i].isSelect) {
        proData.push(extendProList[i])
      }
    }
    console.log(proData)
    this.setData({
      proData: proData
    })
  },

  _showMiniCard(e) {
    console.log(e)
    this.setData({
      showCardModal: true
    })
  },


  //全选
  allSelect() {
    this.setData({
      isAllSelect: !this.data.isAllSelect
    })
    if (this.data.isAllSelect) {
      this.setData({
        extendProList: this.data.extendProList.map((item) => {
          item.isSelect = true
          return item
        }),
        proData: this.data.extendProList
      })
    } else {
      this.setData({
        extendProList: this.data.extendProList.map((item) => {
          item.isSelect = false
          return item
        }),
        proData: []
      })
    }
  },

  //生成海报
  onTapPoster(){
    this.getChooseExtendPro(2)
  },

  // 获取选择推广的商品
  getChooseExtendPro(type){
    if (!this.data.proData.length) {
      wx.showToast({
        title: '请先选择商品',
        icon: 'none'
      })
      return false;
    }
    let spreadProducts = []
    for (var i in this.data.proData){
      spreadProducts.push({
        id: this.data.proData[i].productId,
        imgUrl: this.data.proData[i].productImgUrl,
        name: this.data.proData[i].productName
      })
    }
    console.log(spreadProducts)
    
    wxService.post(`/merchant/spread/save`, {
      spreadProducts: spreadProducts
    }).then(res => {
      if (res) {
        const { result, data } = res.data
        if (result == 0) {
          this.data.proData.forEach((item)=>{
            item.url = item.productImgUrl
            item.title = item.productName
          })
          let tentacleInfo = {
            content: JSON.stringify(this.data.proData),
            contentId: data.id,
            contentType: app.globalData.contants.SHARE_TYPE.PRODUCTS_PROMOTION, //内容类型 
            title: this.data.proData[0].productName,
            type: 3// 1:门店,2:员工(暂时不做),3:会员,4:第三方外部渠道,5:智能营销
          }
          console.log('4444', tentacleInfo.content)

          this.data.currentShareContent = data;
          console.log('++++++++++++++++',this.data.currentShareContent)

          wxService.getTentacleContent(tentacleInfo).then(res => {
            if (res && res.id) {
              this.data.currentShareContent.tentacleId = res.id;
              let id = Integer.digit(this.data.currentShareContent.id, 10, 64);
              let tentacleId = Integer.digit(this.data.currentShareContent.tentacleId, 10, 64);
              var path = 'subPackage/page/pages/friendShareList/friendShareList';
              var scene = 'i=' + id + '&t=' + tentacleId
              if(type == 1){
                this.setData({
                  showCardModal: true,
                  cardTitle: this.data.proData[0].productName,
                  cardUrl: this.data.proData[0].productImgUrl,
                  pagePath: path,
                  scene: scene
                });

              }else{
                this.setData({
                  cardTitle: this.data.proData[0].productName,
                  cardUrl: this.data.proData[0].productImgUrl,
                  pagePath: path,
                  scene: scene
                });
                this.getMiniCode()
              }
            }
          })
        }
      }
    })
  },

  //获取二维码
  getMiniCode() {
    const urls = utils.getCurrentPageUrlWithArgs()
    const page = urls && urls.split("?")[0]

    let data = {
      "autoColor": true,
      "page": this.data.pagePath,
      "scene": this.data.scene,
      "width": 100
    }
    wxService.post(`/marketing/quickMark/getAppQrCodePicture`, data).then(res => {
      const { result, data } = res.data
      if (result == 0) {
        this.setData({
          codeImg: app.globalData.imageUrl + data
          // codeImg: "https://hwimagecdn.ihotwind.cn/usr/201908/miniQrCode-f00c5051fef7479395efb193431762c4.jpg"
        })
        if (this.data.codeImg) {
          this.selectComponent('#getPoster').getAvaterInfo()
        }
      }
    })
  },

  //快速分享
  onTapShare() {
    this.getChooseExtendPro(1)
  },

  // 获取推广商品列表
  getExtendProList(pageNo, pageSize){
    wx.showLoading({
      title: '加载中',
      mask: true
    })
    wxService.post(`/merchant/share/productBonus/buyer/findPage?pageNo=${pageNo}&pageSize=${pageSize}`,{}).then(res => {
      if (res) {
        const { result, data } = res.data
        if (result == 0) {
          wx.hideLoading()
          this.setData({
            extendProList: this.data.pageNo == 1 ? [...data.content] : [...this.data.extendProList, ...data.content],
            totalPages: data.totalPages
          }, () => {
            // this.setData({
            //   no_data: this.data.extendProList.length ? true : false
            // })
          })
        }
      }
    })
  },

  // 获取我的推广订单列表
  getMyExtendOrderList(pageNum, pageSize){
    console.log('pageNum----', pageNum)
    wx.showLoading({
      title: '加载中',
      mask: true
    })
    wxService.post(`/marketing/tentacleContent/getTentacleContentDTO?pageNum=${pageNum}&pageSize=${pageSize}`).then(res => {
      if (res) {
        const { result, data } = res.data
        if (result == 0) {
          wx.hideLoading()
          data.content.forEach((item) =>{
            wxService.getContentByContentType(item.tentacleContent)  
          })
          this.setData({
            myExtendList: pageNum == 1 ? [...data.content] : [...this.data.myExtendList, ...data.content],
            myTotalPages: data.totalPages,
            noMoreFlag: data.content.length < pageSize ? true : false,
          }, () => {
          })
        }
      }
    })
  },

  // 分享促成的订单数
  getMyShareCount(){
    wxService.get(`/sale/trade/buyer/countByMyShare`).then(res => {
      if (res) {
        const { result, data } = res.data
        if (result == 0) {
          this.setData({
            myShareCount: data
          }, () => {
            
          })
        }
      }
    })
  },

  // 推广商品banner
  getExtendProBanner() {
    wxService.get(`/merchant/share/productSectionBonus/buyer/query`).then(res => {
      if (res) {
        const { result, data } = res.data
        if (result == 0 && data) {
          this.setData({
            extendProBanner: data.backgroundImgUrl
          }, () => {

          })
        }
      }
    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    const { memberId, member } = wx.getStorageSync('_baseUserInfo')
    this.getExtendProBanner()
    this.setData({
      pageNo: 1
    })
    this.getExtendProList(this.data.pageNo,10)
    this.data.currentShareContent = null;
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.setData({
      pageNum: 1,
    })
    this.getMyExtendOrderList(this.data.pageNum, 10)
    wx.stopPullDownRefresh();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if (this.data.currentTab == 0){
      if (this.data.pageNo < this.data.totalPages){
        this.setData({
          pageNo: this.data.pageNo + 1,
        }, () => {
          this.getExtendProList(this.data.pageNo,10)
        })
      }
    }else{
      if (this.data.pageNum < this.data.myTotalPages) {
        this.setData({
          pageNum: this.data.pageNum + 1,
        }, () => {
          this.getMyExtendOrderList(this.data.pageNum,10)
        })
      }
    }
  },
  
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (res) {
    if (res.from != 'menu') {
      let id = Integer.digit(this.data.currentShareContent.id, 10, 64);
      let tentacleId = Integer.digit(this.data.currentShareContent.tentacleId, 10, 64);
      var path = 'subPackage/page/pages/friendShareList/friendShareList?i=' + id + '&t=' + tentacleId;
      console.log('用户点击右上角分享', this.data.currentShareContent.id)
      console.log(path)
      return {
        path: path,
        imageUrl: this.data.proData[0].productImgUrl, // 可以更换分享的图片
      }
    }else{
      const { memberId, member } = wx.getStorageSync('_baseUserInfo')
      //修改为参数memberId
      var path = `pages/extendProduct/extendProduct`;
      console.log('推广商品memberId-----', memberId)
      if (memberId){
        let m = Integer.digit(memberId, 10, 64);
        path = `pages/extendProduct/extendProduct?m=${m}`;
      }
      return {
        path: path,
        imageUrl: this.data.extendProList && this.data.extendProList.length > 0 ? this.data.extendProList[0].productImgUrl : '',
      }
    }
  }
})