import { Component, OnInit } from '@angular/core';
import { MyService} from '../my.service';
import { ModalService, ToastService } from 'ng-zorro-antd-mobile';
import { Router,ActivatedRoute } from "@angular/router";
import { LifeCommonService} from '../../common/life-common.service';
import { TrackQuery} from '../../domain/trackQuery';
import * as dayjs from 'dayjs';

@Component({
  selector: 'ydlife-add-task',
  templateUrl: './add-task.component.html',
  styleUrls: ['./add-task.component.scss'],
})
export class AddTaskComponent implements OnInit {
  state: any = {
    en: false,
    date: null,
    show: false,
    pickTime: false,
    now: new Date(),
    type: 'one',
    enterDirection: '',
    rowSize: 'normal',
    showShortcut: false,
    infinite: true,
    defaultValue: undefined,
    minDate: new Date(+new Date() - 5184000000),
    maxDate: new Date(+new Date() + 31536000000),
    onSelect: undefined,
  }
  addTrack:TrackQuery = new TrackQuery()
  tabList:Array<any>;
  tabType:string;
  salesActivityList:Array<any>;
  seasons:Array<any>;
  longTermList:Array<any>;
  linkToastFlag:boolean = false;
  taskInfo:any;
  constructor(private myService:MyService,private router: Router,private _modal: ModalService, private _toast: ToastService,
   public lifeCommonService:LifeCommonService,private activateRoute:ActivatedRoute) {
    this.seasons = [
      {label: '06:00',value:1},{label: '06:30',value:2},
      {label: '07:00',value:3},{label: '07:30',value:4},
      {label: '08:00',value:5},{label: '08:30',value:6},
      {label: '09:00',value:7},{label: '09:30', value:8},
      {label: '10:00',value:9},{label: '10:30',value:10},
      {label: '11:00',value:11},{label: '11:30',value:12},
      {label: '12:00',value:13},{label: '12:30',value:14},
      {label: '13:00',value:15},{label: '13:30',value:16},
      {label: '14:00',value:17},{label: '14:30',value:18},
      {label: '15:00',value:19},{label: '15:30',value:20},
      {label: '16:00',value:21},{label: '16:30',value:22},
      {label: '17:00',value:23},{label: '17:30',value:24},
      {label: '18:00',value:25},{label: '18:30',value:26},
      {label: '19:00',value:27},{label: '19:30',value:28},
      {label: '20:00',value:29},{label: '20:30',value:30},
      {label: '21:00',value:31},{label: '21:30',value:32},
      {label: '22:00',value:33},{label: '22:30',value:34},
      {label: '23:00',value:35},{label: '23:30',value:36},
      {label: '00:00',value:37}
    ];
    // console.log(this.router.getCurrentNavigation().extras.state)
    // this.taskInfo = this.router.getCurrentNavigation().extras.state;
    this.taskInfo =JSON.parse(localStorage.getItem('taskInfo'));
   }

   initPara() {
    this.state = {
      ...this.state,
      ...{
        show: false,
        date: null,
        pickTime: false,
        now: new Date(),
        type: 'one',
        rowSize: 'normal',
        infinite: true,
        enterDirection: '',
        onSelect: undefined,
        showShortcut: false,
        defaultValue: undefined,
      }
    };
  }

  ngOnInit() {
    this.addTrack.practitionerId = JSON.parse(localStorage.getItem('lifeCustomerInfo'))['practitionerId'];
    this.tabList = [{code:'bizchance_promotion_action',name:'营销',taskType:1},{code:'team_building_track',name:'增员',taskType:2},{code:'pep_schedule_task_others',name:'其他',taskType:3}];
    this.addTrack.referLeadsId = this.activateRoute.snapshot.queryParams['referLeadsId'];
    this.addTrack.referPotentialId = this.activateRoute.snapshot.queryParams['referPotentialId'];
    this.addTrack.customerId = this.activateRoute.snapshot.queryParams['customerId'];
    //查询
    if(this.taskInfo){
      for(let i=0;i<this.tabList.length;i++){
        if(this.taskInfo.taskType == this.tabList[i]['taskType']){
          this.tabType = this.tabList[i]['code'];
          this.addTrack.taskType = this.tabList[i]['taskType'];
          this.dropOptionsQuery(this.tabType);
        }
      }
      this.addTrack = {
        ...this.taskInfo,
        taskTimeFrom:[this.taskInfo.taskTimeFrom],
        taskTimeEnd: [this.taskInfo.taskTimeEnd]
      };
    }else{
        //商机页或者增员页跳转过来如果有缓存切换到缓存数据
      if(JSON.parse(sessionStorage.getItem('pageDwellDtatus'))){
        const pageDwellDtatus = JSON.parse(sessionStorage.getItem('pageDwellDtatus'))
        this.tabType = pageDwellDtatus['tabType'];
        this.addTrack.taskType =pageDwellDtatus['taskType'];
        setTimeout(() => {
          this.dropOptionsQuery(this.tabType);
          this.addTrack.mdDropOptionId = pageDwellDtatus['mdDropOptionId'];
        }, 300);
        this.addTrack.taskTimeFrom = [pageDwellDtatus['taskTimeFrom'][0]['label']?pageDwellDtatus['taskTimeFrom'][0]['label']:pageDwellDtatus['taskTimeFrom'][0]];
        this.addTrack.taskTimeEnd =  [pageDwellDtatus['taskTimeEnd'][0]['label']?pageDwellDtatus['taskTimeEnd'][0]['label']:pageDwellDtatus['taskTimeEnd'][0]];
      }else{
        //新增
        this.addTrack.mdDropOptionId = null;
        this.tabType = 'bizchance_promotion_action';
        this.addTrack.taskType = 1;
        this.dropOptionsQuery(this.tabType);
        this.addTrack.taskTimeFrom = ['08:30'];
        this.addTrack.taskTimeEnd =  ['08:30'];
      }
      //如果有日程时间就取缓存没有就默认当天
      if(sessionStorage.getItem('trackTime')){
        this.addTrack.trackTime = sessionStorage.getItem('trackTime');
      }else{
        this.addTrack.trackTime = dayjs().format('YYYY-MM-DD');
      }
    }
     
  }

