// pages/add_record/index.js

const req = require('../../api/teacher.js')
const utils = require('../../utils/util.js')
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    radioValues: [{
        'value': '饮食',
        'code': 'diet',
        'selected': true
      },
      {
        'value': '睡眠',
        'code': 'sleep',
        'selected': false
      },
      {
        'value': '大小便',
        'code': 'wc',
        'selected': false
      },
    ],
    clazz: [],
    studentIds: [],
    controlIndex: 0,
    categoryCode: ['diet_morning', 'diet_morning_more', 'diet_afternoon', 'diet_afternoon_more', 'diet_evening'],//, 'diet_water', 'diet_milk'
    // 饮食子分类
    categorys: [],
    wcCategoryCode: ['wc_pee', 'wc_poo','wc_diaper'],
    // 大小便子分类
    wcCategorys:[],
    typeIndex: 0,
    inputModel: [

    ],
    selectPic: [],
    /* 所有的小分类字典 */
    recordTypes: app.globalData.recordTypes,
    /* 吃饭类型的选项字典 */
    eatStates: app.globalData.eatStates,
    eatCellTags: {},

    //获取到的数据
    eatRecord: [],
    sleepRecord: [],
    wcRecord: [],
    // 如果是多个学生, 则不显示添加图片区域和备注
    hidePhoto: false,
    pictureIds: [],
    pictureUrl: [],
    //学生备注
    remark:'',
    //图片备注
    picRemark: '',
    isHideBtn: false,


  },

  //添加图片
  addPicture: function(e) {
    var that = this;
    // 选择图片
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有
      success: function(res) {
        //选中的图片路径
        let temPath = res.tempFilePaths[0]
        that.data.selectPic.push(temPath)
        that.setData({
          selectPic: that.data.selectPic
        });

        wx.uploadFile({
          url: utils.uploadPath(),
          filePath: temPath,
          name: 'file',
          header: {
            'access-token': utils.getAccessToken()
          },
          success(res) {
            const resData = JSON.parse(res.data)
            // 获取服务端图片id
            that.data.pictureIds.push(resData.obj)
            that.data.pictureUrl.push(utils.handleImgShow(resData.obj))
            if (resData.obj) {
              that.setData({
                pictureIds: that.data.pictureIds,
                pictureUrl: that.data.pictureUrl
              })
            } else {
              throw new Error({
                msg: '图片上传失败'
              })
            }
          },
          fail(err) {
            wx.showToast({
              title: err.msg,
              icon: 'none'
            })
          }
        })

      }
    })
  },

  previewPic: function(e) {
    var current = this.data.pictureUrl[e.target.dataset.index]
    wx.previewImage({
      current: current,
      urls: this.data.pictureUrl
    })

  },

  remarkInput: function (e) {
    console.log(e)
    let inputValue = e.detail.value
    this.setData({
      remark: inputValue
    })

  },

  picRemarkInput: function (e) {
    console.log(e)
    let inputValue = e.detail.value
    this.setData({
      picRemark: inputValue
    })

  },

  headerBtnTap: function (e) {
    var arrRecord = []
    let eatState = null
    if (this.data.controlIndex == 0) {
      arrRecord = this.data.eatRecord
    } else if (this.data.controlIndex == 1) {
      arrRecord = this.data.sleepRecord
    } else if (this.data.controlIndex == 2) {
      arrRecord = this.data.wcRecord;
    }
    var arrRecordList = []
    var item = arrRecord[0].recordItems[0]
    if (item == null) {
      wx.showToast({
        title: '该记录已经删除',
        icon: 'none'
      })
      return
    }

    req.deleteRecord(item.id).then(res=>{
      console.log(res)
      wx.showToast({
        title: '删除成功~',
        duration: 1500
      })
      setTimeout(() => {
        wx.navigateBack({

        })
      }, 1500)

    }).catch(function (err) {
      wx.showToast({
        title: err.message ? err.message : '网络错误',
        icon: 'none',
        duration: 2000
      });
    });


  },
  //删除图片
  deleteImg: function(e) {
    var that = this
    that.data.selectPic.splice(e.currentTarget.dataset.index, 1)
    that.data.pictureIds.splice(e.currentTarget.dataset.index, 1)
    that.data.pictureUrl.splice(e.currentTarget.dataset.index, 1)
    that.setData({
      selectPic: that.data.selectPic,
      pictureIds: that.data.pictureIds,
      pictureUrl: that.data.pictureUrl
    })
  },
  //选择小分类
  tapType: function(e) {

    let index = null
    if (e.target.dataset.index != this.data.typeIndex) {
      index = e.target.dataset.index
    }

    this.setData({
      typeIndex: index,
    })


    this.getRecord()
  },

  indexChanged: function(e) {
    // 点中的是组中第个元素
    var index = e.target.dataset.index;

    // 读取原始的数组
    var radioValues = this.data.radioValues;
    for (var i = 0; i < radioValues.length; i++) {
      // 全部改为非选中
      radioValues[i].selected = false;
      // 当前那个改为选中
      radioValues[index].selected = true;
    }

    // console.log(radioValues)
    // 写回数据
    this.setData({
      radioValues: radioValues,
      controlIndex: index
    });
    // clazz状态
    this.clazzStatus();

    this.getRecord()
  },

  // 初始化分类数据
  configCategory: function() {
    // 饮食分类
    var categorys = this.data.categorys
    for (var i = 0; i < this.data.categoryCode.length; i++) {
      let category = this.data.recordTypes[this.data.categoryCode[i]]
      categorys.push(category)
    }

    var wcCategorys = this.data.wcCategorys
    for (var i = 0; i < this.data.wcCategoryCode.length; i++) {
      let category = this.data.recordTypes[this.data.wcCategoryCode[i]]
      wcCategorys.push(category)
    }

    this.setData({
      categorys: categorys,
      wcCategorys: wcCategorys
    })
  },

  // 调用接口获取数据
  getRecord: function() {
    let studentIds = this.data.studentIds
    console.log(studentIds)

    let category = this.data.radioValues[this.data.controlIndex].code
    let type = ''
    if (this.data.controlIndex == 0) {
      type = this.data.categoryCode[this.data.typeIndex]
    } else if (this.data.controlIndex == 2){
      type = this.data.wcCategoryCode[this.data.typeIndex]
    }

    req.queryRecordList(category, type, studentIds).then(res => {
      console.log(res)
      var eatCellTags = this.data.eatCellTags
      var optionTag = ['diet_morning', 'diet_afternoon', 'diet_evening', 'diet_morning_more', 'diet_afternoon_more']
      for (var i = 0; i < res.length; i++) {
        var item = res[i]

        if (item.recordItems.length == 0) {
          //没有记录时, 自动生成一条
          var r = {}
          r.recordType = type
          r.recordCategory = category
          item.recordItems.push(r)
        }

        for (var k = 0; k < item.recordItems.length; k++) {
          var r = item.recordItems[k]
          if (r.recordCategory == 'sleep') {
            r.cellType = 'input'
            r.cellUnit = '分钟'
            break
          }

          if (r.recordType == 'diet_milk') {
            r.cellType = 'input'
            r.cellUnit = '毫升'
            break
          }

          if (r.recordType == 'diet_water' || this.data.wcCategoryCode.indexOf(r.recordType) != -1) {
            r.cellType = 'input'
            r.cellUnit = '次'
            break
          }

          for (var j = 0, len = optionTag.length; j < len; j++) {
            var tag = optionTag[j]
            if (r.recordType == tag) {
              r.cellType = 'select'
              r.cellOptions = ['少', '正常', '多']
              let eatStatus = Object.keys(this.data.eatStates)
              r.optionIndex = eatStatus.indexOf(r.eatState)
              break
            }
          }

        }
        // 如果小分类没有被选中,去除数据
        if (this.data.typeIndex == null) {
          item.recordItems = []
        }
      }
      if (this.data.controlIndex == 0) {
        this.setData({
          eatRecord: res
        })
      } else if (this.data.controlIndex == 1) {
        this.setData({
          sleepRecord: res
        })
      } else if (this.data.controlIndex == 2) {

        // for (var i = 0; i < res.length; i++) {
        //   var item = res[i]
        //   var pee = '0'
        //   var poo = '0'
        //   var diaper = '0'
        //   item.cellType = 'select'
        //   item.cellOptions = ['小便', '大便', '尿不湿']
        //   for (var j = 0; j < item.recordItems.length; j++) {
        //     var r = item.recordItems[j]
        //     if (r.recordType == 'wc_pee') {
        //       pee = r.value
        //     } else if (r.recordType == 'wc_poo') {
        //       poo = r.value
        //     } else if (r.recordType == 'wc_diaper') {
        //       diaper = r.value
        //     }
        //     console.log('pee ' + pee + ' poo ' + poo + ' diaper ' + diaper)
        //   }
        //   let wcString = '小便 ' + pee + '次   大便 ' + poo + '次   尿不湿 ' + diaper + '次'
        //   item.wcString = wcString
        // }

        this.setData({
          wcRecord: res
        })

      }
      if (this.data.studentIds.length == 1) {
        let std = res[0]
        this.setData({
          isHideBtn: std.state == 'finish'
        })
      }

    })
  },
  // 点击cell上面的选项的点击事件
  quantityCellTap: function(e) {
    console.log(e.currentTarget.dataset)
    let optionIndex = e.currentTarget.dataset.optionindex
    let cellIndex = e.currentTarget.dataset.cellindex
    let records = this.getCurrentRecord()
    var item = records[cellIndex].recordItems[0]
    let selectIndex = e.currentTarget.dataset.optionindex
    // if (this.data.controlIndex == 2) {
    //   if (records[cellIndex].optionIndex == selectIndex) {
    //     records[cellIndex].optionIndex = null
    //   }else{
    //     records[cellIndex].optionIndex = selectIndex
    //   }
    // } else {
      if (item.optionIndex == selectIndex) {
        item.optionIndex = null
      }else{
        item.optionIndex = selectIndex
      }
    // }

    if (this.data.controlIndex == 0) {
      this.setData({
        eatRecord: records
      })
    } else if (this.data.controlIndex == 1) {
      this.setData({
        sleepRecord: records
      })
    } else if (this.data.controlIndex == 2) {
      this.setData({
        wcRecord: records
      })
    }

  },
  // cell上面的输入事件
  bindKeyInput: function(e) {
    let value = e.detail.value
    let cellIndex = e.currentTarget.dataset.cellindex
    console.log(e)
    let records = this.getCurrentRecord()
    var item = records[cellIndex].recordItems[0]
    item.value = value
    if (this.data.controlIndex == 0) {
      this.setData({
        eatRecord: records
      })
    } else if (this.data.controlIndex == 1) {
      this.setData({
        sleepRecord: records
      })
    } else if (this.data.controlIndex == 2) {
      this.setData({
        wcRecord: records
      })
    }

  },
  // 返回当前点击的大类的数据
  getCurrentRecord: function() {
    var arrRecord = []
    if (this.data.controlIndex == 0) {
      arrRecord = this.data.eatRecord
    } else if (this.data.controlIndex == 1) {
      arrRecord = this.data.sleepRecord
    } else if (this.data.controlIndex == 2) {
      arrRecord = this.data.wcRecord;
    }
    return arrRecord

  },
  // 点击底部的保存按钮
  operateTap: function(event) {
    console.log(event._relatedInfo.anchorTargetText)
    var arrRecord = []
    let eatState = null
    if (this.data.controlIndex == 0) {
      arrRecord = this.data.eatRecord
    } else if (this.data.controlIndex == 1) {
      arrRecord = this.data.sleepRecord
    } else if (this.data.controlIndex == 2) {
      arrRecord = this.data.wcRecord;
    }
    var arrRecordList = []

    for (var i = 0; i < arrRecord.length; i++) {
      var item = arrRecord[i]

      for (var j = 0; j < item.recordItems.length; j++) {
        var recordItem = item.recordItems[j]
        var value = recordItem.value;

        let addRecord = {
          "id": recordItem.id,
          "createName": recordItem.createName,
          "createBy": recordItem.createBy,
          "createDate": recordItem.createDate,
          "updateName": recordItem.updateName,
          "updateBy": recordItem.updateBy,
          "updateDate": recordItem.updateDate,
          "sysOrgCode": recordItem.sysOrgCode,
          "sysCompanyCode": recordItem.sysCompanyCode,
          "recordCategory": recordItem.recordCategory,
          "recordType": recordItem.recordType,
          "eatState": Object.keys(this.data.eatStates)[recordItem.optionIndex],
          "value": value,
          "signSummaryId": item.signSummaryId
        }
        // 如果是饮食分类没有选中选项的时候,不保存明细
        if (this.data.controlIndex == 0 && (recordItem.optionIndex == null || recordItem.optionIndex == -1)) {
          continue
        }

        arrRecordList.push(addRecord)
        
      }
    }

    let signSummaryId = null
    let remark = null
    let picRemark = null
    if (this.data.studentIds.length == 1) {
      signSummaryId = arrRecord[0].signSummaryId
      remark = this.data.remark
      picRemark = this.data.picRemark
      

    }

    req.setRecord(signSummaryId,arrRecordList,this.data.pictureIds, remark, picRemark).then(res => {
      wx.showToast({
        title: '保存成功~',
        duration: 1500
      })
      setTimeout(() => {
        wx.navigateBack({

        })
      }, 1500)

    })
  },

  onLoad: function(options) {
    this.data.studentIds = JSON.parse(options.studentIds)
    let remark = options.remark
    let picRemark = options.picRemark
    if (options.pictureIds != null) {
      this.data.pictureIds = JSON.parse(options.pictureIds)
    }
    
    for (var i = 0; i < this.data.pictureIds.length; i++) {
      this.data.pictureUrl.push(utils.handleImgShow(this.data.pictureIds[i]))
    }
    this.setData({
      pictureUrl: this.data.pictureUrl,
      remark: remark != null ? remark : '',
      picRemark: picRemark != null? picRemark : ''
    })
    
    console.log(this.data.pictureIds)
    if (this.data.studentIds.length > 1) {
      this.setData({
        hidePhoto: true
      })
    }
    // onLoad 比 onReady 更早调用,后者为选中时屏幕闪动一下
    this.clazzStatus();

    //分类数据
    this.configCategory()
    //获取选中的分类的记录
    this.getRecord()
  },

  clazzStatus: function() {
    /* 此方法分别被加载时调用,点击某段时调用 */
    // class样式表如"selected last","selected"
    var clazz = [];
    // 参照数据源
    var radioValues = this.data.radioValues;
    for (var i = 0; i < radioValues.length; i++) {
      // 默认为空串,即普通按钮
      var cls = '';
      // 高亮,追回selected
      if (radioValues[i].selected) {
        cls += 'selected ';
      }
      // 最后个元素, 追加last
      if (i == radioValues.length - 1) {
        cls += 'last ';
      }
      //去掉尾部空格
      cls = cls.replace(/(\s*$)/g, '');
      clazz[i] = cls;
    }

    // console.log(clazz)
    // 写回数据
    this.setData({
      clazz: clazz
    });
  },

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

  },

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

  },

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

  },

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

  },

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

  },

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

  },

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

  }
})