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

@Component({
  selector: 'ydlife-todo-list',
  templateUrl: './todo-list.component.html',
  styleUrls: ['./todo-list.component.scss']
})
export class TodoListComponent implements OnInit {
  weekArr: Array<any>;
  taskList:Array<any> = [];
  taskTimeList:Array<any> = [];
  trackTime:string;
  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,
  }
  practitionerId:number;
  //日程是否可修改
  editFlag:boolean = true;
  localTime:any = new Date().getTime();
  constructor(public lifeCommonService: LifeCommonService,private myService:MyService,
    private _modal: ModalService, private _toast: ToastService,private router:Router) {
    this.taskTimeList = [
      {id:1,time:'6:00'},
      {id:2,time:'7:00'},
      {id:3,time:'8:00'},
      {id:4,time:'9:00'},
      {id:5,time:'10:00'},
      {id:6,time:'11:00'},
      {id:7,time:'12:00'},
      {id:8,time:'13:00'},
      {id:9,time:'14:00'},
      {id:10,time:'15:00'},
      {id:11,time:'16:00'},
      {id:12,time:'17:00'},
      {id:13,time:'18:00'},
      {id:14,time:'19:00'},
      {id:15,time:'20:00'},
      {id:16,time:'21:00'},
      {id:17,time:'22:00'},
      {id:18,time:'23:00'},
      {id:19,time:'00:00'},
    ]   
  }
  
  ngOnInit() {
    this.practitionerId = JSON.parse(localStorage.getItem('lifeCustomerInfo'))['practitionerId'];
    this.weekArr = this.lifeCommonService.makeDate();
    if(sessionStorage.getItem('trackTime')){
      this.trackTime = sessionStorage.getItem('trackTime');
      this.weekArr = this.lifeCommonService.makeDate(this.trackTime);
      //选中时间<当前时间
      if((new Date((this.trackTime + ' 23:59').replace(/-/g,'/')).getTime())<this.localTime){
        this.editFlag = false;
      }else{
        this.editFlag = true;
      }
    }else{
      //初始化追踪时间为今天
      this.trackTime = dayjs().format('YYYY-MM-DD');
    }
    this.queryScheduleTrackList();
  }

  setBackground(item){
    let bcConfig = {}
    if(item.taskType == 1){
      bcConfig = {
        'background-color': '#ff908d'
      }
    }else if(item.taskType == 2){
      bcConfig = {
        'background-color': '#ffc28d'
      }
    }else if(item.taskType == 3){
      bcConfig = {
        'background-color': '#72c9cd'
      }
    }
    return bcConfig;
  }

  goBack(){
    // history.go(-1)
    //离开页面清除上次缓存的时间
    sessionStorage.removeItem("trackTime");
    this.router.navigate(['/my']);
  }

  selectDay(weekItem){
    this.trackTime =  weekItem['date'];
    //缓存任务时间
    sessionStorage.setItem('trackTime',this.trackTime);
    this.queryScheduleTrackList();
    //选中时间<当前时间
    if((new Date((this.trackTime + ' 23:59').replace(/-/g,'/')).getTime())<this.localTime){
      this.editFlag = false;
    }else{
      this.editFlag = true;
    }
  }

  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,
      }
    };
  }

  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.trackTime =dayjs(startDate).format('YYYY-MM-DD');
    //缓存任务时间
    sessionStorage.setItem('trackTime',this.trackTime);
    this.queryScheduleTrackList();
    this.weekArr = this.lifeCommonService.makeDate(startDate);
    //选中时间<当前时间
    if((new Date((this.trackTime + ' 23:59').replace(/-/g,'/')).getTime())<this.localTime){
      this.editFlag = false;
    }else{
      this.editFlag = true;
    }
  }

  queryScheduleTrackList(){
    this.myService.queryScheduleTrackList({practitionerId:this.practitionerId,trackTime:this.trackTime}).subscribe((res)=>{
      if(res['success']){
        this.taskList = res['data']['dataList'];
      }else{
        this.taskList = [];
      }
    })
  }

  //删除日程
  deleteScheduleTrackById(taskItem){
      ModalService.alert('删除该项日程', '', [
        { text: '取消', onPress: () => console.log('取消') },
        { text: '确定', onPress: () => 
          this.myService.deleteScheduleTrackById({scheduleTrackId:taskItem.id,taskType:taskItem.taskType}).subscribe((res)=>{
            if(res['success']){
              this.queryScheduleTrackList();
            }else{
              const toast = ToastService.show(`${res['message']}`, 0);
              setTimeout(() => {
                ToastService.hide();
              }, 3000);
            }
          })  
        }
      ]);
  }

  editeTask(taskInfo,type){
    if(type == 'edit'){
      if(this.editFlag == true){
        this.router.navigate(['/addtask'], {state:taskInfo});
        localStorage.setItem('taskInfo',JSON.stringify(taskInfo))
      }else{
        const toast = ToastService.show('不可以修改今天之前的日程哦！', 0);
          setTimeout(() => {
            ToastService.hide();
          }, 3000);
      }
    }else{
      this.deleteScheduleTrackById(taskInfo);
    }
  }

  //新增的时候清空编辑缓存
  removeTaskInfo(){
    localStorage.removeItem('taskInfo');
    sessionStorage.removeItem('pageDwellDtatus');
  }

  replaceStr(phone){
    let reg = /^(\d{3})\d{4}(\d{4})$/
    return phone.replace(reg, '$1****$2')
  }
  
}