  goBack(){
    // history.go(-1);
    this.router.navigate(['/todo']);
    localStorage.removeItem('taskInfo');
  }

  //判断是否选择同一个tab
  selectTab(code,taskType){
    let pageDwellDtatus = {};
    if(this.tabType == code){
       pageDwellDtatus = {
        tabType:this.tabType,
        mdDropOptionId:this.addTrack.mdDropOptionId,
        taskType:this.addTrack.taskType
      }
      sessionStorage.setItem('pageDwellDtatus',JSON.stringify(pageDwellDtatus));
    }else{
      this.tabType = code;
      this.addTrack.taskType = taskType;
      this.addTrack.mdDropOptionId = null;
      if(this.addTrack.taskType == 1 || this.addTrack.taskType == 2){
        this.addTrack.taskRoutineAtweek1 = undefined;
        this.addTrack.taskRoutineAtweek2 = undefined;
        this.addTrack.taskRoutineAtweek3 = undefined;
        this.addTrack.taskRoutineAtweek4 = undefined;
        this.addTrack.taskRoutineAtweek5 = undefined;
        this.addTrack.taskRoutineAtweek6 = undefined;
        this.addTrack.taskRoutineAtweek7 = undefined;
      }
      this.dropOptionsQuery(this.tabType);
      pageDwellDtatus = {
        tabType:this.tabType,
        mdDropOptionId:null,
        taskType:this.addTrack.taskType,
        taskTimeFrom:this.addTrack.taskTimeFrom,
        taskTimeEnd:this.addTrack.taskTimeEnd
      }
      sessionStorage.setItem('pageDwellDtatus',JSON.stringify(pageDwellDtatus));
    } 
  }

  dropOptionsQuery(code){
    this.myService.dropOptionsQuery({code:code}).subscribe((res)=>{
      if(res['success']){
        this.salesActivityList = res['data']['dropMasterInfoList'][0]['dropOptionsInfoList'];
      }
    })
  }

  onChange(result,type) {
    if(type===1){
      this.addTrack.taskTimeFrom = result;
    }
    if(type===2){
      this.addTrack.taskTimeEnd = result;
    }
    const pageDwellDtatus={
      tabType:this.tabType,
      mdDropOptionId:this.addTrack.mdDropOptionId,
      taskType:this.addTrack.taskType,
      taskTimeFrom:this.addTrack.taskTimeFrom,
      taskTimeEnd:this.addTrack.taskTimeEnd
    }
    sessionStorage.setItem('pageDwellDtatus',JSON.stringify(pageDwellDtatus));
  }

  selectTask(id){
    this.addTrack.mdDropOptionId=id;
    const pageDwellDtatus = {
      tabType:this.tabType,
      mdDropOptionId:this.addTrack.mdDropOptionId,
      taskType:this.addTrack.taskType,
      taskTimeFrom:this.addTrack.taskTimeFrom,
      taskTimeEnd:this.addTrack.taskTimeEnd
    }
    sessionStorage.setItem('pageDwellDtatus',JSON.stringify(pageDwellDtatus));
    //如果从查询页过来选了新的任务重新设置
    if(this.taskInfo){
      this.taskInfo = {
        ...this.taskInfo,
        tabType:this.tabType,
        mdDropOptionId:this.addTrack.mdDropOptionId,
        taskType:this.addTrack.taskType
      }
      localStorage.setItem('taskInfo',JSON.stringify(this.taskInfo));
    }
    
    if(this.tabType == 'bizchance_promotion_action' ){
      ModalService.alert('是否联系到商机', '', [
        { text: '否', onPress: () =>  
          this.clearRouterInfo(),
          style: {
            borderTop:'1px #ddd solid'
          }
        },
        { text: '是', onPress: () => this.jumpToLink(),
          style: {
            color: '#f8002e',
            background: '',
            borderLeft:'1px #ddd solid',
            borderTop:'1px #ddd solid'
          }
       },
      ]);
    }
    if(this.tabType == 'team_building_track'){
      ModalService.alert('是否联系到增员', '', [
        { text: '否', onPress: () =>  this.clearRouterInfo(),
          style: {
            borderTop:'1px #ddd solid'
          }
        },
        { text: '是', onPress: () => this.jumpToLink(),
          style: {
            color: '#f8002e',
            background: '',
            borderLeft:'1px #ddd solid',
            borderTop:'1px #ddd solid'
          }
       },
      ]);
    }
  }

