// 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:[],
    myShareCount:'',
    extendProBanner: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  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.getExtendProList(1,10)
    } else if (current == 1) {
      // 我的推广
      wx.hideShareMenu();
      this.getMyShareCount()
      this.getMyExtendOrderList(1,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
    })
  },

  //全选
  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: []
      })
    }
  },

  //快速分享
  onTapShare(){
    console.log('111')
    this.setData({
      showShareModal: true
    })
  },

  // 获取选择推广的商品
  getChooseExtendPro(){
    if (!this.data.proData) {
      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.tentacleId) {
              this.data.currentShareContent.tentacleId = res.tentacleId;

              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;
              this.setData({
                showCardModal: true,
                cardTitle: this.data.proData[0].productName,
                cardUrl: this.data.proData[0].productImgUrl,
                pagePath: path
              });
            }
          })
        }
      }
    })
  },

  //生成卡片
  onTapPoster() {
    this.getChooseExtendPro()
  
  },

  // 获取推广商品列表
  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){
    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) =>{
             //内容类型 1.文章 2.商品 3.页面
            // if (item.content){
            //   if (item.contentType == 3){
            //     item.content = item.content
            //   }else{
            //     let content = JSON.parse(item.content)
            //     item.contentArr = content
            //   }
            // }
            wxService.getContentByContentType(item)  
          })
          this.setData({
            myExtendList: this.data.pageNum == 1 ? [...data.content] : [...this.data.myExtendList, ...data.content],
            myTotalPages: data.totalPages
          }, () => {
          })
          console.log('00000',this.data.myExtendList)
        }
      }
    })
  },

  // 分享促成的订单数
  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 () {
    this.getExtendProBanner()
    this.getExtendProList(1,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{
      //修改为参数memberId
      var path = `pages/extendProduct/extendProduct`;
      if (memberId){
        let m = Integer.digit(memberId, 10, 64);
        path = `pages/extendProduct/extendProduct?m=${m}`;
      }
      return {
        path: path,
        imageUrl: this.data.extendProList[0].productImgUrl,
      }
    }
  }
})