// pages/p-task/p-task.js
var myRequest = require("../../utils/api.js");
const util = require("../../utils/utils");
import * as echarts from '../../components/ec-canvas/echarts';
const app = getApp()
let chart = null;
function initChart(canvas, width, height, dpr) {
  chart = echarts.init(canvas, null, {
    width: width,
    height: height, 
    devicePixelRatio: dpr
  })
  return chart;
}
Page({

  /**
   * 页面的初始数据
   */
  data: {
    tabPanelCustomStyle: '',
    icons: [,
      'chevron-right',
    ],
    tableData:[],
    tableIndex:0,
    defaultSize:50,
    fileList: [],
    deviceId: '',
    projectId: '',
    deviceCode: '',
    details: [],
    state: [],
    alarmData: [],
    filePath: '',
    ec: {
      onInit: initChart
    },
    who:'',
    chartData: [],
    xData: [],
    date: util.getTime1(),
    dateVisible: false,
    dataKeyVisible: false,
    storeAddress: '',
    storeLatitude: '',
    storeLongitude: '',
    sensorData: [],
    sensorInfo: [],
    page: 1,
    size: 10,
    isFromSearch: false,
    visible: false,
    cur: {},
    dataKey: '',
    dataValue: '',
    distributeData: [],
    is_text: false,
    fileUrl: app.globalData.fileUrl,
    siteTotal: 0,
    sensorName: '',
  },
  // 数据处理
  dataProcessing() {
    let that=this;
    var xdata=that.data.xData;
    var data=that.data.chartData;
    let option =  {
      title:{
        text: '站点历史数据折线图',
        left: 'center',
        top:'4%',
        textStyle:{
          fontSize:14,
          color:'#333333'
        }
      },
      legend: {
        z: 100,
        top:'15%',
        right:'4%',
        icon:'rect',
        itemWidth:11,
        itemHeight:8,
        textStyle:{
          fontSize:12,
          color:'#8C8C8C'
        }
      },
      grid:{
        left: '5%',
        right: '5%',
        bottom: '5%',
        top:'30%',
        containLabel: true
      },
      tooltip: {
        show: true,
        trigger: 'axis',
      },
      xAxis: {
        type: 'category',
        data: xdata,
        axisLabel : {
          show : true,
          // interval: 0,
          // rotate:45, //代表逆时针旋转45度
          textStyle:{
            color:'#8C8C8C',
            fontSize:12
          }
        },
        axisLine : {
          show : true,
          lineStyle : {
            color:'#8C8C8C'
          }
          // x轴坐标轴颜色
        },
        axisTick : {
            show : true,
            lineStyle : {
              color:'#8C8C8C'
            }
            // x轴刻度的颜色
        },
      },
      yAxis: {
        splitLine: {
          show: true
        },
        splitArea: { show: true },
        axisLabel : {
          show : true,
          textStyle : {
            color : '#999',
            fontSize:12
          }
        },
        axisLine : {
            lineStyle : {
              color : 'transparent'
            }
            // y轴坐标轴颜色
        },
        axisTick : {
            lineStyle : {
              color : 'transparent'
            }
            // y轴刻度的颜色
        },
      },
      dataZoom: [{
        startValue: '2020-05-17'
      }, {
        type: 'inside'
      }],
      series: {
        name: '',
        type: 'line',
        data: data,
        markLine: {
          silent: false,
        }
      }
    };
    setTimeout(function() {
      chart.setOption(option);
    }, 1000)
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let that = this;
    that.setData({ 
      deviceId: options.deviceId,
      deviceCode: options.code,
      projectId: wx.getStorageSync('projectId'),
      dateText: util.getTime1(),
    })
    that.getDeviceDetail();
    that.getAlarmData();
    that.getSensorData();
  },
  getHistoryData1() {
    var that = this;
    myRequest.myRequest('device/historyChart', {
      dataKey: that.data.formData.dataKey,
      deviceCode: that.data.deviceCode,
      date: that.data.date,
    }, 'get').then(function(res){
      var historyData = res.data.data;
      var xData = [];
      var yData = [];
      for (let i = 0; i < historyData.length; i++) {
        xData.push(historyData[i][0]);
        yData.push(historyData[i][1]);
      }
      that.setData({
        xData: xData,
        chartData: yData,
      })
      that.dataProcessing();
    }).catch(function(res){ 
      console.log(res);
    })
  },
  getHistoryData() {
    var that = this;
    myRequest.myRequest('device/history', {
      dataKey: that.data.formData.dataKey,
      deviceCode: that.data.deviceCode,
      date: that.data.date,
    }, 'get').then(function(res){
      var historyData = res.data.data;
      var xData = [];
      var yData = [];
      for (let i = 0; i < historyData.length; i++) {
        xData.push(historyData[i][0]);
        yData.push(historyData[i][1]);
        historyData[i][2] = i+1
      }
      
      let arr =  res.data.data.slice(0,that.data.defaultSize)
      
      that.setData({
        tableData: res.data.data,
        tableIndex:1,
        historyData:arr,
        xData: xData,
        chartData: yData,
      })
      debugger
      // that.dataProcessing();
    }).catch(function(res){ 
      console.log(res);
    })
  },
  bindtopScroll(e){
    console.log(this.data.tableIndex)

    let data = this.data.tableData.slice((this.data.tableIndex-3)*this.data.defaultSize,(this.data.tableIndex-2)*this.data.defaultSize)
    let lastval = [...this.data.historyData]
    if(this.data.tableIndex>2){
      lastval.splice(lastval.length-this.data.defaultSize,lastval.length)
      this.setData({
        tableIndex:this.data.tableIndex-1,
        historyData:[...data,...lastval],
       
      })
      let id =`item${(this.data.tableIndex-1)*this.data.defaultSize}`
      this.setData({
        who:id
      })
    }

   
  },
  bindnextScroll(e){
    let data = this.data.tableData.slice(this.data.tableIndex*this.data.defaultSize,(this.data.tableIndex+1)*this.data.defaultSize)

    let lastval = [...this.data.historyData]


    if(this.data.tableIndex>1){
      lastval.splice(0,this.data.defaultSize)
    }
  
 console.log(this.data.who)
    this.setData({
      tableIndex:this.data.tableIndex+1,
      historyData:[...lastval,...data],
     
    })
    let id =`item${(this.data.tableIndex-1)*this.data.defaultSize-8}`
    this.setData({
      who:id
    })
  console.log(e)
  },
  getOption(){
    let that=this;
    var xdata=that.data.xData;
    var data=that.data.chartData;
    return {
      title:{
        text: '站点历史数据折线图',
        left: 'center',
        top:'4%',
        textStyle:{
          fontSize:14,
          color:'#333333'
        }
      },
      legend: {
        z: 100,
        top:'15%',
        right:'4%',
        icon:'rect',
        itemWidth:11,
        itemHeight:8,
        textStyle:{
          fontSize:12,
          color:'#8C8C8C'
        }
      },
      grid:{
        left: '5%',
        right: '5%',
        bottom: '5%',
        top:'30%',
        containLabel: true
      },
      tooltip: {
        show: true,
        trigger: 'axis',
      },
      xAxis: {
        type: 'category',
        data: xdata,
        axisLabel : {
          show : true,
          // interval: 0,
          // rotate:45, //代表逆时针旋转45度
          textStyle:{
            color:'#8C8C8C',
            fontSize:12
          }
        },
        axisLine : {
          show : true,
          lineStyle : {
            color:'#8C8C8C'
          }
          // x轴坐标轴颜色
        },
        axisTick : {
            show : true,
            lineStyle : {
              color:'#8C8C8C'
            }
            // x轴刻度的颜色
        },
      },
      yAxis: {
        splitLine: {
          show: true
        },
        splitArea: { show: true },
        axisLabel : {
          show : true,
          textStyle : {
            color : '#999',
            fontSize:12
          }
        },
        axisLine : {
            lineStyle : {
              color : 'transparent'
            }
            // y轴坐标轴颜色
        },
        axisTick : {
            lineStyle : {
              color : 'transparent'
            }
            // y轴刻度的颜色
        },
      },
      dataZoom: [{
        startValue: '2020-05-17'
      }, {
        type: 'inside'
      }],
      series: {
        name: '',
        type: 'line',
        data: data,
        markLine: {
          silent: false,
        }
      }
    };
  },
  handlePopup(e) {
    const { key, unit, convertflag } = e.currentTarget.dataset;
    if (unit != null && unit.indexOf(';')) {
      const unitArr = unit.split(';');
      const unitData = [];
      for (let i = 0; i < unitArr.length; i++) {
        const units = unitArr[i].split(':');
        if (units[1] != '故障') {
          unitData.push({ value: units[0], label: units[1] });
        }
      }
      this.setData({
        distributeData: unitData
      });
    }
    if (convertflag == '1') {
      this.setData({
        is_text: false
      })
    } else if (convertflag == '0') {
      this.setData({
        is_text: true,
        dataValue: ''
      })
    }
    console.log(this.data.dataValue);
    this.setData(
      {
        cur: 'bottom',
      },
      () => {
        this.setData({ 
          visible: true,
          dataKey: key,
          dataValue: ''
         });
      },
    );
  },
  onVisibleChange(e) {
    this.setData({
      visible: e.detail.visible,
    });
  },
  getDataValue(e) {
    this.setData({
      dataValue: e.detail.value
    })
  },
  cancellation() {
    this.setData({
      visible: false,
    })
  },
  Distribute() {
    const { dataKey, dataValue, deviceCode } = this.data;
    var dataValue1 = dataValue == 4 ? 1 : dataValue;
    var that = this;
    myRequest.myRequest('device/write?deviceCode='+deviceCode+'&dataKey='+dataKey+'&dataValue='+dataValue1, {
      deviceCode: deviceCode,
      dataKey: dataKey,
      dataValue: dataValue1,
    }, 'post').then(function(res){
      wx.showToast({
        title: '下发成功',
        icon: 'none',
      })
      that.getDeviceState();
      that.setData({
        visible: false
      })
    }).catch(function(res){
      console.log(res);
    })
  },
  onChangeDistribute(e) {
    this.setData({ dataValue: e.detail.value });
  },

  // 转任务
  toTask(e) {
    var id = e.currentTarget.dataset.id;
    var name = e.currentTarget.dataset.name;
    var code = e.currentTarget.dataset.code;
    wx.navigateTo({
      url: '../u-task/u-task?alarmRecordId=' + id + '&deviceCode=' + code + '&deviceName=' + name,
    })
  },

  //获取站点详情
  getDeviceDetail() {
    var that = this;
    myRequest.myRequest('device/details', {
      deviceId: that.data.deviceId
    }, 'get').then(function(res){
      var baseUrl = app.globalData.url;
      var imgList = [
        {
          url: baseUrl + '/static/img/' + res.data.data.boardImg,
          type: 'image'
        }
      ]
      that.setData({
        details: res.data.data,
        filePath: res.data.data.boardImg,
        latitude: res.data.data.latitude,
        longitude: res.data.data.longitude,
        fileList: imgList,
      })
      wx.setNavigationBarTitle({
        title: res.data.data.name,
      })
    }).catch(function(res){
      console.log(res);
    })
  },
  //设备情况
  getDeviceState() {
    var that = this;
    var code = that.data.details.code;
    if (undefined == code) {
      return false;
    }
    myRequest.myRequest('device/state', {
      deviceCode: code,
      page: this.data.page,
      size: this.data.size,
      sensorName: this.data.sensorName,
    }, 'get').then(function(res){
      console.log('设备情况：' + res.data.data);
      var siteList = res.data.data.items;
      var siteTotal = res.data.data.totalPage;

      that.setData({
        state: siteList,
        siteTotal: siteTotal
      })
      // if (siteList.length != 0){
      //   var list = [];
      //   //如果isFromSearch是true从data中取出数据，否则先从原来的数据继续添加 
      //   that.data.isFromSearch ? list=siteList : list=that.data.state.concat(siteList) 
      //   that.setData({ 
      //     state: list, //获取数据数组 
      //   });
      // }
      // that.setData({ 
      //   searchLoadingComplete: true, //把“没有数据”设为true，显示 
      //   searchLoading: false //把"上拉加载"的变量设为false，隐藏 
      //  });
    }).catch(function(res){
      console.log(res);
    })
  },
  lower: function () {
    this.setData({
      page: this.data.page+1,
      isFromSearch: false
    });
    this.getDeviceState()
  },
  prev: function() {
    let page = this.data.page == 1 ? 1 : this.data.page-1;
    this.setData({
      page: page,
      isFromSearch: false
    });
    this.getDeviceState()
  },
  next: function() {
    let siteTotal = this.data.page+1;
    let page = siteTotal <= this.data.siteTotal ? siteTotal : this.data.siteTotal
    this.setData({
      page: page,
      isFromSearch: false
    });
    this.getDeviceState()
  },
  //告警信息
  getAlarmData() {
    var that = this;
    myRequest.myRequest('alarm/listPage', {
      deviceCode: that.data.deviceCode,
      projectId: that.data.projectId,
      page: 1,
      size: 1000,
    }, 'get').then(function(res){
      that.setData({
        alarmData: res.data.data.items 
      })
    }).catch(function(res){
      console.log(res);
    })
  },
  getSearchKeywords(e) {
    const { value } = e.detail;
    this.setData({
      sensorName: value
    })
  },
  // 搜索
  search() {
    this.getDeviceState()
  },
  //地图选择位置
  getCenterLocation() {
    var that = this;
    wx.showModal({
      title: '',
      content: '是否要更新站点地址？',
      success: function (res) {
        if (res.confirm) {
          that.getLocation();
        }
      }
    })
  },
  getLocation() {
    var that = this
    wx.getLocation({//调用API得到经纬度
      type: 'gcj02',
      isHighAccuracy: true,
      success: function (res) {
        that.setData({
          latitude: res.latitude,
          longitude: res.longitude
        })
        that.deviceUpdate();
      }
    })
  },
  //弃用
  getLocation1() {
    var storeLatitude = this.data.storeLatitude;
    var storeLongitude = this.data.storeLongitude;
    if (storeLongitude && storeLatitude) {
      this.setData({
        latitude: storeLatitude,
        longitude: storeLongitude,
      })
      this.deviceUpdate();
    }
  },
  deviceUpdate() {
    var that = this;
    myRequest.myRequest('device/update', {
      id: that.data.deviceId,
      boardImg: that.data.filePath,
      longitude: that.data.longitude,
      latitude: that.data.latitude,
    }, 'post').then(function(res){
      wx.showToast({
        title: '操作成功',
        icon: 'none',
      })
      that.getDeviceDetail();
    }).catch(function(res){
      console.log(res);
    })
  },

  onTabsChange(event) {
    if (event.detail.value == 1) {
      this.setData({
        state: [],
        page: 1,
      })
      this.getDeviceState();
    } else if (event.detail.value == 3) {
      this.getAlarmData();
    }
    this.setData({
      visible: false,
    })
  },
  handleAdd(e) {
    var that = this;
    const { fileList } = that.data;
    const { files } = e.detail;
    that.setData({
      fileList: [...fileList, ...files],
    });
    myRequest.updateImg({file:files[0].url}).then(function(res){
      fileList.push({url:files[0].url,type:'image',percent:100});
      that.setData({
        filePath: res
      })
      that.deviceUpdate();
    }).catch(function(res){
      console.log(res);
    })
    
  },
  handleRemove(e) {
    const { index } = e.detail;
    const { fileList } = this.data;
    fileList.splice(index, 1);
    this.setData({
      fileList,
    });
  },
  showPicker(e) {
    const { mode } = e.currentTarget.dataset;
    this.setData({
      mode,
      [`${mode}Visible`]: true,
    });
  },
  hidePicker() {
    const { mode } = this.data;
    this.setData({
      [`${mode}Visible`]: false,
    });
  },
  getSensorData() {
    var that = this;
    myRequest.myRequest('device/sensors', {
      deviceCode: that.data.deviceCode
    }, 'get').then(function(res){
      var data = res.data.data;
      var sensorData = [];
      for (let i = 0; i < data.length; i++) {
        sensorData.push({label: data[i].name, value: data[i].transferId})
      }
      that.setData({
        sensorData: sensorData,
        'formData.dataKey': sensorData[0].value
      })
      that.getHistoryData();
      that.getHistoryData1();
      that.getSensorInfo();
    }).catch(function(res){
      console.log(res);
    })
  },
  onPicker(e) {
    var filed = e.currentTarget.dataset.filed;
    this.setData({
      [`${filed}Visible`]: true,
    });
  },
   onPickerChange(e) {
    const { key } = e.currentTarget.dataset;
    const { value, label } = e.detail;
    this.setData({
      [`${key}Visible`]: false,
      [`${key}Value`]: value,
      [`${key}Text`]: label.join(' '),
      [`formData.${key}`]: value[0],
    });
    this.getHistoryData();
    this.getHistoryData1();
    this.getSensorInfo();
  },
  onConfirm(e) {
    const { value } = e.detail;
    const { mode } = this.data;
    this.setData({
      [mode]: value,
      [`${mode}Text`]: value,
      [`formData.${mode}`]: value,
    });
    this.getHistoryData();
    this.getHistoryData1();
  },
  onCityPicker(e) {
    var filed = e.currentTarget.dataset.filed;
    console.log(filed)
    this.setData({
      [`${filed}Visible`]: true,
    });
  },
  //根据站点编号和传输id查询传感器信息
  getSensorInfo() {
    var that = this;
    myRequest.myRequest('device/sensorInfo', {
      deviceCode: that.data.deviceCode,
      dataKey: that.data.formData.dataKey,
    }, 'get').then(function(res){
      var data = res.data.data;
      that.setData({
        sensorInfo: data
      })
    }).catch(function(res){
      console.log(res);
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    this.oneComponent = this.selectComponent('#mychart-dom-line');
  },

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

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

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

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

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

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