import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import { Response } from '@angular/http';
import { Storage } from '@ionic/storage';
import { AppService } from '../../service/appHttpService';
import { ChooseAddressPage }  from '../chooseAddress/chooseAddress';

import { OutGoingReportEditPage } from '../outGoingReportEdit/outGoingReportEdit';


@IonicPage()
@Component({
  selector: 'page-outGoingReportDetail',
  templateUrl: 'outGoingReportDetail.html'
})

export class OutGoingReportDetailPage {

  //临时个人报备
  temp_userpre = {
    id: '',
    leaveDate : '',
    backDate : '',
    managerDesc : '',
    outaddressids : '',
    managerId: '',
    areaName : '',
    entTime : '',
    premanagerImg: '',
    premanagerIntroduce:''
  }
  //地点id,多个之间用逗号分隔
  addressid = "";

  //离沪地点显示
  locations : any;

  //报备实体
  premanager;

  //选择的所有地点
  allselectedCity:Array<String> = [];

  temp_city:Array<String> = [];

  constructor(
    public navCtrl: NavController,
    public navParams: NavParams,
    public appService: AppService,
    public storage: Storage
  ) {
    //当前页面---个人报备页面2 （临时存储离沪数据）

    //个人报备1——> 个人报备2页面
    this.premanager = this.navParams.get("premanager");  
    
    this.storage.set('premanager',this.premanager);
    
    if(this.premanager!=null ){
        if(this.premanager["reserve1"]!=null && this.premanager["reserve2"]!=null){
            //原来方法：this.newLeave.dateStart=new Date().toISOString();会误差8个小时，以下方法是个简单处理技巧，仅限中国地区使用 +8*60*60*1000
          this.temp_userpre.leaveDate=new Date(this.premanager["reserve1"]).toISOString();//假期开始时间
          this.temp_userpre.backDate=new Date(this.premanager["reserve2"]).toISOString();//假期结束时间
        }

        this.temp_userpre.managerId = this.premanager.id;
        //报备截至时间
        this.temp_userpre.entTime = this.premanager.endTime;
        this.temp_userpre.premanagerImg = this.premanager.uploadPic;
        this.temp_userpre.premanagerIntroduce = this.premanager.managerDesc;
         //编辑初始化：查询
        if(this.premanager["reported"]){//已报备
            this.appService.ObserverHttpPost("/wisdomgroup/modules/userpre/getUserpre",{premanagerId:this.premanager.id.toString()})
                .subscribe((res: Response) => {
                let result = res.json();
                this.temp_userpre.id = result.id;     //临时-id 
                if(result.isorFromsh == 1){ //离沪
                  this.temp_userpre.managerDesc = result.userpreDesc;
                  this.temp_userpre.leaveDate = result.formshTime;
                  this.temp_userpre.backDate = result.comeshTime;   
                  this.allselectedCity = result.areaList;   //地点回显
                  //将原保存的地点放入storage中
                  this.storage.set("cityList",this.allselectedCity);
                } 
              }, error => {        
                  this.appService.alert('网络异常！');    
              }   
            );
        }
    }else{
        //报备
    }
   
    //这个操作是拿出放在storage中城市地点的集合放在 当前页面的临时temp_city中
    this.storage.get("cityList").then((value)=>{
        if(value != null && value != ''){
           this.temp_city = value;
           this.allselectedCity = this.temp_city;      
        }
        this.storage.get("city").then((value)=>{
          if(value != null && value != ''){
            //对每选择一个city都放在临时变量中再保存一次
            this.temp_city.push(value);        
            this.storage.set('cityList',this.temp_city);
            this.allselectedCity =  this.temp_city;
          }
          this.storage.remove("city");
       });
    });

     //地点城市页面 到 个人报备2（本页面） 页面
     //get的目的是在地点城市页面到 个人报备2（此页面）数据仍然存在
     this.storage.get("temp_userpre").then((value)=>{
          if(value != null && value != ''){
            this.temp_userpre = value;
          }
     });


  }

  ngOnInit():void{



  }

  //添加地点
  addAddress(){

    this.storage.remove('city');

    this.storage.set('temp_userpre',this.temp_userpre);

    this.navCtrl.push("ChooseAddressPage");

    
  }

  //删除地点
  deleteAddress(city){  
    let index_city = 0;
    for (let index = 0; index < this.allselectedCity.length; index++) {
      const element = this.allselectedCity[index];
      if(element["id"] == city ) {
        index_city = index;
      }                
    }
    this.allselectedCity.splice(index_city,1);
    this.storage.remove("cityList");   
    this.storage.set('cityList',this.allselectedCity); 
  }

  //个人报备2  --> 个人报备1 页面
  //保存 按钮
  //将该页面值带入个人报备1页面 进行统一的个人报备
  saveFieldValue(){ 

      //1.离沪时间和回沪时间不能为空
      if((this.temp_userpre.leaveDate == null || this.temp_userpre.leaveDate == '') 
         ||( this.temp_userpre.backDate == null || this.temp_userpre.backDate == '')){
          this.appService.alert("日期不能为空");
          return false;
      } 

      //2.判断回沪日期和离沪日期
      let dateflag = Date.parse(this.temp_userpre.leaveDate.toString()) > Date.parse(this.temp_userpre.backDate.toString());
      if(dateflag){
          this.appService.alert("回沪日期应大于回沪日期");
          return false;
      }
      //3.离沪地点不能为空
      if(this.allselectedCity != null && this.allselectedCity.length>0){
           if( this.allselectedCity != null &&  this.allselectedCity.length > 0){
                this.addressid = '';
                this.locations  = '';
                for (let index = 0; index < this.allselectedCity.length; index++) {
                  const element = this.allselectedCity[index];
                  this.addressid +=  element["id"]+",";    
                  this.locations +=  element["areaName"]+",";                       
                }
                this.addressid = this.addressid.substring(0,this.addressid.lastIndexOf(","));
                this.locations = this.locations.substring(0,this.locations.lastIndexOf(","));
                this.temp_userpre.outaddressids = this.addressid;
                this.temp_userpre.areaName = this.locations;
            }
      }else{
        this.appService.alert("离沪地点不能为空");
        return false;
      }
      
      //this.storage.remove('temp_userpre');
      
      this.storage.set('temp_userpre',this.temp_userpre);
      this.navCtrl.push("OutGoingReportEditPage");

  }
}
