// pages/lianxi/index.js
const api = require("../../utils/request.js");
Page({

  /**
   * 页面的初始数据
   */
  data: {
    questioncatData: [],
    isLoad: true,
    workscopeName:''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function () {
    if (getApp().globalData.userinfo.workscope) {
      this.setData({
        workscopeId: getApp().globalData.userinfo.workscope,
        workscopeName:getApp().globalData.userinfo.workscope_name
      })
    } else {
      wx.switchTab({
        url: '/pages/main/main',
      })
    }

  },

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

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.getList()
  },
  getList: function () {
    var that = this
    if (that.data.workscopeId) {
      api.request('/question/questioncat/workscope/', 'GET', { 'id': that.data.workscopeId }).then(res => {
        let questioncatData = []
        if (res.data.length > 0) {
          for (var i = 0; i < res.data.length; i++) {
            let questioncat = {}
            questioncat['id'] = res.data[i].id
            questioncat['name'] = res.data[i].name
            questioncat['tmtotal'] = res.data[i].tmtotal
            questioncat['type'] = res.data[i].type
            questioncat['ydtmtotal'] = 0
            questioncatData.push(questioncat)
          }
          that.setData({
            questioncatData: that.showYd(questioncatData)
          })
        }
      })
    }

  },
  showYd: function (cat) {
    for (var i = 0; i < cat.length; i++) {
      try {
        var value = wx.getStorageSync('cat' + cat[i].id.toString())
        if (value) {
          cat[i]['ydtmtotal'] = value.length
        }
      } catch (e) {
      }
    }
    return cat
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    var process = {}
    try {
      const res = wx.getStorageInfoSync()
      const keys = res.keys
      for(var i=0;i<keys.length;i++){
        if(keys[i].indexOf('cat')!=-1){
          try{
            if(wx.getStorageSync(keys[i]) ){
              process[keys[i]] = wx.getStorageSync(keys[i]) 
            }
            
          }catch(e){}
        }
      }
    } catch (e) {
      // Do something when catch error
    }
    api.request('/crm/consumer/process/', 'put', { 'process': process }).then(res => {
    })
  },

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

  },

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

  },

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

  },

  startLianxi: function (e) {
    wx.navigateTo({
      url: 'main?questioncat=' + e.currentTarget.id,
    })
  },
  restartLianxi: function (e) {
    try {
      wx.setStorageSync('cat' + e.currentTarget.id, [])
    } catch (e) { }
    wx.navigateTo({
      url: 'main?questioncat=' + e.currentTarget.id,
    })
  }
})