// pages/upload/upload.js
const app = getApp()
const $api = require('../../utils/api.js').API;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    open:true,
    stock_date:'',
    stock:[{name:'',fund:''}],
    stockList:[],
    today_stock_img:[],
    value:[-1],
    is_markt:0,
    today_fund:'',
    change:0,
    experience:'',
    cur:0,
    freshen:true,
    disable:false,
    id:0,
    images:[],
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onShow(){
    if (!this.data.freshen) {
      return;
    }
    this.setData({
      disable: false
    })

    $api.initUser()

    wx.getStorage({
      key: 'user',
      complete: res => {
        this.setData({
          role: res.data.role,
        })
      }
    })

    $api.getCurrecord().then(res=>{
      if (!res.data.data.id){return}
      let stock = res.data.data.today_stock
      this.setData({
        stock: stock.length > 0 ? stock : [{ name: '', fund: '' }],
        today_stock_img: res.data.data.today_stock_img,
        today_fund: res.data.data.today_fund,
        is_markt: res.data.data.is_markt,
        change: 1,
        experience: res.data.data.experience,
        id:res.data.data.id
      })
    })

  },
  onLoad: function (options) {
    var y=new Date().getFullYear() 
    var m=Number(new Date().getMonth() + 1)
    var d = new Date().getDate()
    m=m>9?m:'0'+m;
    d=d>9?d:'0'+d
    this.setData({
      stock_date:y+'-'+m+'-'+d
    })
    
  },
  /**添加持股 */
  add(){
    var stock = this.data.stock;
    var value=this.data.value;
    stock.push({ name: '', fund: '' })
    value.push(-1)
    this.setData({
      stock: stock,
      value: value
    })
  },
  del(e){
    var i = e.target.dataset.id;
    var stock = this.data.stock;
    var value = this.data.value; 
    stock.splice(i,1)
    value.splice(i,1)
    this.setData({
      stock: stock,
      value: value
    })
  },
  delToday(e){
    this.setData({
      today_fund: '',
    })
  },
  bindPickerChange(e){
    var i=this.data.cur;
    var v = e.target.dataset.name
    var stock=this.data.stock;
    stock[i].name = v
    stock[i].code = e.target.dataset.id

    this.setData({
      stock: stock
    })
    setTimeout(()=>{
      this.setData({
        stockList: []
      },50)
    })
    return;
  },
  stockSearch(e){
    if (e.detail.value == ''){
      this.setData({
        stockList: []
      })
      return
    }
    var i = e.target.dataset.id;
    var v = e.detail.value
    var stock = this.data.stock;
    stock[i].name = v;
    this.setData({
      stock: stock
    })
    $api.searchStock({ name: e.detail.value}).then(res=>{
        this.setData({
          stockList:res.data.data,
          cur:e.target.dataset.id
        })
    })
  },
  blur(){
    // console.log(233)
    this.setData({
      stockList: []
    })
  },
  nameChange(e){
    console.log(e)
    var i = e.target.dataset.id;
    var v = e.detail.value
    var stock = this.data.stock;
    stock[i].name = v;
    this.setData({
      stock: stock
    })
  },
  fundChange(e){
    var i = e.target.dataset.id;
    var v = e.detail.value
    var stock = this.data.stock;
    if (v.split('.').length > 1 && v.split('.')[1].length > 4) {
      v = Math.floor(Number(v) * 10000) / 10000
    }
    stock[i].fund = v;

    this.setData({
      stock: stock
    })
  },
  fundChange1(e) {
    var v = e.detail.value
    if (v.split('.').length > 1 && v.split('.')[1].length > 4){
      v = Math.floor(Number(v)*10000)/10000
    }
    this.setData({
      today_fund: v
    })
  },
  expChange(e){
    var v = e.detail.value
    this.setData({
      experience: v
    })
  },
  switch1Change(e){
      this.setData({
        is_markt: Number(e.detail.value)
      })
  },
  uploadImg() {
    var today_stock_img = this.data.today_stock_img;
    wx.chooseImage({
      success: res => {
        wx.showLoading({
          title: '正在上传',
        })
    
        const tempFilePaths = res.tempFiles
        for (let i = 0; i < tempFilePaths.length; i++) {
          $api.upload(tempFilePaths[i].path, 'file').then(res => {
            wx.hideLoading()
            if (res.code == 0) {
              console.log(res.data)
              today_stock_img.push(res.data.url)
              this.setData({
                today_stock_img: today_stock_img
              })
              console.log(this.data.today_stock_img,22222222222)
              if (i==0 && today_stock_img.length == 1){
                  this.loadOcr(tempFilePaths[i].path,res.data.url)
              }
            } else {
              wx.showToast({
                title: '上传失败',
              })
            }
          })
            .catch(err => {
              wx.hideLoading()
            })

        }

      }
    })
  },
  loadOcr(path,url){
    var _this = this

    wx.getImageInfo({
      src:path,
      success:function(ires){
        _this.loadImageOcr(url,ires.width < ires.height ? 'phone':'pc')
      }
    })
  },

  loadImageOcr(img_url,source){
    var _this = this
    var param = {
      img_url:img_url.split('?')[0],
      source:source,
    }
    console.log('img_url',param['img_url'])
    console.log('source',param['source'])
    $api.imageOcr(param).then(res => {
      console.log('ocr',res)
      if(res.data.code == 0){
        _this.setData({
          today_fund:res.data.data.today,
          stock:res.data.data.list
        })
      }
    })
  },

  startOcr(e){
    var index = e.target.dataset.index;
    var img_url = this.data.today_stock_img[index]
    
    console.log('startocr',img_url)
    this.loadImageOcr(img_url,this.data.images[index].width < this.data.images[index].height ? 'phone':'pc')
  },

  imageLoad: function(e) {
    var width=e.detail.width; //获取图片真实宽度
    var height=e.detail.height;
    
    var image=this.data.images;
    //将图片的datadata-index作为image对象的key,然后存储图片的宽高值
    image[e.target.dataset.index]={
      width:width,
      height:height,
    }
    this.setData({
    images:image
    })
  },

  del1(e) {
    var i = e.target.dataset.id;
    var today_stock_img = this.data.today_stock_img;
    today_stock_img.splice(i, 1)
    this.setData({
      today_stock_img: today_stock_img
    })
  },
  prview(e){
    var src = e.target.dataset.src;
    wx.previewImage({
      current: src, // 当前显示图片的http链接
      urls: [src] // 需要预览的图片http链接列表
    })
  },
  post(){
    var stocks = []
    var slist = this.data.stock

    for(let i=0;i<slist.length;i++){
      if(slist[i].name.length <= 0){
        continue;
      }

      if(slist[i].fund > 5000){
        wx.showToast({
          icon: 'none',
          title: '持仓金额单位为万'
        })
        return;
      }

      stocks.push(slist[i])
    }

    var parm = {
      stock_date: this.data.stock_date,
      today_stock: stocks,
      is_markt: this.data.is_markt,
      today_stock_img: this.data.today_stock_img,
      today_fund: Number(this.data.today_fund),
      id:this.data.id,
      experience: this.data.experience
    }

    if (!parm.today_fund) {
      wx.showToast({
        icon: 'none',
        title: '请输入今日净资产'
      })
      return
    }

    if (parm.today_fund >= 10000) {
      wx.showToast({
        icon: 'none',
        title: '今日净资产单位为万'
      })
      return
    }

    // if (!parm.is_markt) {
    //   // for (let i = 0; i < parm.today_stock.length;i++){
    //   //   if (!parm.today_stock[i].name || !parm.today_stock[i].fund) {
    //   //     wx.showToast({
    //   //       icon: 'none',
    //   //       title: '请选择股票并输入资金额'
    //   //     })
    //   //     return;
    //   //     break;
    //   //   }
    //   // }

    // } else {
    //   parm.today_stock = []
    // }

    console.log(parm)
    if (parm.today_stock_img.length <= 0) {
      wx.showToast({
        icon: 'none',
        title: '请上传截图'
      })
      return
    }
    wx.showLoading({
      title: '正在提交',
    })
    this.setData({
      disable: true
    })
    $api.updateRecord(parm).then(res => {
      wx.hideLoading()
      wx.showToast({
        title: '提交成功',
      })
      this.setData({
        freshen: true,
        disable: false
      })
      setTimeout(() => {
        this.setData({
          stock: [{ label: '', name: '', code: '', fund: '' }],
          stockList: [],
          today_stock_img: [],
          value: [-1],
          is_markt: 0,
          today_fund: ''
          
        })
        wx.switchTab({
          url: '../user/user',
        })
      }, 200)
    })
    .catch(
      this.setData({
        disable:false
      })
    )    
  },
  
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },



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

  },

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

  },

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

  },

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

  },

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

  }
})