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";
import {ActivityDetailPage} from "../activityDetail/activityDetail";

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

  picture: string;
  isLoad:boolean = false;
  //batches: object[];      //所有批次信息
  batches: Array<String>[];
  activity = {
        activityName:'',
      batchList:[],
      id:'',
      applyCount:null     //批次数量限制
  };          //活动信息
  item = {
      batchName:'',
      batchPerNumber:null,
      activityId:'',
      id:'',
      batchLimitNumber:null,
      hasSignUpCount:null
  };
  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;
      });
  }



  //切换批次其对应活动说明也发生改变
  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;
  }

  condirmAlert(){
      this.appService.alert('确定提交该活动订单？',(res)=>{
          this.confirmOrder();
      })
  }

//报名
  confirmOrder() {
  //验证信息：
  /**0.对于暂未有批次的。
    1.判断携带人数是否超过限额人数。
   leaveNum: 剩余人数
   applyNum：报名批次数量
  **/
  let leaveNum = this.item.batchLimitNumber - this.item.hasSignUpCount;
  let applyNum = 0;
  this.activity.batchList.forEach((res)=>{
        if(res.order){
            console.log(res.order);
            applyNum ++;
        }
  });
  //报名次数 applyCount 1,2,3,4,5,0-> 不限
  if(this.activity.applyCount > 0){
      if(applyNum >= this.activity.applyCount){
          this.appService.popToastView("提交失败，报名批次达到上限",'middle',1000);
          return;
      }else if (Number(this.order.Personnumber +1) > Number(leaveNum)) {
          this.appService.popToastView("报名人数超过了该批次的剩余人数",'middle',1000);
          return;
      }else{
          this.submitOrder();
      }
  } else {             //报名（新增）
    this.submitOrder();
  }
}

  //报名操作
  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) {
    setTimeout(() => {
      this.ionViewDidEnter();
      console.log('Async operation has ended');
      refresher.complete();
    }, 2000);
  }

    submitOrder(){
        // return false;


        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;
                            //清空 插入
                            this.navCtrl.push("ActivityDetailPage",{id:this.item.activityId});
                    } else {

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

}