  clearRouterInfo(){
    this.linkToastFlag=false,
    this.router.navigate(['/addtask'], {replaceUrl: true});
    this.addTrack.referLeadsId = undefined;
    this.addTrack.referPotentialId = undefined;
  }

  clickCalendar(){
    this.initPara();
    this.state.show = true;
    this.state.date = new Date();
  }

  triggerCancel() {
    this.state.show = false;
  }

  triggerConfirm(value) {
    const { startDate, endDate } = value;
    this.state = {
      ...this.state,
      ...{ show: false, startDate, endDate }
    };
    this.triggerCancel();
    this.addTrack.trackTime = dayjs(startDate).format('YYYY-MM-DD');

  }

  jumpToLink(){
    if(this.tabType == 'bizchance_promotion_action'){
      this.router.navigate(['/linkbusiness'])
    }
    if(this.tabType == 'team_building_track'){
      this.router.navigate(['/linkrecruiting'])
    }
  }

  //选择长期任务
  selectIsLongTermTask(type){
    if(type===1){
      this.addTrack.taskRoutineAtweek1 == 1?this.addTrack.taskRoutineAtweek1 = 0:this.addTrack.taskRoutineAtweek1 = 1;
    }
    if(type===2){
      this.addTrack.taskRoutineAtweek2 == 1?this.addTrack.taskRoutineAtweek2 = 0:this.addTrack.taskRoutineAtweek2 = 1;
    }
    if(type===3){
      this.addTrack.taskRoutineAtweek3 == 1?this.addTrack.taskRoutineAtweek3 = 0:this.addTrack.taskRoutineAtweek3 = 1;
    }
    if(type===4){
      this.addTrack.taskRoutineAtweek4 == 1?this.addTrack.taskRoutineAtweek4 = 0:this.addTrack.taskRoutineAtweek4 = 1;
    }
    if(type===5){
      this.addTrack.taskRoutineAtweek5 == 1?this.addTrack.taskRoutineAtweek5 = 0:this.addTrack.taskRoutineAtweek5 = 1;
    }
    if(type===6){
      this.addTrack.taskRoutineAtweek6 == 1?this.addTrack.taskRoutineAtweek6 = 0:this.addTrack.taskRoutineAtweek6 = 1;
    }
    if(type===7){
      this.addTrack.taskRoutineAtweek7 == 1?this.addTrack.taskRoutineAtweek7 = 0:this.addTrack.taskRoutineAtweek7 = 1;
    }
  }

  clickAddTask(){
    if(!this.addTrack.mdDropOptionId){
      const toast = ToastService.show('请选择您要添加的日程分类!', 0);
      setTimeout(() => {
        ToastService.hide();
      }, 3000);
      return;
    }
    if(!this.addTrack.taskTimeFrom ){
      const toast = ToastService.show('请选择任务需要的起始时间!', 0);
      setTimeout(() => {
        ToastService.hide();
      }, 3000);
      return;
    }
    if(!this.addTrack.taskTimeEnd){
      const toast = ToastService.show('请选择任务需要的结束时间!', 0);
      setTimeout(() => {
        ToastService.hide();
      }, 3000);
      return;
    }
    const  trackAdded = {
        ...this.addTrack,
        taskImportantTag:this.addTrack.taskImportantTag?1:0,
        isActive:1,
        taskTimeFrom:this.addTrack.taskTimeFrom[0]['label']?this.addTrack.taskTimeFrom[0]['label']:this.addTrack.taskTimeFrom[0],
        taskTimeEnd:this.addTrack.taskTimeEnd[0]['label']?this.addTrack.taskTimeEnd[0]['label']:this.addTrack.taskTimeEnd[0],
        mdDropOptionName:undefined
      }
    if(trackAdded.taskTimeFrom == trackAdded.taskTimeEnd){
      const toast = ToastService.show('任务起始时间不能等于结束时间!', 0);
      setTimeout(() => {
        ToastService.hide();
      }, 3000);
      return;
    }
    this.myService.addScheduleTrack(trackAdded).subscribe((res)=>{
      const toast = ToastService.show(`${res['message']}`, 0);
      setTimeout(() => {
        ToastService.hide();
      }, 3000);
      setTimeout(()=>{
        if(res['success']){
          this.router.navigate(['/todo'])
        }
      },3000)
    })
  }
}
