// pages/searchResults/searchResults.js
const app = getApp()
const api = require('../../api/index')
const showImage = require('../../utils/showImage')
const downLoad = require('../../utils/downLoad')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    imgHttp:app.globalData.imghttp,
    phone:app.globalData.phone,
    queryParams:{
      current:1,
      size:10
    },
    ifAddSearchRecord:true,
    total:0,
    loading:false,
    tableData:[],
    keyword:'',
    searchType:1,//检索类型1是爆款产品0是手动检索
    product:{},//产品信息
    patentNoList:[],
    patentList:[],
    buttons:[
      {
        label: '付费解读',
        method:'check',
        icon:'/static/image/工单.png'
      },
      {
        label: '一键导出',
        method:'export',
        icon:'/static/image/导出.png'
      },
      {
        label:'人工客服',
        method:'makePhoneCall',
        icon:'/static/image/人工客服.png'
      }
    ],
    concernType:{
      '0':'myIcongroup43 ',//黑
      '1':'myIconanquanbangzhu',//白
      '2':'myIconicon-test',//灰
      '-1':'myIconguanzhu-yiguanzhu'//已关注
    },
    showDialog:false,
    showDialog2:false,
    followType:null,
    isAdd:false,
    triggered:false,
    load:false,
    hasMore:true,
    clickType:null,//1是关注，2是监控
    changeFollow:false,
    dataRangeRecord:[]
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    var data = JSON.parse(decodeURIComponent(options.product))
    this.setData(
      {
        searchType:options.type,
        product:data,
        keyword:data.key
      }
    )
    console.log(this.data.product)
    this.init()
    
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
    this.setData(
      {
        patentNoList:[],
        patentList:[],
      }
    )
  },

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

  },

  /**
   * 页面功能
   */
  //获取检索专利的范围
  getDataRangeRecord(){
    if(this.data.dataRangeRecord  && this.data.dataRangeRecord.length>0){
      return false
    }
    api.getDataRangeRecord().then(res=>{
      if(res.code == 200){
        this.setData(
          {
            dataRangeRecord:res.data.data
          }
        )
      }
    })
  },
  //初始化加载
  init(){
    var params = {
      current:1,
      size:10
    }
    this.setData(
      {
        queryParams:params,
        total:0,
        tableData:[],
        hasMore:true
      }
    )
    this.getPatentVectors()
  },

  //下拉刷新
  onRefresh() {
    console.log('onRefresh')
    this.setData({
      triggered: true,
    })
    this.init()
  },
  toURL(){
    console.log(2)
    if(this.data.searchType == 1 && this.data.product.id){
      wx.navigateTo({
        url: '/pages/productDetail/productDetail?productId='+this.data.product.id,
      })
    }
    // if(this.data.product.amazonLink){
    //   wx.navigateTo({
    //     url: '/pages/webView/webView?src='+this.data.product.amazonLink,
    //   })
    // }
    
  
  },

  openDialog2(){
    this.getDataRangeRecord()
    this.setData(
      {
        showDialog2:true
      }
    )
  },
  closeDialog2(){
    this.setData(
      {
        showDialog2:false
      }
    )
  },


  //查看图片
  previewImage(e) {
    console.log(e)
    var { 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
    showImage.showImageList(
      {
        current,
        urls: imgs.map((n) => ({ image: n, remark: n })),
        indicatorDots: true,
        indicatorColor: '#fff',
        indicatorActiveColor: '#04BE02',
        showDelete:false
      }
    )

  },
  //修改输入的关键词
  changeKeyword(e){
    this.setData(
      {
        keyword:e.detail
      }
    )
  },
 //切换检索类型
 changeSearchType(e){
   console.log(e)
   var field = e.detail
   var str = this.data.product[field] || ''
   this.setData(
     {
       keyword:str
     }
   )
 },
  //点击搜索按钮
  search(e){
    console.log(e)
    var {value,field,lastField,filePath} = e.detail
    if(lastField){
      this.setData(
        {
          ["product."+lastField]:''
        }
      )
    }
    this.setData(
      {
        ["product."+field]:value,
        ["product.filePath"]:filePath,
        ifAddSearchRecord:true,
        concernType:null,
        searchType:0
      }
    )
    this.init()
  },

  //查询产品相关专利
  getPatentVectors(){
    console.log(this.data.product)
    var params = {
      pageNum:this.data.queryParams.current,
      pageSize:this.data.queryParams.size,
      ifAddSearchRecord:this.data.ifAddSearchRecord
    }
    if(this.data.searchType == 1){
      params.productId = this.data.product.id
    }else{
      params.description = this.data.product.description
    }
    params.key = this.data.product.key
    params.companyName = this.data.product.companyName
    var vectorDTO = JSON.stringify(params)
    var url = 'getPatentVectors'
    var data = {
      vectorDTO:vectorDTO
    }
    if(this.data.product.filePath){
      url = "getPatentVectorsByImage"
    }
    wx.showLoading({
      title: '加载中',
    })
    api[url](data,this.data.product.filePath).then(res=>{
      if(res.code == 200){
        console.log(res)
        var len1 = this.data.tableData.length
        var len = len1>0?len1: 0
        var data = this.data.tableData.concat(res.data.data)
        this.setData(
          {
            tableData:data,
            total:res.data.total,
            ifAddSearchRecord:false,
            triggered: false,
            load:false
          }
        )
        if(this.data.total<=data.length){
          this.setData({
            hasMore:false
          })
        }
        for(let i = 0;i<res.data.data.length;i++){
          this.getPictureByNo(res.data.data[i],len)
          len += 1 
        }
        // res.data.data(item=>{
        //   this.getPictureByNo(item,len)
        //   len += 1 
        // })
      }
    }).catch(error=>{
      this.setData({
        triggered: false,
        load:false
      })
    })
  },
  //根据专利号获取相关图片
  getPictureByNo(data,index){
    var params = {
      appNo:data.appNo
    }
    api.getPictureByNo(params).then(res=>{
      if(res.code == 200){
        this.setData(
          {
            ["tableData["+index+"].imageList"]:res.data
          }
        )
      }
    })
  },
  //加载更多
  loadMore(){
    var current = this.data.queryParams.current
    this.setData(
      {
        ['queryParams.current']:current+1,
        load :true
      }
    )
    this.getPatentVectors()
  },
  //查看专利详情
  checkPatentDetail(e){
    var {patentno} = e.currentTarget.dataset
    wx.navigateTo({
      url: '/pages/patentDetails/patentDetails?patentNo='+patentno,
    })
  },
  //选择专利
  changePatentNoList(event) {
    console.log(event)
    var {item,patentno} = event.currentTarget.dataset
    var data = event.detail
    var patent = this.data.patentList
    var index = data.indexOf(patentno)
    if(index == -1){
      var index1 = patent.findIndex(item=>{
        return item.patentno == patentno
      })
      patent.splice(index1,1)
    }else{
      patent.push(item)
    }
    this.setData({
      patentNoList: event.detail,
      patentList:patent
    });
  },

  onchange(e){
    console.log(1)
  },

  //查看已选择的专利
  clickButton(e){
    console.log(e)
    var that = this
    wx.navigateTo({
      url: '/pages/selectedPatents/selectedPatents',
      events: {
        // 为指定事件添加一个监听器，获取被打开页面传送到当前页面的数据
        acceptDataFromOpenedPage: function(data) {
          console.log(data)
        },
        someEvent: function(data) {
          console.log(data)
        }
      },
      success: function(res) {
        // 通过eventChannel向被打开页面传送数据
        res.eventChannel.emit('acceptDataFromOpenerPage', { data: that.data.patentList,patentNoList:that.data.patentNoList })
      }
    })
  },

  //关注产品
  open(clickType=1){

    if(this.data.searchType == 0 && !this.data.product.id){
      this.toImproveInformation('关注')
      return false
    }
    this.setData(
      {
        showDialog:true,
        clickType:clickType
      }
    )
  },
  //取消关注
  closeDialog(){
    this.setData(
      {
        showDialog:false,
        followType:null
      }
    )
    wx.nextTick(() => {
      this.setData({ changeFollow: false }) // 在当前同步流程结束后，下一个时间片执行
    })
  },
  //关注类型
  attention(e){
    var {type} = e.currentTarget.dataset
    this.setData(
      {
        followType:type
      }
    )
  },
  //是否收藏
  changeIsAdd(e){
    this.setData(
      {
        isAdd:e.detail
      }
    )
  },
  //确认关注
  confirm(e){
    var {type,isAdd} = e.detail
    this.setData(
      {
        isAdd:isAdd
      }
    )
    var that = this
    var params = {
      productId:this.data.product.id,
      concernType:type==-1?null:type
    }
    if(this.data.clickType == 2){
      this.addMonitoring(params,type)
      return
    }
    wx.showLoading({
      title: '加载中',
    })
    
    api.follow(params).then(res=>{
      if(res.code == 200){
        var obj = {
          type: 'success', 
          message: '关注成功',
          top:wx.getStorageSync('height')
        }
        api.notify(obj)
        that.setData({
          ['product.concernType'] : type,
        })
        that.closeDialog()
        this.collectPatent()
      }
    })
  },
  //跳转填写产品信息
  toImproveInformation(method){
    var that = this
    wx.navigateTo({
      url: `/pages/form/addProduct/addProduct`,
      success: function(res) {
        // 通过eventChannel向被打开页面传送数据
        var data = {
          ...that.data.product,
          // concernType:that.data.followType,
          method:method
        }
        res.eventChannel.emit('acceptDataFromOpenerPage', data)
      }
    })
  },
//收藏专利
collectPatent(){
  if(this.data.isAdd ){
    this.setData(
      {
        idAdd:false
      }
    )
    if(this.data.patentNoList && this.data.patentNoList.length>0){
      var params1 = {
        productId:this.data.product.id,
        patentNos:this.data.patentNoList
      }
      api.collectPatent(params1).then(res=>{
        if(res.code == 200){
          
        }
      })
    }
  }
},

//打开弹窗
cancel(){
  this.setData(
    {
      changeFollow:true,
      showDialog:true,
      clickType:1
    }
  )
},
  //取消关注
  cancelFollow(e){
    if(!this.data.product.id){
      return false
    }
    // this.closeDialog()
    wx.showModal({
      title: '提示',
      content: '取消关注后会取消该产品的监控，确认取消关注？',
      complete: (res) => {
        if (res.cancel) {}
        if (res.confirm) {
          var product = this.data.product
          var params = {
            productId:product.id
          }
          this.closeDialog()
          wx.showLoading({
            title: '取消中',
          })
          api.unFollow(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({
                ['product.concernType'] : null,
                ["product.ifMonitor"]:false
              })
              // if(this.data.searchType == 0){
              //   this.setData({
              //     ['product.id'] : null
              //   })
              // }
            }
          })
        }
      }
    })
  },
 //监控
 control(e){
  if(this.data.searchType == 0 && !this.data.product.id){
    this.toImproveInformation('监控')
    return
  }
  if(this.data.product.concernType == 0 || this.data.product.concernType){
    wx.showModal({
      title: '提示',
      content: '是否确定监控该产品？',
      complete: (res) => {
        if (res.cancel) {}
        if (res.confirm) {
          var params = {
            productId:this.data.product.id
          }
          this.addMonitoring(params)
        }
      }
    })
    return false;
  }
  this.open(2)
},
//监控产品接口
addMonitoring(product,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(
      {
        ['product.ifMonitor'] : true,
      }
    )
    if(type == 0 || type){
      this.setData({
        ['product.concernType'] : type,
      })
    }
    this.closeDialog()
  })
},

 //取消监控产品接口
 cancelMonitoring(params,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(
        {
          ["product.ifMonitor"]:false
        }
      )
      if(type == 1){
        this.setData(
          {
            ["product.concernType"]:null
          }
        )
      }
    }
  })
},

