// subPackage/page/pages/grassCommunity/grassCommunity.js
const app = getApp()
const wxService = require('../../../../utils/wxService')
const utils = require('../../../../utils/util')
const { memberId } = wx.getStorageSync('_baseUserInfo')
const envInfo = require('../../../../config/index').envInfo

wxService.page({

  /**
   * 页面的初始数据
   */
  data: {
    pics:[],
    showSelectRelatedGoods: false,
    proGoods:[],
    params:{
      article: "",
      headline: "",
      sspList: [],
      stcList: [],
      userId: memberId,
      tagsId:''
    },
    tabName:'',
    video:'',
    pageNo:1,
    pageSize:100,
    requesting: false,
    showSelectTabModal: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(options)
    if(options && options.id){
      this.setData({
        'params.id': options.id
      },() => {
        this.getInitInfo()
      })
    }
  },

  /**
  * 生命周期函数--监听页面显示
  */
  onShow: function () {
    console.log('onshow')
  },

  // 获取编辑详情
  getInitInfo(){
    const { memberId } = wx.getStorageSync('_baseUserInfo')
    let params = {
      id: this.data.params.id,
      userId: memberId
    }
    wxService.post(`/merchant/contentMobileTerminal/terminalContentDetails`, params).then(res => {
      const { result, data } = res.data
      if (result == 0) {
        this.setData({
          params:{
            article: data.article,
            headline: data.headline,
            sspList: data.sspList,
            userId: memberId,
            id:data.id
          }
        })
        for (var i in data.sspList){
          if (data.sspList[i].url){
            this.data.pics.push(data.sspList[i].url)
          }
          if (data.sspList[i].videoUrl){
            this.setData({
              video: data.sspList[i].videoUrl
            })
          }
        }

        this.setData({
          pics: this.data.pics
        })
        this.getInitPro(data.productIds)
      }
    }).finally(() => {
    })
  },

  // 获取关联商品
  getInitPro(productIds){
    if (productIds && productIds.length > 0){
      wxService.post(`/sale/product/buyer/listPage?pageNo=${this.data.pageNo}&pageSize=${this.data.pageSize}`,{
        productIds: productIds
      }).then(res => {
        const { result, data } = res.data
        if (result == 0 && data.content) {
          this.setData({
            proGoods: data.content
          })
          let stcList = []
          for (var i in this.data.proGoods) {
            stcList.push({
              commodityId: this.data.proGoods[i].productId
            })
            this.setData({
              'params.stcList': stcList
            })
          }
        }
      }).finally(() => {
      })
    }
  },

  // 关联商品
  handleRelatedGoods(){
    console.log('关联商品')
    this.setData({
      showSelectRelatedGoods: true
    })
  },
  uploadImg(){
    this.chooseImg()
  },
  chooseImg(){
    let that = this;
    let pics = this.data.pics ;
    var url = envInfo.ctx + '/merchant/upload/pic'
    wx.chooseImage({
      count: 5 - pics.length, // 最多可以选择的图片5张，
      sizeType: ['original', 'compressed'], // original 原图，compressed 压缩图，默认二者都有
      sourceType: ['album', 'camera'], // album 从相册选图，camera 使用相机，默认二者都有
      success: function (res) {
        var imgsrcs = res.tempFilePaths;
        imgsrcs.forEach(src => {
          pics.push(src);
        });
        that.setData({
          pics: pics
        });
        // console.log(',..............',that.data.pics)
        that.moreImgUpload({
          url: url,//这里是你图片上传的接口
          path: imgsrcs//这里是选取的图片的地址数组        
        });
      },
      fail: function () {
        // fail      
      },
      complete: function () {
        // complete      
      }
    })
  },
 
  // 关联商品
  _selectGoods(e){
    this.setData({
      proGoods: e.detail
    })
    let stcList = []
    for (var i in this.data.proGoods) {
      stcList.push({
        commodityId: this.data.proGoods[i].productId
      })
      this.setData({
      'params.stcList': stcList
      })
    }
    
  },

  //关联标签
  _selectTab(e){
    console.log(e)
    this.setData({
      'params.tagsId': e.detail.id,
      tabName: e.detail.name
    })
  },

  // 标签选择
  selectTab(){
    this.setData({
      showSelectTabModal: true
    })
  },


  //多张图片上传
  moreImgUpload(data) {
    var that = this,
      i = data.i ? data.i : 0,//当前上传的哪张图片
      success = data.success ? data.success : 0,//上传成功的个数
      fail = data.fail ? data.fail : 0;//上传失败的个数
      wx.uploadFile({
        url: data.url,
        filePath: data.path[i],
        header : {
          'buyer-token' : wx.getStorageSync('token')
        },
        name: 'imgs',//这里根据自己的实际情况改
        formData: null,//这里是上传图片时一起上传的数据
        success: (res) => {
          if (res.statusCode == 200){
            var imgdata = JSON.parse(res.data);
            var img = imgdata.data[0];
            success++;//图片上传成功，图片上传成功的变量+1
            this.data.params.sspList.push({
              cover: 0,
              url: envInfo.imgCtx + img.url
            });
            that.setData({
              'params.sspList': this.data.params.sspList
            })
          }
        },
        fail: (res) => {
          fail++;//图片上传失败，图片上传失败的变量+1
        },
        complete: (res) => {
          i++;
          if (i == data.path.length) { //当图片传完时，停止调用  

          }else {//若图片还没有传完，则继续调用函数                
            console.log('00000',i);
            data.i = i;
            data.success = success;
            data.fail = fail;
            that.moreImgUpload(data);
          }
        }
      })
  },
  
  // 删除图片
  deleteImage(event) {
    var pics = this.data.pics
    pics.splice(event.currentTarget.dataset.index, 1)
    this.setData({
      pics: pics
    })
    var sspList = this.data.params.sspList
    for (var i in sspList) {
      if (sspList[i].url) {
        sspList.splice(i, 1)
      }
    }
    this.setData({
      'params.sspList': sspList
    })
  },

  // 上传视频
  _uploadVideo(e){
    this.data.params.sspList.push({
      cover: 0,
      videoUrl: e.detail
    });
    this.setData({
      'params.sspList': this.data.params.sspList
    })
  },

  // 删除视频
  _deleteVideo(e){
    var sspList = this.data.params.sspList
    for (var i in sspList){
      if (sspList[i].videoUrl){
        console.log(i)
        sspList.splice(i,1)
      }
    }
    this.setData({
      'params.sspList': sspList
    })
   
  },

  // 发布笔记
  formSubmit(e){
    if (this.data.requesting){
      return;
    } 
    if (!this.data.params.sspList || this.data.params.sspList.length < 1) {
      wx.showToast({
        title: '请上传至少一张图片',
        icon: 'none'
      })
      return;
    }
    if (this.data.params.sspList && this.data.params.sspList[0].videoUrl && !this.data.params.sspList[1]) {
      wx.showToast({
        title: '请上传至少一张图片',
        icon: 'none'
      })
      return;
    }
    if (!e.detail.value.headline){
      wx.showToast({
        title: '请添加标题',
        icon: 'none'
      })
      return;
    }
    const { memberId } = wx.getStorageSync('_baseUserInfo')

    this.setData({
      'params.headline': e.detail.value.headline,
      'params.article': e.detail.value.article,
      'params.userId': memberId
    })
    this.data.params.sspList.forEach((item,index) => {
      if (index == 0){
        item.cover = 1;
      }
    });
    this.setData({
      requesting: true
    })

    wxService.post(`/merchant/contentMobileTerminal/contentSave`, this.data.params).then(res => {
      const { result, data } = res.data
      if (result == 0) {
        this.setData({
          requesting: false
        })
        wxService.router('/subPackage/page/pages/myRelease/myRelease')
      }
    }).finally(() => {
      this.setData({
        requesting: false
      })
    })
  }

})