// pages/form/addProduct/addProduct.js
const upload = require("../../../utils/upload")
const api = require('../../../api/index')
import { $wuxForm} from '../../../miniprogram_npm/wux-weapp/index'

Page({

  /**
   * 页面的初始数据
   */
  data: {
    validateMessages: {
      required: '%s 字段为必填',
    },
    form:{
      
    },
    funType:null,
    labelWidth:350,
    fileList:[],
    concernType:[
      {
        type:1,
        label:'白名单',
        icon:'myIconanquanbangzhu'
      },
      {
        type:2,
        label:'灰名单',
        icon:'myIconicon-test'
      },
      {
        type:0,
        label:'黑名单',
        icon:'myIcongroup43'
      },
      {
        type:-1,
        label:'仅关注',
        icon:'myIconguanzhu-yiguanzhu'//已关注
      },
    ]
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    const eventChannel = this.getOpenerEventChannel()
    var that = this
    eventChannel.on('acceptDataFromOpenerPage', function(data) {
      var form = {
        searchCondition:data.key,
        // concernType:data.concernType,
      }
      var file = []
      if(data.filePath){
        file.push(
          {
            status: 'done',
            url: filePath,
          }
        )
      }
      
      that.setData(
        {
          form:form,
          fileList:file,
          funType:data.method
        }
      )
      if(data.filePath){
        that.uploadFile(data.filePath)
      }
      
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

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

  },


  /**
   * 页面方法集合
   */
  //表单栏位值发生变化时
  onValuesChange(e) {
    console.log(e)
    const { changedValues, allValues } = e.detail
    // this.setValues(changedValues)
    Object.keys(changedValues).forEach((field) => {
      this.setData({
          ['form.'+field]: changedValues[field],
      })
    })
    console.log('onValuesChange \n', changedValues, allValues)
  },
  //修改关注类型
  changeConcernType(e){
    this.setData(
      {
        ["form.concernType"]:e.detail
      }
    )
  },
  //图片上传
  beforeUpload(e){
    console.log(e)
    if(e.detail.errMsg=="chooseMedia:ok"){
      // var data = [{
      //   status: 'done',
      //   url: e.detail.tempFiles[0].tempFilePath,
      // }]
      var data = this.data.fileList
      var url = e.detail.tempFiles[0].tempFilePath
      data.push(
        {
          status: 'done',
          url: url,
        }
      )
      this.setData({ fileList:data })
      this.uploadFile(url)
    }
  },
  onRemove(e) {
    console.log(e)
    const { file, fileList } = e.detail
    wx.showModal({
      content: '确定删除？',
      success: (res) => {
        if (res.confirm) {
          var data = this.data.fileList
          this.setData({
            fileList: data.filter((n) => n.url !== file.url),
          })
        }
      },
    })
  },
  uploadFile(tempFilePaths){
    var that = this
    upload.upload(tempFilePaths).then(res=>{
      if(res.code == 200){
        var guid = res.data[0]
        var index = that.data.fileList.findIndex(item=>{
          return item.url == tempFilePaths
        })
        that.setData(
          {
            ["fileList["+index+"].guid"]:guid
          }
        )
        // var arr = that.data.form.fileGuids || []
        // arr.push(res.data[0])
        // that.setData(
        //   {
        //     ["form.fileGuids"]:arr
        //   }
        // )
      }
    })
  },
  
  //输入备注
  changRemark(e){
    this.setData(
      {
        ["form.description"]:e.detail.value
      }
    )
  },

  //提交工单
  submit(){
    var key = api.isLogin()
    if(!key){
      return false
    }
    // var that = this
    const { validateFields } = $wuxForm()
    validateFields((err, values) => {
      console.log(err)
      if (!err) {
        if(this.data.concernType!=0 && !this.data.concernType){
            wx.showModal({
              title: '提示',
              content: '请选择关注类型',
              complete: (res) => {
                if (res.cancel) {}
                if (res.confirm) {}
              }
            })
            return
        }
        var fileGuids = this.data.fileList.map(item=>{
          return item.guid
        })
        var params = {
          ...this.data.form,
          concernType:this.data.form.concernType==-1?null:this.data.form.concernType,
          fileGuids:fileGuids
        }
        if(this.data.funType == '监控'){
          this.addMonitoring(params)
          return
        }

        wx.showLoading({
          title: '加载中',
        })
        var that = this
        api.throttle(
          api.addOrUpdateProduct(params).then(res=>{
            if(res.code == 200){
              wx.showToast({
                title: '关注成功',
                icon: 'success',
                duration: 2000
              })
             that.updateMessage(params,res.data.data)
            }
          })
        )
      }else{
        var error = Object.keys(err)
        var key = error[0]
        var len = err[key].errors.length
        var message = err[key].errors[len-1].message
        wx.showModal({
          title: '提示',
          content: message,
          complete: (res) => {
            if (res.cancel) {
              
            }
        
            if (res.confirm) {
              
            }
          }
        })
      }
    })
  },
  //修改上一页信息
  updateMessage(params,id){
    var pages = getCurrentPages()
    var prepage = pages[pages.length-2]
    var product = prepage.data.product
    product.concernType = this.data.form.concernType
    product.id = id
    product.name=params.name
    product.key = params.searchCondition
    product.filePath = this.data.fileList[0]?.url
    if(this.data.funType == '监控'){
      product.ifMonitor = true
    }
    prepage.setData({
      product : product,
      showDialog:false,
      followType:null,
    })
    prepage.collectPatent()
    wx.navigateBack()
  },
  //监控产品接口
  addMonitoring(product){
    wx.showLoading({
      title: '加载中',
    })
    api.addMonitoring(product).then(res=>{
      wx.showToast({
        title: '监控成功',
        icon: 'success',
        duration: 2000
      })
      this.updateMessage(params,res.data.data)
    })
  },


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

  },

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

  },

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

  },

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

  },

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

  }
})