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

@Component({
  selector: 'v-search',
  templateUrl: './search.page.html',
  styleUrls: ['../home/home.page.scss', './search.page.scss'],
})
export class SearchPage implements OnInit {

  data = [];
  items = [];
  noData = false;
  historys = JSON.parse(window.localStorage.getItem('history.home.search')) || [];
  text = '';
  v: any;

  @Input()
  get value(): any {
    return this.v;
  }
  set value(v: any) {
    this.search(v);
  }
  @Output() valueChange = new EventEmitter();

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

  ngOnInit() {
    this.getData();
  }

  search(v) {
    this.text = v;
    this.items = this.data.filter(o => o.name.indexOf(v) > -1);
    this.checkItem();
  }

  checkItem() {
    if (this.items.length === 0) {
      this.noData = true;
    } else {
      this.noData = false;
    }
  }

  getData() {
    this.api.app.getAll(['', (data) => {
      if (data && data.constructor === Array) {
        const obj = [];
        data.map((value, index) => {
          const itemInfo = {
            name: value.fieldRegionName,
            no: value.fieldRegionNo,
            yewei: value.liquidLevel,
            temp: value.temp,
            img: this.getImgName(value.fieldRegionName),
            url: value.fieldRegionGroup === '中转池自动控制组' ? 'east' : 'other',
            time: new Date().getTime(),
            state: value.state
          };
          obj.push(itemInfo);
        });
        this.data = obj;
      } else {
        this.api.presentMsgToast('获取数据失败');
      }
      this.checkItem();
    }]);
  }

  getImgName(name) {
    let ret = 'fajiao.jpg';

    switch (name) {
      case '东中转池':
        ret = 'e.jpg';
        break;
      case '西中转池' :
        ret = 'w.jpg';
        break;
      case '发酵池' :
        ret = 'fajiao.jpg';
        break;
      case '分离池' :
        ret = 'fenli.jpg';
        break;
      case '匀浆池' :
        ret = 'yunjiang.jpg';
        break;
      case '出料池' :
        ret = 'chuliao.jpg';
        break;
      case '沉沙池' :
        ret = 'chensha.jpg';
        break;
      default:
        break;
    }

    return ret;
  }

  toControl(url, name, no) {
    if (this.text) {
      if (this.historys.length >= 10) {
        this.historys.pop();
      }
      if (this.historys.filter(item => item === this.text).length === 0) {
        this.historys.push(this.text);
        window.localStorage.setItem('history.home.search', JSON.stringify(this.historys));
      }
    }
    const query = '?name=' + name + '&no=' + no;
    this.tf.transfer({
      url: '/' + url,
      query: query,
      hash: ''
    });
  }

  choose(e) {
    this.valueChange.emit(e);
  }
}
