import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams, AlertController, ToastController, Events } from 'ionic-angular';

import { MyActivityListPage } from '../myActivityList/myActivityList';
import { Http, Response } from '@angular/http';

import { AppService, AppGlobal } from '../../service/appHttpService';

@IonicPage()
@Component({
  selector: 'page-activityApply',
  templateUrl: 'activityApply.html',
})
export class ActivityApplyPage {

  picture: string;
  isLoad:boolean = false;
  //batches: object[];      //所有批次信息
  batches: Array<String>[];
  activity: any;          //活动信息
  onebatch:Array<String>;

  onebatchSurplusQuota: number;  //某批次剩余报名名额
  //报名订单
  order = {
    Orderid: '',         //订单id						
    Personnumber: 0,    //携带人数
    Orderbz: '',         //报名备注
    Activityid: '',      //关联活动id
    Batchid: '',        //关联批次id

    orderbz_end:''
  };
  //页面报名保存展示
  isCover: boolean = false;
  //活动详情显示
  introduce: string;
  //选中的批次的id，默认第一个id
  isSelected: string;
  //报名成功
  isSuccess: boolean = false;
  //报名失败
  isError: boolean = false;
  activityType: Array<String> = ['未知', '体检', '疗休养', '培训', '工会活动'];

  //活动须知
  noticeArry: object[];

  pageflag: boolean = false;

  constructor(public navCtrl: NavController,
    public navParams: NavParams,
    public alertCtrl: AlertController,
    public http: Http,
    public appService: AppService,
    public toast: ToastController,
    // public keyboard: Keyboard,
    public event: Events, ) {

  }

  //活动介绍限定一行17个字符串，两行57个字符串，多余以省略号代替
  subIntroduce(str: string) {
    if (!str) this.introduce = '';
    if (str.length <= 17) this.introduce = str;
    if (str.length > 17 && str.length <= 25) this.introduce = str.substr(0, 17) + "...";
    if (str.length > 25 && str.length <= 42) this.introduce = str;
    if (str.length > 42) this.introduce = str.substr(0, 42) + "...";
  }

  //初始化显示活动列表
  ngOnInit(): void {
    this.activity = this.navParams.get("item");
    
    if (this.activity.activityIMG) {
      this.picture = AppGlobal.picture + this.activity.activityIMG;
      this.isLoad = true;
    }

    this.subIntroduce(this.activity.activityIntro);  //处理活动详情字数显示问题
    //订单的活动id
    this.order.Activityid = this.activity.id;
    this.initBatchList(this.navParams.get("changeOrderInfo"));

  }

  //报名：初始化批次信息
  initBatchList(changBatchOrder) {
    this.appService.ObserverHttpGet("/wisdomgroup/modules/batch/findBatchForApp", { id: this.activity.id })
      .subscribe((res: Response) => {
        let data = res.json();
        this.batches = data;
        console.log("batches::" + this.batches);
        //增加属性：报名剩余名额,不可报名标识
        if (this.batches.length > 0) {
          this.batches.forEach(element => {
            element["onebatchSurplusQuota"] = Number(element["batchLimitNumber"]) - Number(element["hasSignUpCount"]);
            element["noRegistrationFalg"] = false;  //可报名
            element["hasOverdueflag"] = false;  //未逾期（报名已截止）
            //报名截止日期小于当前时间不可报名 
            let signflag = Date.parse(element["batchEndDate"].toString()) < Date.parse(new Date().toString());
            if (signflag || element["onebatchSurplusQuota"] <= 0) {
              element["noRegistrationFalg"] = true;  //不可报名标识
            }
            if(signflag){
              element["hasOverdueflag"] = true;  //逾期标识
            }
          });
        } else {
          this.onebatch = null;
        }

        if (changBatchOrder != null) {  //重选批次
          this.pageflag = true;
          this.order.Orderid = changBatchOrder.orderid;
          this.order.Orderbz = changBatchOrder.orderbz;

          this.order.orderbz_end = changBatchOrder.orderbz;

          this.order.Activityid = changBatchOrder.activityid;
          this.order.Batchid = changBatchOrder.batchid;
          this.order.Personnumber = changBatchOrder.personnumber;
          this.isSelected = this.order.Batchid;  //进入页面默认显示已选择的批次     
          this.onebatch = changBatchOrder.batch;  //某个批次
          //某个批次
          this.onebatch["onebatchSurplusQuota"] = Number(this.onebatch["batchLimitNumber"]) - Number(this.onebatch["hasSignUpCount"]);
          this.onebatch["noRegistrationFalg"] = false; //默认可报名
          let signflag = Date.parse(this.onebatch["batchEndDate"].toString()) < Date.parse(new Date().toString());
          if (signflag || this.onebatch["onebatchSurplusQuota"] <= 0) {
            this.onebatch["noRegistrationFalg"] = true;  //不可报名标识
          }
          if(signflag){
            this.onebatch["hasOverdueflag"] = true;  //逾期标识
          }
          console.log(this.onebatch);
          this.noticeArry =  this.strSplit(this.onebatch["batchNotice"]);

        } else { //报名
            if (this.batches.length > 0) {
              for (let index = 0; index < this.batches.length; index++) {
                if (!this.batches[index]["noRegistrationFalg"]) {
                  this.onebatch = this.batches[index]; //初始化显示 活动说明               
                  
                  this.noticeArry = this.strSplit(this.onebatch["batchNotice"]);
                  break;
                }           
              }
              //选择第一可操作的批次          
              if (this.onebatch != null) {
                this.order.Batchid = this.onebatch["id"];  //初始设置订单批次id
                this.isSelected = this.onebatch["id"];   //初始设置选中批次的id
              }else{ //默认选择第一个显示
                this.onebatch = this.batches[0];
              }   
            }else {
              this.onebatch = null;
            }        
      }
    }, error => {        
          this.appService.alert('网络异常！');    
      }   
    );
  }

