// pages/searchResults/searchResults.js
const app = getApp()
const api = require('../../api/index')
const downLoad = require('../../utils/downLoad')
import { $startWuxRefresher, $stopWuxRefresher,$stopWuxLoader,$wuxGallery} from '../../miniprogram_npm/wux-weapp/index'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    imgHttp:app.globalData.imghttp,
    phone:app.globalData.phone,
    queryParams:{
      current:1,
      size:10
    },
    ifAddSearchRecord:true,
    total:0,
    loading:false,
    tableData:[],
    keyword:'',
    scrolltop: 60,
    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':'myIconicon-test',//黑
      '1':'myIconanquanbangzhu',//白
      '2':'myIcongroup43'//灰
    },
    showDialog:false,
    followType:null,
    isAdd:false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  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() {
  },

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

  },

  /**
   * 页面功能
   */
  //初始化加载
  init(){
    var params = {
      current:1,
      size:10
    }
    this.setData(
      {
        queryParams:params,
        total:0,
        tableData:[],
        patentNoList:[],
        patentList:[],
      }
    )
    this.getPatentVectors()
  },
  //下拉
  onPulling() {
    console.log('onPulling')
  },
  //下拉刷新
  onRefresh() {
    console.log('onRefresh')
    this.init()
  },
 
  //查看图片
  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
    $wuxGallery().show({
      current,
      urls: imgs.map((n) => ({ image: n, remark: n })),
      indicatorDots: true,
      indicatorColor: '#fff',
      indicatorActiveColor: '#04BE02',
      showDelete:false
    })
    // wx.previewImage({
    //   current,
    //   urls:imgs,
    // })
  },
  //修改输入的关键词
  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
      }
    )
    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
        
        this.setData(
          {
            tableData:this.data.tableData.concat(res.data.data),
            total:res.data.total,
            ifAddSearchRecord: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 
        // })
      }
    })
  },
  //根据专利号获取相关图片
  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
      }
    )
    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(){
    this.setData(
      {
        showDialog:true
      }
    )
  },
  //取消关注
  closeDialog(){
    this.setData(
      {
        showDialog:false,
        followType:null,
      }
    )
  },
  //关注类型
  attention(e){
    var {type} = e.currentTarget.dataset
    this.setData(
      {
        followType:type
      }
    )
  },
  //是否收藏
  changeIsAdd(e){
    
    this.setData(
      {
        isAdd:e.detail
      }
    )
    console.log(e)
  },
  //确认关注
  confirm(){
    console.log(this.data.followType)
    if(this.data.followType != 0 && !this.data.followType){
      api.notify(
        {
          type:'warning',
          message:'请选择关注类型',
          top:wx.getStorageSync('height')
        }
      )
      return false
    }
    var that = this
    if(this.data.searchType == 0){
      console.log(1)
      wx.navigateTo({
        url: `/pages/form/addProduct/addProduct`,
        success: function(res) {
          // 通过eventChannel向被打开页面传送数据
          var data = {
            ...that.data.product,
            concernType:that.data.followType
          }
          res.eventChannel.emit('acceptDataFromOpenerPage', data)
        }
      })
      return false
    }
    var params = {
      productId:this.data.product.id,
      concernType:this.data.followType
    }
    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'] : that.data.followType,
        })
        that.closeDialog()
        // console.log(that.data.isAdd,this.data.patentNoList)
        this.collectPatent()
      }
    })
  },
//收藏专利
collectPatent(){
  if(that.data.isAdd ){
    that.setData(
      {
        idAdd:false
      }
    )
    if(that.data.patentNoList && that.data.patentNoList.length>0){
      var params1 = {
        productId:that.data.product.id,
        patentNos:that.data.patentNoList
      }
      api.collectPatent(params1).then(res=>{
        if(res.code == 200){
          
        }
      })
    }
  }
},
  //取消关注
  cancelFollow(e){
    if(!this.data.product.id){
      return false
    }
    wx.showModal({
      title: '提示',
      content: '确认取消关注？',
      complete: (res) => {
        if (res.cancel) {}
        if (res.confirm) {
          var product = this.data.product
          var params = {
            productId:product.id
          }
          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
              })
              if(this.data.searchType == 0){
                this.setData({
                  ['product.id'] : null
                })
              }
            }
          })
        }
      }
    })
  },
 //监控
 control(e){
  // var index = e.currentTarget.dataset.index
  wx.showModal({
    title: '提示',
    content: '敬请期待！',
    complete: (res) => {
      if (res.cancel) {}
      if (res.confirm) {}
    }
  })
},
//点击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(){
  wx.navigateTo({
    url: '/pages/form/riskAssessment/riskAssessment',
  })
},
makePhoneCall(){
  wx.makePhoneCall({
    phoneNumber: this.data.phone
  })
},


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

  },

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

  },

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

  },

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

  },

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

  }
})