import { Component, ViewChild } from '@angular/core';
import { IonicPage, NavController, Slides } from 'ionic-angular';

import {  Response } from '@angular/http';

import { AppService } from '../../../service/appHttpService';
import { ActivityConfirmPage } from '../../activity/activityConfirm/activityConfirm';
import { JoinPersonsPage } from '../../joinPersons/joinPersons';

import { ActivityStatisticService } from '../../../service/activityStatisticService';
import {OrderDetailPage} from "../../activity/order-detail/order-detail";
import {OrderEditPage} from "../../activity/order-edit/order-edit";
import {ActivityDetailPage} from "../../activity/activityDetail/activityDetail";



declare var Swiper;
@IonicPage()
@Component({
  selector: 'page-myActivityList',
  templateUrl: 'myActivityList.html',
})
export class MyActivityListPage {

  swiper: any;
  
  allOrder: Array<String> = [];           //全部订单
  waitGoOrder: Array<String> = []        //待出行
  waitSureOrder: Array<String> = [];      //待确认

  isCover: boolean = false; //是否显示弹出框
  first: boolean = false;  //第一层弹框
  second: boolean = false;  //第二层弹框
  third: boolean = false;  //第三层弹框
  fourth: boolean = false; //第四层弹框
  isSuccess: boolean = false; //是否提交成功
  isError: boolean = false; //是否提交失败


  order = {
    orderfgconent:'',
  };  //确认评价的订单

  //活动类型
  activityType: Array<String> = ['未知', '体检', '疗休养', '培训', '工会活动'];
  //参加人员类型（活动发布对象）
  activityFbObject: Array<String> = ['未知', '全体人员', '用户组', '处事部门'];

  //ViewChild传入一个字符串contentSlides，变量contentSlides接收。其它不变  
  @ViewChild('contentSlides') contentSlides: Slides;
  menus: Array<string> = ['活动订单', '待进行', '待确认'];

  waitgoOrderCount = 0;
  waitsureOrderCount = 0;

    swiperIndex = 0;

  constructor(
    public navCtrl: NavController,
    public appService: AppService,
    //public flushRef: ChangeDetectorRef
    public activityStatisticService:ActivityStatisticService
  ) {

  }
  //当页面加载的时候触发，只触发一次，当有缓存的的时候，打开页面时不在加载  
  ionViewDidLoad() {

  }
  //选择菜单  
  selectPageMenu(index) {
      this.swiperIndex = index;
    //切换页面  
  }



  //初始化加载我的全部活动
  ionViewDidEnter(): void {
    this.initAllMyActivityOrder();
  }

  ionViewWillEnter(){
    this.activityStatisticService.myActivityOrderCount((data)=>{
     this.waitgoOrderCount = data.waitgoOrder;
     this.waitsureOrderCount = data.waitSureOrder;      
   });
 }

  initAllMyActivityOrder() {
    this.appService.ObserverHttpPost("/wisdomgroup/modules/order/searchAllOrder", null)
      .subscribe((res: Response) => {
          let data = res.json();
          console.log("activityOrderListData------->", data);
          this.allOrder = data;
        this.allOrder.forEach(element => { //待出行
          //添加属性
          //针对待出行的状态订单处理：批次报名截止日小于当前时间只显示按钮：参与人员
          if (element["orderstate"] == '1') {
            element["showParticipantBtn"] = false;
            let signflag =  Date.parse(element["batch"].batchEndDate.toString())<Date.parse(new Date().toString());
            console.log("signflag:"+signflag);
            if(signflag){
              element["showParticipantBtn"] = true;  //显示参与人员按钮标识
            } 
            this.waitGoOrder.push(element);
          }
          if (element["orderstate"] == '2') {  //待确认
            this.waitSureOrder.push(element);
          }
      });
      }, error => {
      }
      );
  }

  //取消报名（订单）
  sureCancelOrder(orderid): void {
    this.appService.alert('确定取消报名吗？', res => {
      this.cancelOrder(orderid);
    });
  }

  cancelOrder(orderid): void {
    this.appService.ObserverHttpGet("/wisdomgroup/modules/order/deleteOrder", { "id": orderid })
      .subscribe((res: Response) => {
        //let data = res.json();
          this.appService.alert('报名已取消！');    
          for (let index = 0; index < this.allOrder.length; index++) {
             if(this.allOrder[index]["orderid"].indexOf(orderid)>-1){
              this.allOrder.splice(this.allOrder[index]["orderid"].indexOf(orderid),1); 
            }
          }
          for (let index = 0; index < this.waitGoOrder.length; index++) {
              if(this.waitGoOrder[index]["orderid"].indexOf(orderid)>-1){
              this.waitGoOrder.splice(this.waitGoOrder[index]["orderid"].indexOf(orderid),1); 
            }
          }
          this.waitgoOrderCount =  this.waitGoOrder.length;
          //this.allOrder.splice(this.allOrder.indexOf(orderid),1)   
          //console.log("b:"+this.allOrder);    
          //this.waitGoOrder.splice(this.waitGoOrder.indexOf(orderid),1) 
          //this.waitgoOrderCount =  this.waitGoOrder.length;

        }, error => {        
        }
      );
  }

