import { Component, OnInit } from '@angular/core';
import {Transfer} from '../service/transfer';
import {Api} from '../service/api';
import {Load} from '../service/load';
import {ActivatedRoute} from '@angular/router';

@Component({
  selector: 'v-other',
  templateUrl: './other.page.html',
  styleUrls: ['./other.page.scss'],
})
export class OtherPage implements OnInit {
  value = [false, false, false, false, false, false, false];
  yewei = 0;
  temp = 0;
  proc = 0;
  duration = 23;
  nanClicked = false;
  beiClicked = false;
  nanLoading = false;
  beiLoading = false;
  _inv;
  color;
  devices = [];
  fieldRegionNo = '';
  fieldRegionName = '';

  constructor(private tf: Transfer, private api: Api, private load: Load, private ac: ActivatedRoute) {
  }

  ngOnInit() {
    this.ac.queryParams.subscribe((data) => {
      this.fieldRegionNo = data.no;
      this.fieldRegionName = data.name;
    });
  }

  // ionic的生命周期函数
  ionViewWillEnter () {
    this.nanClicked = false;
    this.beiClicked = false;
    this.nanLoading = false;
    this.beiLoading = false;
    this.getData(1);
  }

  ionViewWillLeave() {
    clearTimeout(this._inv);
  }

  toggle(a) {
    a.loading = true;
    const req = {
      fieldDeviceNo: a.fieldDeviceNo,
      op: a.value ? 0 : 1,
      ts: new Date().getTime()
    };
    this.load.toLoad('指令已发送, 等待处理结果', true);
    this.api.control.controlSwitch([req, (data) => {
      if (data && data.code === 1) {
        this.getData(1);
        this.api.presentMsgToast(data.message);
      } else {
        a.loading = false;
        this.api.presentMsgToast(data.message);
      }
      this.load.offLoad();
    }]);
  }

  cancel() {
    this.nanClicked = false;
    this.beiClicked = false;
    this.nanLoading = false;
    this.beiLoading = false;
  }

  onLeftClick() {
    this.tf.transfer({url: '/home'});
  }

  getData(time) {
    if (time) {this.load.toLoad('加载中...', false); }
    this.api.app.getDeviceData([{fieldRegionNo: this.fieldRegionNo}, (data) => {
      if (data.constructor === Array) {
        this.devices = data;
      } else {
        this.api.presentMsgToast(data.message || '获取数据失败');
      }
      this.load.offLoad();
      this._inv = setTimeout(() => {
        this.getData(0);
      }, 30000);
    }]);

    this.api.app.getLiquidLevelData([{fieldRegionNo: this.fieldRegionNo}, (data) => {
      if (data.liquidLevel) {
        this.yewei = Number(data.liquidLevel);
        this.proc = (Number(data.liquidLevel) / (Number(data.liquidLevelMax) * 1.5)) * 100;
        this.color = Number(data.liquidLevel) > Number(data.liquidLevelMax) ||
        Number(data.liquidLevel) < Number(data.liquidLevelMin) ? 'red' : '';
      }
      if (data.temp) {
        this.temp = Number(data.temp);
      }
    }]);
  }
}
