// pages/mine/product/productmanage/productmanage.js
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    goodsId: '',
    goodsBean: null,
    shopId: '',
    cataLogId: '', //上级页面传递
    goodsName: '', //商品名称
    goodsCount: 0, //商品数量
    goodsPrice: 0.00, //商品单价
    goodsUnit: '', //商品单位
    goodsStatus: 1, //商品状态  1 上架  2 下架
    goodsPay: 1, //支付方式  1 线上  2 线下
    goodsLogoPhotos: [], //商品Logo
    goodsPhotos: [], //商品图片
    goodsVideos: [], //商品视频
    goodsSummary: '', //商品说明
    goodsOrder: 0, //商品排序
    isPopular: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      goodsId: options.shopGoodsId
    })
    this.getGoodsDetail(this.data.goodsId)
  },
  getGoodsDetail(id) {
    wx.showLoading({
      title: '加载中...',
    })
    app.http.get(app.urls.getGoodsDetail.format({
        goodsId: id
      }), {
        header: {
          token: app.globalData.token
        }
      })
      .then(res => {
        wx.hideLoading({})
        if (code == 200) {
          this.setDataToView(res.data)
        }
      })
      .catch(err => {
        wx.hideLoading({})
      })
  },
  selGoodsPopular(e) {
    console.log(e)
    this.setData({
      isPopular: e.detail.value
    })
  },
  setDataToView(data) {
    let _self = this
    if (data.goodsPhotos != '') {
      let ids = data.goodsPhotos
      let idsList = ids.split(',')
      idsList.forEach(el => {
        if (el != '') {
          _self.data.goodsPhotos.push({
            id: el,
            path: app.tradeUrl + app.baseImgUrl + el
          })
        }
      })
      _self.setData({
        goodsPhotos: _self.data.goodsPhotos
      })
    }

    if (data.goodsIcon != '') {
      let ids = data.goodsIcon
      _self.data.goodsLogoPhotos.push({
        id: ids,
        path: app.tradeUrl + app.baseImgUrl + ids
      })
      _self.setData({
        goodsLogoPhotos: _self.data.goodsLogoPhotos
      })
    }

    if (data.goodsVideo != '') {
      let ids = data.goodsVideo
      let idsList = ids.split(',')
      idsList.forEach(el => {
        if (el != '') {
          _self.data.goodsVideos.push({
            id: el,
            videoUrl: app.tradeUrl + app.baseImgUrl + el,
            path: '../../../../images/ic_video_default.png',
          })
        }
      })
      _self.setData({
        goodsVideos: _self.data.goodsVideos
      })
    }
    this.setData({
      goodsBean: data,
      shopId: data.shopId,
      cataLogId: data.cataLogId, //上级页面传递
      goodsName: data.goodsName, //商品名称
      goodsCount: data.goodsTotal, //商品数量
      goodsPrice: data.goodsUnitPrice, //商品单价
      goodsUnit: data.goodsUnit, //商品单位
      goodsStatus: data.goodsStatus, //商品状态  1 上架  2 下架
      goodsPay: data.paymentType, //支付方式  1 线上  2 线下
      goodsSummary: data.goodsSummary, //商品说明
      goodsOrder: data.goodsSort, //商品排序
      isPopular: data.isPopular == '0' ? false : true
    })
  },
  //商品状态切换
  selGoodsStatus(e) {
    this.setData({
      goodsStatus: e.detail.value
    })
  },
  //支付方式切换
  selGoodsPay(e) {
    this.setData({
      goodsPay: e.detail.value
    })
  },
  //输入框监听
  inputWatch(e) {
    let key = e.currentTarget.dataset.model
    this.setData({
      [key]: e.detail.value
    })
  },
  //商品说明
  goodsSummaryInput(e) {
    this.setData({
      goodsSummary: e.detail.value
    })
  },
  /**
   * 添加图片、视频  1 logo   2 图片  
   */
  chooseLogo() {
    let _self = this
    wx.chooseImage({
      count: 1, //默认9
      sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], //从相册选择
      success: (res) => {
        res.tempFilePaths.forEach(element => {
          _self.doUploadImg(1, element)
        });
      }
    });
  },
  choosePhoto() {
    let _self = this
    wx.chooseImage({
      count: 1, //默认9
      sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], //从相册选择
      success: (res) => {
        res.tempFilePaths.forEach(element => {
          _self.doUploadImg(2, element)
        });
      }
    });
  },
  chooseVideo() {
    let _self = this
    wx.chooseMedia({
      count: 1,
      mediaType: ['video'],
      sourceType: ['album', 'camera'], //从相册选择
      maxDuration: 30,
      success: (res) => {
        _self.doUploadVideo(res)
      }
    });
  },
  /**
   * 删除图片、视频
   */
  delLogo(e) {
    let _self = this
    wx.showModal({
      title: '提示',
      content: '确定要删除该图片吗？',
      cancelText: '取消',
      confirmText: '确定',
      success: res => {
        if (res.confirm) {
          _self.data.goodsLogoPhotos.splice(e.currentTarget.dataset.index, 1)
          _self.setData({
            goodsLogoPhotos: _self.data.goodsLogoPhotos
          })
        }
      }
    })
  },
  delPhoto(e) {
    let _self = this
    wx.showModal({
      title: '提示',
      content: '确定要删除该图片吗？',
      cancelText: '取消',
      confirmText: '确定',
      success: res => {
        if (res.confirm) {
          _self.data.goodsPhotos.splice(e.currentTarget.dataset.index, 1)
          _self.setData({
            goodsPhotos: _self.data.goodsPhotos
          })
        }
      }
    })
  },
  delVideo(e) {
    let _self = this
    wx.showModal({
      title: '提示',
      content: '确定要删除该视频吗？',
      cancelText: '取消',
      confirmText: '确定',
      success: res => {
        if (res.confirm) {
          _self.data.goodsVideos.splice(e.currentTarget.dataset.index, 1)
          _self.setData({
            goodsVideos: _self.data.goodsVideos
          })
        }
      }
    })
  },
  /**
   * 预览图片、视频
   */
  viewLogo(e) {
    var tempList = [e.currentTarget.dataset.url]
    wx.previewImage({
      urls: tempList,
      current: e.currentTarget.dataset.url
    });
  },
  viewPhoto(e) {
    var tempList = [e.currentTarget.dataset.url]
    wx.previewImage({
      urls: tempList,
      current: e.currentTarget.dataset.url
    });
  },
  viewVideo(e) {
    var tempList = [{
      url: e.currentTarget.dataset.url,
      type: 'video'
    }]
    wx.previewMedia({
      sources: tempList,
      current: 0,
      showmenu: false
    })
  },
  //上传图片
  //进行图片上传 type 1 营业执照   2 logo
  doUploadImg(type, path) {
    wx.showLoading({
      title: '上传中...',
    })
    let _self = this
    app.http.upload(app.urls.doUploadImg, {
        name: 'image',
        path: path,
        header: {
          token: app.globalData.token
        }
      })
      .then(res => {
        wx.hideLoading({})
        var id = JSON.parse(res).data
        let pathStr = app.urls.baseImgUrl + id
        let item = {
          id: id,
          path: pathStr
        }
        if (type == 1) {
          let tempList = _self.data.goodsLogoPhotos.concat(item)
          _self.setData({
            goodsLogoPhotos: tempList
          })
        } else {
          //图片
          let tempList = _self.data.goodsPhotos.concat(item)
          _self.setData({
            goodsPhotos: tempList
          })
        }
      })
      .catch(err => {
        wx.hideLoading({})
      })
  },
  doUploadVideo(e) {
    wx.showLoading({
      title: '上传中...',
    })
    let _self = this
    app.http.upload(app.urls.doUploadVideo, {
        name: 'video',
        path: e.tempFiles[0].tempFilePath,
        header: {
          token: app.globalData.token
        }
      })
      .then(res => {
        wx.hideLoading({})
        var id = JSON.parse(res).data
        let pathStr = e.tempFiles[0].thumbTempFilePath
        let videoU = app.urls.baseImgUrl + id
        let item = {
          id: id,
          path: pathStr,
          videoUrl: videoU
        }
        let tempList = _self.data.goodsVideos.concat(item)
        _self.setData({
          goodsVideos: tempList
        })
      })
      .catch(err => {
        wx.hideLoading({})
      })
  },
  //修改
  doUpdate() {
    if (this.checkParams()) {
      let _self = this
      wx.showLoading({
        title: '更新中...',
      })
      let p = ''
      _self.data.goodsPhotos.forEach(el => {
        p += el.id + ','
      })
      if (p.length != '') {
        p = p.substr(0, p.length - 1)
      }
      let videoId = ''
      if (_self.data.goodsVideos.length > 0) {
        videoId = _self.data.goodsVideos[0].id
      }
      app.http.put(app.urls.doUpdateGoods.format({
          shopGoodsId: _self.data.goodsId
        }), {
          header: {
            token: app.globalData.token
          },
          data: {
            categoryId: _self.data.cataLogId,
            goodsIcon: _self.data.goodsLogoPhotos[0].id,
            goodsName: _self.data.goodsName,
            goodsPhotos: p,
            goodsSort: _self.data.goodsOrder,
            goodsStatus: _self.data.goodsStatus,
            goodsSummary: _self.data.goodsSummary,
            goodsTotal: _self.data.goodsCount,
            goodsUnit: _self.data.goodsUnit,
            goodsUnitPrice: _self.data.goodsPrice,
            goodsVideo: videoId,
            paymentType: _self.data.goodsPay,
            shopId: _self.data.shopId,
            isPopular: _self.data.isPopular ? 1 : 0
          }
        })
        .then(res => {
          wx.hideLoading({})
          if (code == 200) {
            wx.showToast({
              title: '更新成功',
              icon: 'success'
            })
            var pages = getCurrentPages(); //当前页面
            var beforePage = pages[pages.length - 2]; //前一页
            beforePage.setData({
              isAddPage: true
            })
            wx.navigateBack({})
          }
        })
        .catch(err => {
          wx.hideLoading({})
        })
    }
  },
  doDelGoods() {
    let _self = this
    wx.showModal({
      title: '提示',
      content: '确定要删除该商品吗?',
      success(res) {
        if (res.confirm) {
          wx.showLoading({
            title: '删除中...',
          })
          app.http.delete(app.urls.doDelGoods.format({
              ids: _self.data.goodsId
            }), {
              header: {
                token: app.globalData.token
              }
            })
            .then(res => {
              wx.hideLoading({})
              if (code == 200) {
                wx.showToast({
                  title: '删除成功',
                  icon: 'success'
                })
                var pages = getCurrentPages(); //当前页面
                var beforePage = pages[pages.length - 2]; //前一页
                beforePage.setData({
                  isAddPage: true
                })
                wx.navigateBack({})
              }
            })
            .catch(err => {
              wx.hideLoading({})
            })
        }
      }
    })
  },
  //校验参数合法性
  checkParams() {
    if (this.data.goodsName == '') {
      wx.showToast({
        title: '请输入商品名称',
        icon: 'error'
      })
      return false
    }
    if (this.data.goodsCount == 0) {
      wx.showToast({
        title: '请输入商品数量',
        icon: 'error'
      })
      return false
    }

    if (this.data.goodsCount == 0) {
      wx.showToast({
        title: '请输入商品数量',
        icon: 'error'
      })
      return false
    }
    if (this.data.goodsUnit == '') {
      wx.showToast({
        title: '请输入商品单位',
        icon: 'error'
      })
      return false
    }
    if (this.data.goodsLogoPhotos.length <= 0) {
      wx.showToast({
        title: '请上传商品Logo',
        icon: 'error'
      })
      return false
    }
    if (this.data.goodsPhotos.length <= 0) {
      wx.showToast({
        title: '请上传商品图片',
        icon: 'error'
      })
      return false
    }
    return true
  }
})