  //更新订单）
  reelectBatch(item): void {
      this.navCtrl.push('ActivityDetailPage',{id:item.activityid});
  }

  //跳转人员参与情况列表页面
  joinPeople(order) {
    this.navCtrl.push("JoinPersonsPage",{
      batchid:order.batchid,
      batch:order.batch,
    });
  }

  
  //确认评价按钮,第一层弹框
  evaluation(item) {
    
    this.isCover =true;
    this.first =true;
    this.order["orderid"] =  item["orderid"];
    this.order["batchid"] =  item["batchid"];
    this.order["activityid"] =  item["activityid"];
    this.order["orderstate"] = '2';  //确认状态

    this.order["personnumber"] =  item["personnumber"]; //携带人数
    this.order["orderbz"] =  item["orderbz"];  //备注说明

  }


  //第二层弹框，参加
  yes() {
    this.first = false;
    this.second = true;
  }

  //第三层弹框，未参加
  no() {
    this.first = false;
    this.third = true;
  }

  //确定未参加
  sure() {
    this.third = false;
    this.isCover = false;
    //未出行（更改订单状态为：报名未出行；确认方式为app）  
    this.order["orderstate"] = '3';  //报名未出行
    this.order["orderconfirm"] = '1' ;  //手机app确认
    
    this.appService.ObserverHttpPost("/wisdomgroup/modules/order/confirmEvaluationOrder",this.order)
    .subscribe((res: Response) => {
        let resultback = res.json();
        if(resultback.status == '200'){
             //待确认列表移除，全部列表移除该订单
            let orderid = this.order["orderid"];
            //this.allOrder.splice(this.allOrder.indexOf(orderid),1)    
            //this.waitSureOrder.splice(this.waitSureOrder.indexOf(orderid),1) 

            for (let index = 0; index < this.allOrder.length; index++) {
              if(this.allOrder[index]["orderid"].indexOf(orderid)>-1){
               this.allOrder[index]["orderstate"] = '3';
               this.allOrder[index]["orderconfirm"] = '1';
             }
            }
            
            for (let index = 0; index < this.waitSureOrder.length; index++) {
                if(this.waitSureOrder[index]["orderid"].indexOf(orderid)>-1){
                this.waitSureOrder.splice(this.waitSureOrder[index]["orderid"].indexOf(orderid),1); 
              }
            }
            this.waitsureOrderCount = this.waitSureOrder.length;
        }else{
          //失败
        }             
      }, error => {        
      }
    );
  }

  //否定为参加，跳到第一层
  not() {
    this.third = false;
    this.first = true;
  }

  //no是对应的满意度，跳转到第四层
  next(no: number) {
    this.second = false;
    this.fourth = true;
    this.order["orderpjlevel"] = no; //满意度评价等级
  }

  //提交建议 (确认出行)
  commit(){
    //确认出行：更改订单状态为完成，订单满意度评价，意见，确认方式
    this.order["orderstate"] = '4';  //已完成
    this.order["orderconfirm"] = '1' ;  //手机app确认
    console.log("ordervalue:"+this.order);
    this.appService.ObserverHttpPost("/wisdomgroup/modules/order/confirmEvaluationOrder",this.order)
    .subscribe((res: Response) => {
        let resultback = res.json();
        if(resultback.status == '200'){
             //待确认列表移除，全部列表移除该订单
            let orderid = this.order["orderid"];
            //this.allOrder.splice(this.allOrder.indexOf(orderid),1) 
            //this.waitSureOrder.splice(this.waitSureOrder.indexOf(orderid),1)  
            for (let index = 0; index < this.allOrder.length; index++) {
              if(this.allOrder[index]["orderid"].indexOf(orderid)>-1){

               this.allOrder[index]["orderstate"] = '4';
               this.allOrder[index]["orderconfirm"] = '1';
               this.allOrder[index]["orderpjlevel"] =  this.order["orderpjlevel"];
               this.allOrder[index]["orderfgconent"] = this.order["orderfgconent"];

             }
            }
            for (let index = 0; index < this.waitSureOrder.length; index++) {
                if(this.waitSureOrder[index]["orderid"].indexOf(orderid)>-1){
                this.waitSureOrder.splice(this.waitSureOrder[index]["orderid"].indexOf(orderid),1); 
              }
            }
            this.waitsureOrderCount = this.waitSureOrder.length;
            if(true){
              this.fourth =false;
              this.isSuccess=true;
              setTimeout(() => {
                this.isCover=false;
                this.isSuccess=false;
              }, 2000);
            }
            
        }else{
          //失败
        }             
      }, error => {        
      }
    );
  }

  //跳转到确认活动页面
  goConfirmActivity(item) {
          this.navCtrl.push('OrderDetailPage',{item:item});
  }

  goBack(){
    this.navCtrl.popToRoot();
  }


}