cancelControl(){
  var product = this.data.product
  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,0)
          break;
        case 1:
          params.ifCancelConcern = true
          that.cancelMonitoring(params,1)
          break;
        case 2:
          break
      }
    },
    fail (res) {
      console.log(res.errMsg)
    }
  })

},


//点击button
onClick(e){
  console.log(e)
  var btn = e.detail.value
  this[btn.method]()
},
//导出
export(){
  if(!this.data.patentNoList || this.data.patentNoList.length==0){
    wx.showToast({
      title: '您未选择专利！',
      icon:'none',
      duration: 2000
    })
    return false
  }
 
  var params = {
    patentNos:this.data.patentNoList
  }
  wx.showLoading({
    title: '导出中',
  })
  var that = this
  api.exportPatent(params).then(res=>{
    if(res.code == 200){
      var url = that.data.imgHttp + res.data.data
      // wx.setClipboardData({
      //   data: url,
      //   success(res) {
      //     wx.showToast({
      //       title: '复制成功，快到浏览器打开/下载！',
      //       icon: 'none',
      //       duration: 3000
      //     })
      //   }
      // })
      downLoad.downLoadFile(res.data.data).then(res=>{
        
      })
    }
  })
},
//我要查风险
check(){
  if(!this.data.patentNoList || this.data.patentNoList.length == 0){
    wx.showToast({
      title: '请先选择专利',
      icon:'none'
    })
    return false
  }
  var that = this
  wx.navigateTo({
    url: '/pages/form/riskAssessment/riskAssessment',
    events: {
      // 为指定事件添加一个监听器，获取被打开页面传送到当前页面的数据
      acceptDataFromOpenedPage: function(data) {
        console.log(data)
      },
      someEvent: function(data) {
        console.log(data)
      }
    },
    success: function(res) {
      // 通过eventChannel向被打开页面传送数据
      res.eventChannel.emit('acceptDataFromOpenerPage', { patentNoList:that.data.patentNoList })
    }
  })
},
makePhoneCall(){
  wx.makePhoneCall({
    phoneNumber: this.data.phone
  })
},


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

  },

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

  },

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

  },

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

  },

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

  }
})