// myComponents/product/product.js
const app = getApp()
const api = require('../../api/index')
Component({

  /**
   * 组件的属性列表
   */
  properties: {
    tableData:{
      type:Array,
      value:[],
      observers:function(val){
        // console.log(val)
      }
    },
    total:{
      type:Number,
      value:null
    },
    loading:{
      type:Boolean,
      value:false
    },
    isFollow:{
      type:Boolean,
      value:false
    },
    isMonitor:{
      type:Boolean,
      value:false
    },
    menu:{
      type:Array,
      value:[]
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    imgHttp:app.globalData.imghttp,
    concernType:{
      '0':'myIcongroup43',//黑
      '1':'myIconanquanbangzhu',//白
      '2':'myIconicon-test',//灰
      '-1':'myIconguanzhu-yiguanzhu'//已关注
    },
    show:false,
    clickType:null,//1是关注，2是监控
    index:null,
  },

  /**
   * 组件的方法列表
   */
  methods: {

    moreMenu: function (e) {
      
      var {index} = e.currentTarget.dataset
      var dom = this.selectComponent('#myPopover'+index)
      dom.showMenu()
    },

    // 响应popover组件中的子元素点击事件
    onClickA: function (e) {
      const {item,index} = e.currentTarget.dataset
      console.log(item,index)
      if(item.method == 'selectCollectPatent'){
        this[item.method](index)
      }else{
        var data = {
          method:item.method,
          params:{
            index:index
          }
        }
        this.triggerEvent('click',data)
      }
      
      var dom = this.selectComponent('#myPopover'+index)
      dom.showMenu()
    },
    //查询已收藏的专利
    selectCollectPatent(index){
      var product = this.data.tableData[index]
      wx.navigateTo({
        url: '/pages/collectPatent/collectPatent?productId='+product.assoId,
      })
    },
    //查看图片
    previewImage(e) {
      const { current,imglist } = e.currentTarget.dataset
      var imgs = []
      for(var i =0;i<imglist.length;i++){
        imgs.push(this.data.imgHttp + imglist[i].guid)
      }
      current = this.data.imgHttp + current
      wx.previewImage({
        current,
        urls:imgs,
      })
    },
    //打开关注类型
    open(e){
      var key = api.isLogin()
      if(!key){
        return false
      }
      var index = e.currentTarget.dataset.index
      this.setData({
        // ['tableData['+ index + '].show'] : true,
        index:index,
        clickType:1
      })
      this.triggerEvent('showPopup')
    },
    closeDialog(){
      this.setData({
        index:null,
        clickType:null
      })

      this.triggerEvent('hiddenPopup')
    },
    //关闭关注类型
    // cancel(e){
    //   var index = e.currentTarget.dataset.index
    //   this.setData({
    //     ['tableData['+ index + '].show'] : false,
    //     clickType:null
    //   })
    // },
    //关注或监控
    attention(e){
      // var {type,index} = e.currentTarget.dataset
      var {type} = e.detail
      var index = this.data.index
      var product = this.data.tableData[index]
      var params = {
        productId:product.id,
        concernType:type
      }
      if(this.data.clickType == 2){
        this.addMonitoring(params,index,type)
        return 
      }
      wx.showLoading({
        title: '加载中',
      })
      api.follow(params).then(res=>{
        if(res.code == 200){
          var obj = {
            type: 'success', 
            message: '关注成功',
          }
          if(this.properties.isFollow){
            obj.top = wx.getStorageSync('height')
          }
          api.notify(obj)
          this.setData({
            // ['tableData['+ index + '].show'] : false,
            ['tableData['+ index + '].concernType'] : type,
          })
          this.closeDialog()
        }
      })
    },

    //打开弹窗
    cancel(e){
      var key = api.isLogin()
      if(!key){
        return false
      }
      var index = e.currentTarget.dataset.index
      this.setData(
        {
          index:index,
          clickType:1
        }
      )
      this.triggerEvent('showPopup',
      {
        changeFollow:true
      })
    },
    //取消关注
    cancelFollow(e){
      var key = api.isLogin()
      if(!key){
        return false
      }
      wx.showModal({
        title: '提示',
        content: '取消关注后会取消该产品的监控，确认取消关注？',
        complete: (res) => {
          if (res.cancel) {}
          if (res.confirm) {
            // var index = e.currentTarget.dataset.index
            var index =this.data.index
            console.log(index)
            var product = this.data.tableData[index]
            var params = {
              productId:product.id
            }
            this.closeDialog()
            api.unFollow(params).then(res=>{
              if(res.code == 200){
                var obj = {
                  type: 'success', 
                  message: '取关成功',
                }
                if(this.properties.isFollow){
                  obj.top = wx.getStorageSync('height')
                  this.triggerEvent('cancelFollow',index)
                }
                api.notify(obj)
                this.setData({
                  ['tableData['+ index + '].concernType'] : null,
                  ['tableData['+ index + '].ifMonitor'] : false
                })
              }
            })
          }
        }
      })
      
    },
    //监控
    control(e){
      var key = api.isLogin()
      if(!key){
        return false
      }
      var index = e.currentTarget.dataset.index
      var product = this.data.tableData[index]
      if(product.concernType == 0 || product.concernType){
        wx.showModal({
          title: '提示',
          content: '是否确定监控该产品？',
          complete: (res) => {
            if (res.cancel) {}
            if (res.confirm) {
              var params = {
                productId:product.id
              }
              this.addMonitoring(params,index)
            }
          }
        })
        return
      }
      this.setData({
        // ['tableData['+ index + '].show'] : true,
        index:index,
        clickType:2
      })
      this.triggerEvent('showPopup')
    },
    //监控产品接口
    addMonitoring(product,index,type){
      wx.showLoading({
        title: '加载中',
      })
      api.addMonitoring(product).then(res=>{
        var obj = {
          type: 'success', 
          message: '监控成功',
        }
        if(this.properties.isFollow){
          obj.top = wx.getStorageSync('height')
        }
        api.notify(obj)
        this.setData({
          // ['tableData['+ index + '].show'] : false,
          ['tableData['+ index + '].ifMonitor'] : true,
        })
        if(type == 0 || type){
          this.setData({
            ['tableData['+ index + '].concernType'] : type,
          })
        }
        this.closeDialog()
      })
    },
    //取消监控产品接口
    cancelMonitoring(params,index,type){
      wx.showLoading({
        title: '取消中',
      })
      api.cancelMonitoring(params).then(res=>{
        if(res.code == 200){
          var obj = {
            type: 'success', 
            message: '取消监控成功',
          }
          if(this.properties.isFollow){
            obj.top = wx.getStorageSync('height')
          }
          api.notify(obj)
          this.setData(
            {
              ["tableData["+ index +"].ifMonitor"]:false
            }
          )
          if(type == 1){
            this.setData(
              {
                ["tableData["+ index +"].concernType"]:null
              }
            )
          }
          this.triggerEvent('cancelMonitoring',index)
        }
      })
    },
    cancelControl(e){
      var {index} = e.currentTarget.dataset
      var product = this.data.tableData[index]
      var params = {
        productIds:[product.id],
        ifCancelConcern:false
      }
      var that = this
      wx.showActionSheet({
        itemList: ['只取消监控', '取消监控和关注', '关闭'],
        success (res) {
          console.log(res.tapIndex)
          switch(res.tapIndex){
            case 0:
              that.cancelMonitoring(params,index,0)
              break;
            case 1:
              params.ifCancelConcern = true
              that.cancelMonitoring(params,index,1)
              break;
            case 2:
              break
          }
        },
        fail (res) {
          console.log(res.errMsg)
        }
      })
    
    },
    //加载更多
    loadMore(){
      this.triggerEvent('loadMore')
    },
    //查看爆款产品专利
    checkMessage(e){
      var key = api.isLogin()
      if(!key){
        return false
      }
      var data = e.currentTarget.dataset.item
      var product = '{}'
      if(data){
        product = JSON.stringify(data)
      }
      var type = 1
      wx.navigateTo({
        url: '/pages/searchResults/searchResults?type='+type+'&product='+encodeURIComponent(product),
      })
    },
  },
   /**  
   * 组件的生命周期函数列表  
   */  
  lifetimes: {  
    // 在组件实例进入页面节点树时执行  
    attached: function () {  
      // 初始化操作  
     
      // ...  
    },  
    // 在组件实例被移除出页面节点树时执行  
    detached: function () {  
      // 清理工作  
      console.log('组件销毁');  
      // ...  
    },  
    // ...  
  },  
})