  //分隔字符串
  strSplit(str):object[]{
    let temp = str.split(/[\n]/g);
        for(let i =0;i<temp.length;i++){
          if(temp[i] == ""){
              temp.splice(i, 1);
              //删除数组索引位置应保持不变
              i--;
          }
      }
      return temp;
  }


  //切换批次其对应活动说明也发生改变
  showBatchDetails(onebatchDetail) {
    console.log(onebatchDetail.batchSetAddress);
    this.onebatch = onebatchDetail;
    this.order.Batchid = this.onebatch["id"];  //改变批次时，更改工单关联的批次id
    this.isSelected = this.onebatch["id"];     //选中批次的id

    this.noticeArry = this.onebatch["batchNotice"].split("\r\n");

  }

  //携带人数 数字加减
  add() {
    console.log("1:"+this.order.Personnumber);
    console.log("2:"+this.onebatch["batchPerNumber"]);

    if(this.order.Personnumber<this.onebatch["batchPerNumber"]){
      this.order.Personnumber++;
    }
  }
  next() {
    if (this.order.Personnumber >= 1) {
      this.order.Personnumber--;
    }
  }
  //具体介绍
  hidden() {
    this.isCover = false;
  }
  show() {
    this.isCover = true;
  }

//报名
confirmOrder(orderId) {
  console.log(this.order.Personnumber + ":" + this.order.Activityid + ":" + this.order.Batchid);
  //验证信息：
  /**0.对于暂未有批次的。
    1.判断携带人数是否超过限额人数。
    2当前报名人数是否超过剩余人数。
    4.当前时间>报名截止日期
  **/
  if (this.batches.length == 0) {
    this.appService.toast("该活动还未生成批次信息");
    return;
  }
  if (this.onebatch["noRegistrationFalg"]) {
    this.appService.toast("已到报名截止日期或批次报名剩余数为0");
    return;
  } 
  
  if (this.order.Personnumber > this.onebatch["batchPerNumber"]) {
    this.appService.toast("携带人数不能超过" + this.onebatch["batchPerNumber"] + "人");
    return;
  }
  if (Number(this.order.Personnumber + 1) > this.onebatch["onebatchSurplusQuota"]) {
      this.appService.toast("报名人数超过了该批次的剩余人数");
      return;
  }
  if (orderId.length > 0) {  //我的活动：重选批次（修改）
    this.changeOrderInfo(orderId);
  } else {             //报名（新增）
    this.commitSignUpOrder();
  }
}

  //报名操作
  commitSignUpOrder() {
    console.log('报名操作');
    this.order.Orderbz = this.order.orderbz_end;
    let temp_Orderbz =  encodeURIComponent(this.order.Orderbz) ;
    this.order.Orderbz = temp_Orderbz;
    
    this.appService.ObserverHttpPost("/wisdomgroup/modules/order/create", this.order)
      .subscribe((res: Response) => {

        if (true) {
          this.isSuccess = true;
          setTimeout(() => {
            console.log("报名成功");
            this.isSuccess = false;
            //this.navCtrl.setRoot("MyActivityListPage");
            this.navCtrl.push("MyActivityListPage");
          }, 1000);
        } else {

        }
      }, error => {
        this.appService.alert('网络异常！');
      }
      );
  }

  //重选批次
  changeOrderInfo(orderId) {
    console.log('更新操作');
    this.order.Orderbz = this.order.orderbz_end;
    let temp_Orderbz =  encodeURIComponent(this.order.Orderbz) ;
    this.order.Orderbz = temp_Orderbz;
    this.appService.ObserverHttpPost("/wisdomgroup/modules/order/reelectBatchForOrder", this.order)
      .subscribe((res: Response) => {

        if (true) {
          this.isSuccess = true;
          setTimeout(() => {
            console.log("修改订单信息成功");
            this.isSuccess = false;
            this.navCtrl.push("MyActivityListPage");
          }, 1000);
        } else {

        }
      }, error => {
        this.appService.alert('网络异常！');
      }
      );
  }


  doRefresh(refresher) {
    console.log('Begin async operation', refresher);
    setTimeout(() => {
      this.ngOnInit();
      console.log('Async operation has ended');
      refresher.complete();
    }, 2000);
  }

}
