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

import { MyActivityListPage } from '../../mine/myActivityList/myActivityList';
import { Http, Response } from '@angular/http';
import { Storage } from '@ionic/storage';
import { AppService, AppGlobal } from '../../../service/appHttpService';
import {ActivityConfirmPage} from "../activityConfirm/activityConfirm";
import {MinePage} from "../../tabs/mine/mine";

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

  picture: string;
  isLoad:boolean = false;
  //batches: object[];      //所有批次信息
  batches: Array<String>[];
  activity = {
    activityName:'',
      id:''
  };          //活动信息
  item = {
      batchName:'',
      batchPerNumber:null,
      activityId:'',
      id:''
  };
  role = {
      loginName:''
  };      //角色信息
  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 storage: Storage,
    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) + "...";
  }

  //初始化显示活动列表
  ionViewDidEnter(): void {
    this.activity = this.navParams.get("activity");
    this.item = this.navParams.get('item');
    this.order.Activityid = this.activity.id;
      // //获取角色
     this.storage.get("user").then((value) => {
          this.role = value;
          console.log(this.role);
      });
  }



  //切换批次其对应活动说明也发生改变
  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);
    if(this.order.Personnumber < this.item.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() {
    
    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('网络异常！');
      }
      );
  }



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

    submitOrder(){
        this.order.Batchid = this.item.id;
        this.order.Activityid = this.item.activityId;
        this.appService.ObserverHttpPost("/wisdomgroup/modules/order/create", this.order)
            .subscribe((res: Response) => {
                    if (true) {
                        this.isSuccess = true;
                            //清空 插入
                            const index = this.navCtrl.getActive().index;
                            this.navCtrl.remove(0, index);
                            this.navCtrl.setRoot(MinePage);
                            this.navCtrl.parent.select(3);
                            this.navCtrl.push("MyActivityListPage");
                    } else {

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

}
