// pages/add/index.js
const config = require("../../config/config")
const dayjs = require('dayjs');
const {
  api
} = require("../../utils/api")
Page({

  /**
   * 页面的初始数据
   */
  data: {
    minDate: new Date(2019, 1, 1).getTime(),
    show:false,
    value: new Date().getTime(),
    showDate:false,
    visible: false,
    pic: '',
    form: {
      name:'',
      plantTime:'',
      ossIds:[],
      "carePlans": [{
        "name": "浇水",
        "desc": "浇水",
        "period": 7,
        "color":'#4B84EE',
        "icon":"saturation"
      },
      {
        "name": "施肥",
        "desc": "施肥",
        "period": 30,
        color:"#EAA13B",
        icon:"fill-color"
      },
      {
        "name": "修剪",
        "desc": "修剪",
        color:"#60C26B",
        "period": 180,
        "icon":"cut"
      },
      {
        "name": "旋转方向",
        "desc": "旋转方向",
        "period": 7,
        "color":'#9D5FEF',
        "icon":"refresh"
      },
      
      {
        "name": "换土",
        "desc": "换土",
        "period": 365,
        color:"#EAA13B",
        "icon":"clear"
      },
      {
        "name": "换盆",
        "desc": "换盆",
        "period": 365,
        color:"#626BE9",
        "icon":"broccoli"
      }
    ]
    },
    badge:null
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    const date = dayjs(new Date().getTime()).format('YYYY-MM-DD')
    const tmps = this.data.form
    tmps.plantTime = date
    this.setData({form: tmps})
  },

  handleConfirm(e) {
    const value = e.detail.value
    const date = dayjs(value).format('YYYY-MM-DD')
    const tmps = this.data.form
    tmps.plantTime = date
    this.setData({form:tmps})
},

  showDatePicker(){
    this.setData({showDate:true})
  },

  showPicker(){
    this.setData({visible:true})
  },

  update(e){
    const item = e.detail.value
    const tmps = this.data.form
    const index =this.data.form.carePlans.findIndex(e => e.name === item.name)
    tmps.carePlans[index] = item
    this.setData({form:tmps})
  },

  upload() {
    const _this = this
    wx.chooseMedia({
      count: 1,
      mediaType: ['image'],
      sourceType: ['album', 'camera'],
      success(res) {
        const avatarUrl = res.tempFiles[0].tempFilePath
        wx.showLoading({
          title: '请稍后...',
        })
        _this.setData({
          pic: avatarUrl
        })
        wx.uploadFile({
          filePath: avatarUrl,
          name: 'file',
          header: {
            'Authorization': 'Bearer ' + wx.getStorageSync('token'),
          },
          url: config.baseUrl + '/oss/upload',
          success: res => {
            wx.hideLoading()
            var data = JSON.parse(res.data);
            if (data.code === 200) {
                const  ossIds =[data.data.file.id]
                _this.fetchCheck(data.data.file.id)
                _this.data.form.ossIds = ossIds
            }
          }
        })
      }
    })
  },

  fetchCheck(id){
    api("/ocr/url",'GET',{id:id}).then(res => {
      if (res.code == 200){

        const tmp = res.data.result[0]
        if ( tmp.score > 0.5){
          const tmps = this.data.form
          tmps.name = tmp.name
          this.setData({form: tmps})
        }
      }
    })
  },
  input(e){
    const value = e.detail.value
    this.data.form.name = value
  },

  submit(){

    if (this.data.form.ossIds.length === 0){
      wx.showModal({
        content: '请上传植物照片'
      })
      return
    }

    if (this.data.form.name.length === 0){
      wx.showModal({
        content: '请填写植物名称'
      })
      return
    }
    wx.showLoading({
      title: '请稍后',
    })
    api('/plant/add','POST',this.data.form,'json').then(res => {
      if (res.code === 200){
        const tmps = res.data
        if (tmps != null){
          this.setData({badge: tmps[0],show:true})
        } else {
          wx.navigateBack()
        }
      } else {
        wx.showModal({
          content: res.msg
        })
      }
    })
  },

  goBack(){
    wx.navigateBack()
  },

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

  },

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

  },

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

  },

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

  },

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

  },

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

  },

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

  }
})