// packageC/video_goods/releaseVideo/releaseVideo.js
var app = getApp();
const GoodsByidUrl = "plugin.store-alone-temp.frontend.videoShare.goods.getGoodsById";
const subTapUrl = "plugin.store-alone-temp.frontend.videoShare.video.sub";
Page({

  /**
   * 页面的初始数据
   */
  data: {
    language: '',
    myvideo: '',
    goods_id: '',
    title: "",
    videoUrl: "",
    isVideo: true,
    realVideo: "",
    coverUrl: "",
    duration: 0, //视频时长
    chooseGoods: null, //商品信息
    videoPath: "", //视频链接参数
    videoCover: "", //封面图片参数
    limit: 60, //视频限制时长
    uploadIng: false, //正在上传中
    videoProgress: 0,
    showUploadBtn: false, //是否显示确认上传按钮引导用户上传（解决ios无法自动播放）
    imguploadIng: false,
    isNeedGoods: true, //是否开启选择商品

    categoryList: [],
    categoryFilterList: [],
    category_id: null,
    category_name: "",
    showCategory: false,
    searchWord: "",
    is_show_cate: false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.data.myvideo = wx.createVideoContext('myvideo');
    this.init();
    this.getList();
    this.getPermission();
    try {
      var value = wx.getStorageSync('shareVideoPath');
      if (value) {
        let shareVideoPath = JSON.parse(value);
        if (shareVideoPath.title) {
          this.setData({
            title: shareVideoPath.title
          });
        }
        if (shareVideoPath.videoUrl) {
          this.setData({
            videoUrl: shareVideoPath.videoUrl
          });
        }
        if (shareVideoPath.videoUrl) {
          this.setData({
            videoUrl: shareVideoPath.videoUrl,
            videoPath: shareVideoPath.videoUrl
          });
        }
        if (shareVideoPath.videoCover) {
          this.setData({
            videoCover: shareVideoPath.videoCover
          });
        }
        if (shareVideoPath.category_id) {
          this.setData({
            category_id: shareVideoPath.category_id
          });
        }
        if (shareVideoPath.category_name) {
          this.setData({
            category_name: shareVideoPath.category_name
          });
        }
      }
    } catch (e) {
      // Do something when catch error
    }
    if (options.goods_id) {
      this.setData({
        goods_id: options.goods_id
      });
      this.getGoodsById();
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    let language = wx.getStorageSync('langIndex');
    this.setData({
      'language': language.en
    });
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

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

  },

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

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  init() {
    this.setData({
      title: '',
      videoUrl: '',
      isVideo: true,
      duration: 0,
      chooseGoods: null,
      videoCover: '',
      limit: '',
      uploadIng: false,
      showUploadBtn: false,
      coverUrl: '',
      realVideo: '',
      videoPath: '',
      isNeedGoods: true
    });
  },
  getList() {
    //获取限制时长
    let urlStr = app.getNetAddresss("plugin.video-share.frontend.set.getLimit");
    app._getNetWork({
      url: urlStr,
      data: {
        validate_page: 1
      }, // validate_page 实名认证判断
      success: (resdata) => {
        var res = resdata.data;
        if (res.result == 1) {
          this.setData({
            is_show_cate: res.data.is_show_cate == "1" ? true : false,
            isNeedGoods: res.data.select_goods == 1 ? true : false
          });
          if (!app._isTextEmpty(res.data.limit)) {
            this.setData({
              limit: res.data.limit
            });
          }
        } else {
          wx.showToast({
            title: res.msg,
            icon: 'none',
            duration: 1500
          });
        }
      },
      fail: function (res) {
        console.log(res);
      }
    });
  },
  //验证会员发布权限
  getPermission() {
    let urlStr = app.getNetAddresss("plugin.video-share.frontend.permission.verify");
    app._getNetWork({
      url: urlStr,
      data: {},
      success: function (resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          if (!res.data.ret) {
            wx.navigateBack({
              delta: 1,
              success: function () {
                setTimeout(() => {
                  wx.showToast({
                    title: res.msg,
                    icon: 'none',
                    duration: 1500
                  });
                }, 1000);
              }
            });

          }
        } else {
          wx.showToast({
            title: res.msg,
            icon: 'none',
            duration: 1500
          });
        }
      },
      fail: function (res) {
        console.log(res);
      }
    });
  },
  getGoodsById() {
    let that = this;
    let urlStr = app.getNetAddresss(app.globalData.store_alone_temp == 1?GoodsByidUrl:"plugin.video-share.frontend.goods.getGoodsById");
    app._getNetWork({
      url: urlStr,
      data: {
        goods_id: this.data.goods_id
      },
      success: function (resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          that.setData({
            chooseGoods: res.data.goods
          });
        } else {
          wx.showToast({
            title: res.msg,
            icon: 'none',
            duration: 1500
          });
        }
      },
      fail: function (res) {
        console.log(res);
      }
    });
  },
  onReadVideo() {
    let that = this;
    //iOS中选择上传视频不能超过60秒
    // wx.chooseVideo({
    //   sourceType: ['album', 'camera'],
    //   maxDuration: 60,
    //   camera: 'back',
    //   compressed:false,
    //   success(res) {
    //     that.getDuration(res.duration, res.tempFilePath);
    //     that.setData({
    //       videoUrl: res.tempFilePath
    //     });
    //   }
    // });
    // wx.chooseVideo 获取不到视频缩略图
    wx.chooseMedia({
      count: 1,
      mediaType: ['video'],
      sourceType: ['album', 'camera'],
      maxDuration: 60,
      success(res) {
        that.getDuration(res.tempFiles[0].duration, res.tempFiles[0].tempFilePath);
        that.data.coverUrl = res.tempFiles[0].thumbTempFilePath;
        that.uploadImageM(); //上传封面 -----------------
        that.setData({
          videoUrl: res.tempFiles[0].tempFilePath
        });
      }
    })
  },
  getDuration(durationData, videoData) {
    let duration = durationData;
    //获取视频或者音频时长
    let that = this;
    that.data.duration = duration;
    if (that.data.duration < 1) {
      that.setData({
        videoUrl: null
      });
      wx.showToast({
        title: '视频时长太短了！',
        icon: 'none',
        duration: 1500
      });
      return;
    } else if (that.data.limit && that.data.duration > Number(that.data.limit) + 1) {
      that.setData({
        videoUrl: null
      });
      wx.showToast({
        title: `视频时长不能超过${that.data.limit}秒`,
        icon: 'none',
        duration: 1500
      });
      return;
    } else {
      that.setSrcAndCaptureImage(videoData);
      return;
    }
  },
  setSrcAndCaptureImage(videoData) {
    this.data.realVideo = videoData;
    if (this.data.realVideo) {
      this.setData({
        videoUrl: null
      });
    }
    this.uploadAudioM(); //上传视频 --------------
  },
  uploadAudioM() {
    let that = this;
    //视频上传
    that.setData({
      uploadIng: true
    });
    let wx_token = wx.getStorageSync('wx_token');
    let session = wx.getStorageSync('session');
    let urlStr = app.getNetAddresss("plugin.video-share.frontend.upload.uploadAudio");
    urlStr += '&3rd_session=' + session;
    wx.uploadFile({
      url: urlStr, //仅为示例，非真实的接口地址
      filePath: this.data.realVideo,
      name: 'file',
      formData: {},
      header: {
        "Content-Type": "application/json",
        Accept: "application/json",
        Cookie: "PHPSESSID=" + wx_token,
      },
      success(res) {
        var resData = JSON.parse(res.data);
        if (resData.result == 1) {
          that.data.videoPath = resData.data.audio;
          that.data.file_name = resData.data.file_name;
          that.setData({
            uploadIng: false,
            videoPath: resData.data.audio,
            file_name: resData.data.file_name
          });
          //本地保存标题、视频链接--------------
          let hasData = {
            title: (that.data.title ? that.data.title : ''),
            videoUrl: (that.data.videoPath ? that.data.videoPath : ''),
            videoCover: (that.data.videoCover ? that.data.videoCover : ''),
            file_name: (that.data.file_name ? that.data.file_name : '')
          };
          try {
            wx.setStorageSync('shareVideoPath', JSON.stringify(hasData));
          } catch (e) {
            console.log(e);
          }
        } else {
          that.setData({
            videoUrl: null,
            isVideo: true,
            duration: 0,
            videoCover: '',
            limit: '',
            uploadIng: false,
            showUploadBtn: false
          });
          wx.showToast({
            title: resData.msg,
            icon: 'none',
            duration: 2500
          });
        }
      }
    });
  },
  uploadImageM() {
    //图片上传
    let that = this;
    that.setData({
      imguploadIng: true
    });
    let urlStr = app.getNetAddresss("upload.uploadPic");
    wx.uploadFile({
      url: urlStr, //仅为示例，非真实的接口地址
      filePath: this.data.coverUrl,
      name: 'file',
      formData: {},
      success(res) {
        var resData = JSON.parse(res.data);
        if (resData.result == 1) {
          that.setData({
            videoCover: resData.data.img_url
          });
          //本地保存标题、视频链接--------------
          let hasData = {
            title: (that.data.title ? that.data.title : ''),
            videoUrl: (that.data.videoPath ? that.data.videoPath : ''),
            videoCover: (that.data.videoCover ? that.data.videoCover : '')
          };
          try {
            wx.setStorageSync('shareVideoPath', JSON.stringify(hasData));
          } catch (e) {
            console.log(e);
          }
          that.setData({
            imguploadIng: false
          });
        } else {
          that.setData({
            imguploadIng: false
          });
          wx.showToast({
            title: resData.msg,
            icon: 'none',
            duration: 1500
          });
        }
      }
    });
  },
  BtnMethos() {
    let that = this;
    if (this.data.isNeedGoods && app._isTextEmpty(this.data.chooseGoods)) {
      //商品为空，则跳转到商品搜索页添加商品
      //本地保存标题、视频链接--------------
      let hasData = {
        title: (that.data.title ? that.data.title : ''),
        videoUrl: (that.data.videoPath ? that.data.videoPath : ''),
        videoCover: (that.data.videoCover ? that.data.videoCover : ''),
        file_name: (that.data.file_name ? that.data.file_name : ''),
        category_id: (that.data.category_id ? that.data.category_id : ''),
        category_name: (that.data.category_name ? that.data.category_name : '')
      };
      try {
        wx.setStorageSync('shareVideoPath', JSON.stringify(hasData));
      } catch (e) {
        console.log(e);
      }
      wx.navigateTo({
        url: '/packageC/video_goods/addVideoGood/addVideoGood'
      });
    } else {
      //商品不为空，而且视频、标题已添加，则进行发布
      if (app._isTextEmpty(this.data.title)) {
        wx.showToast({
          title: "请输入4-18个字标题",
          icon: 'none',
          duration: 1500
        });
        return;
      }
      if (app._isTextEmpty(this.data.videoUrl)) {
        wx.showToast({
          title: "请选择视频进行上传！",
          icon: 'none',
          duration: 1500
        });
        return;
      }
      if (app._isTextEmpty(this.data.videoCover)) {
        wx.showToast({
          title: "请选择一张图片作为视频封面图！",
          icon: 'none',
          duration: 1500
        });
        return;
      }
      let file = wx.getStorageSync('shareVideoPath');
      file = JSON.parse(file);
      let json = {
        goods_id: this.data.goods_id,
        title: this.data.title,
        video: this.data.videoPath,
        cover: this.data.videoCover,
        file_name: this.data.file_name ? this.data.file_name : file.file_name
      };

      if (this.data.is_show_cate) {
        json.category_id = this.data.category_id || 0;
      }

      let urlStr = app.getNetAddresss(app.globalData.store_alone_temp == 1?subTapUrl:"plugin.video-share.frontend.video.sub");
      app._postNetWork({
        url: urlStr,
        data: json,
        success: (resdata) => {
          var res = resdata.data;
          if (res.result == 1) {
            wx.showToast({
              icon: 'none',
              title: res.msg,
              duration: 1500
            });
            try {
              wx.removeStorageSync('shareVideoPath');
            } catch (e) {
              // Do something when catch error
            }
            wx.navigateTo({
              url: '/packageC/video_goods/VideoList/VideoList'
            });
          } else {
            wx.showToast({
              icon: 'none',
              title: res.msg,
              duration: 1500
            });
          }
        },
        fail: function (res) {
          console.log(res.msg);
        }
      });
    }
  },
  titleBlur(event) {
    let val = event.detail.value;
    if (val.length < 4) {
      wx.showToast({
        icon: 'none',
        title: '请输入不小于4个字',
        duration: 1500
      });
      return;
    }
    this.setData({
      title: val
    });
  },
  gotoAdd() {
    wx.navigateTo({
      url: '/packageC/video_goods/addVideoGood/addVideoGood'
    });
  },
  onReadimge() {
    let that = this;
    if (that.data.imguploadIng) {
      wx.showToast({
        icon: 'none',
        title: '图片正在上传请勿点击',
        duration: 1500
      });
    }
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success(res) {
        const tempFilePaths = res.tempFilePaths;
        that.data.coverUrl = tempFilePaths[0];
        that.uploadImageM(); //上传封面 -----------------
      }
    });
  },
  getCategory() {
    if (this.data.categoryList.length > 0) {
      this.setData({
        showCategory: true
      });
      return;
    }

    let that = this;
    let urlStr = app.getNetAddresss("plugin.video-share.frontend.video.getCategory");
    app._getNetWork({
      url: urlStr,
      data: {},
      success: function (resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          that.setData({
            categoryList: res.data,
            categoryFilterList: res.data,
            showCategory: true
          });
        } else {
          wx.showToast({
            title: res.msg,
            icon: 'none',
            duration: 1500
          });
        }
      },
      fail: function (res) {
        console.log(res);
      }
    });
  },
  onFilterCategory(e) {
    if (e.type == 'change') {
      this.setData({
        searchWord: e.detail
      });
    }

    if (this.data.searchWord == "") {
      this.setData({
        categoryFilterList: this.data.categoryList
      });
      return;
    }
    if (this.data.categoryList.find(obj => obj.name == this.data.searchWord)) {
      let arr = new Array(this.data.categoryList.find(obj => obj.name == this.data.searchWord));
      this.setData({
        categoryFilterList: arr
      });
      return;
    } else {
      this.setData({
        categoryFilterList: this.data.categoryList
      });
      return;
    }
  },
  onClickCategory(e) {
    console.log(e.currentTarget.dataset);
    this.setData({
      category_id: e.currentTarget.dataset.id,
      category_name: e.currentTarget.dataset.name,
      showCategory: false
    });
  },
  onClose() {
    this.setData({
      showCategory: false
    });
  },
  removeImg(e) {
    let _tag = e.currentTarget.dataset.tag
    if (_tag == "img") {
      this.setData({
        videoCover: null,
        images: []
      })
    } else if (_tag == "video") {
      this.setData({
        videoUrl: null,
        videoPath: null
      })
    }
  },
});