import { Component, OnInit, AfterViewInit } from "@angular/core";
import { Validators, FormGroup, FormBuilder } from '@angular/forms';
import { Subject } from 'rxjs';
import { debounceTime } from 'rxjs/operators';
import { MainService } from 'src/app/services/main.service';
import { ToolService } from 'src/app/services/tool.service';
import { NzMessageService } from 'ng-zorro-antd';
import { Router } from '@angular/router';
import { Swiper, Autoplay } from 'swiper';
Swiper.use([Autoplay]);
import chunk from 'lodash-es/chunk';

@Component({
  selector: "app-realtime-broadcast",
  templateUrl: "./realtime-broadcast.component.html",
  styleUrls: ["./realtime-broadcast.component.less"],
})
export class RealtimeBroadcastComponent implements OnInit,AfterViewInit {
  constructor(
    private fb: FormBuilder,
    private mainService: MainService,
    public tool: ToolService,
    private message: NzMessageService,
    public router: Router,
  ){}
  validateForm: FormGroup; //表单
  isMask:boolean = false; //遮罩
  changeInpSubject = new Subject(); //防抖
  showDropdown:boolean = false; //下拉
  loginUser: any = this.tool.getCurrentUserInfo(); //登录人信息

  ngOnInit(): void {
    //防抖
    this.changeInpSubject.pipe(debounceTime(500)).subscribe(({type, searchText}) => {
      // this.getHospitalList(type, searchText);
    });
    this.initForm();
  }

  ngAfterViewInit(){
    this.computedNum();
    this.getIncidentStatusList();
  }

  ngOnDestroy(){
    clearInterval(this.timer);
    this.mySwiper1pending && this.mySwiper1pending.destroy();
    this.mySwiper2handler && this.mySwiper2handler.destroy();
    this.mySwiper3overtime && this.mySwiper3overtime.destroy();
  }

  mySwiper1pending:Swiper;
  mySwiper2handler:Swiper;
  mySwiper3overtime:Swiper;
  swiperEnter(key){
    this['mySwiper' + key] && this['mySwiper' + key].autoplay.stop();
  }

  swiperLeave(key){
    this['mySwiper' + key] && this['mySwiper' + key].autoplay.start();
  }

  // 轮播
  startSwiper(type){
    let _this = this;
    this['mySwiper' + type] && this['mySwiper' + type].destroy();
    setTimeout(() => {
      this['mySwiper' + type] = new Swiper('#mySwiper' + type, {
        autoplay: {
          delay: this.config.rollingSeconds * 1000,
          // stopOnLastSlide: false,
          // disableOnInteraction: false,
        },
        observer: true, //修改swiper自己或子元素时，自动初始化swiper
        observeParents: true, //修改swiper的父元素时，自动初始化swiper
        allowTouchMove: false, //禁止触摸滑动
        // loop: true,
        // pagination: {
        //   el: '.swiper-pagination',
        //   clickable: true, //轮播按钮支持点击
        // },
        on: {
          // slideChangeTransitionEnd: function(swiper) {
          //   _this.activeIndex = swiper.realIndex;
          // },
          click: function(swiper, event){
            let parentNode = (event as any).target.closest('.list');
            let hasClass = parentNode !== null;
            if(hasClass){
              const id = parentNode.getAttribute('data-id');
              if(id !== null){
                _this.openItsmDetails({id});
              }
            }
          }
        },
      });
    }, 0)
  }

  // 定时器
  timer = null;
  num:number = 0;
  startGetList(){
    clearInterval(this.timer);
    this.timer = setInterval(() => {
      this.num--;
      if(this.num < 0){
        this.num = this.config.refreshSeconds;
        this.refreshIncidentList();
      }
    }, 1000)
  }

  // 初始化form表单
  initForm() {
    this.validateForm = this.fb.group({
      deptIds: [[], [Validators.required]],
      groupIds: [[]],
      showOvertime: [undefined, [Validators.required]],
      refreshSeconds: [30, [Validators.required]],
      rollingSeconds: [3, [Validators.required]],
    });
  }

  // 展示弹窗
  showConfig(isEdit = false){
    this.isMask = true;
    this.getHospitalType();
    if(isEdit && this.config.id){
      this.validateForm.controls.deptIds.setValue(this.config.deptIds.split(',').map(v => +v));
      this.validateForm.controls.groupIds.setValue(this.config.groupIds ? this.config.groupIds.split(',').map(v => +v) : []);
      this.config.groupList && (this.groupList = this.config.groupList);
      this.validateForm.controls.showOvertime.setValue(this.config.showOvertime);
      this.validateForm.controls.refreshSeconds.setValue(this.config.refreshSeconds);
      this.validateForm.controls.rollingSeconds.setValue(this.config.rollingSeconds);
    }
  }

  // 关闭遮罩
  hideModal(){
    this.isMask = false;
  }

  // 边输边搜节流阀
  isLoading = false;
  changeInp(type, searchText) {
    this.isLoading = true;
    this.changeInpSubject.next({type, searchText});
  }

  // 获取院区类型
  hospitalTypes:any[] = [];
  getHospitalType() {
    this.mainService.getDictionary("list", "hospital_type").subscribe((result) => {
      this.hospitalTypes = result || [];
      this.getHospitalList();
    });
  }

  // 获取维修科室
  hospitalList:any[] = [];
  getHospitalList() {
    let type = this.hospitalTypes.find(v => v.value == 6);
    let postData = {
      hospital: {
        type: type || undefined,
      },
      idx: 0,
      sum: 99999,
    };
    this.mainService
      .getFetchDataList("data", "hospital", postData)
      .subscribe((result) => {
        this.hospitalList = result.list || [];
      });
  }

  // 修改维修科室
  changeHospital(arr){
    this.getGroupList();
    this.validateForm.controls.groupIds.setValue([]);
  }

  // 打开运维分组
  openChangeGroup(flag){
    flag && this.getGroupList();
  }

  // 获取运维分组
  groupList:any[] = [];
  getGroupList() {
    if(!this.validateForm.value.deptIds.length){
      this.isLoading = false;
      this.groupList = [];
      return;
    }
    let postData = {
      group2: {
        hospitalIds: this.validateForm.value.deptIds.toString(),
        typeIds: 3,
      },
      idx: 0,
      sum: 20,
    };
    this.mainService
      .getFetchDataList("data", "group2", postData)
      .subscribe((result) => {
        this.isLoading = false;
        this.groupList = result.list || [];
      });
  }

  // 根据用户查询配置
  config:any = {};
  getConfig() {
    let postData = {
      incidentViewConfig: {
        userId: this.tool.getCurrentUserInfo().id,
      },
      idx: 0,
      sum: 1,
    };
    this.mainService
      .getFetchDataList("simple/data", "incidentViewConfig", postData)
      .subscribe((res:any) => {
        let result = res.list || [];
        if(result.length){
          this.config = result[0];
          this.num = this.config.refreshSeconds;

          // 初始化故障工单列表
          if(this.config.showOvertime == 1){
            this.incidentList['2handler'].name = '待处理（不含延期处理）';
            this.incidentList['3overtime'] = {
              name: '挂起',
              list: [],
            }
            this.getIncidentList('1pending');
            this.getIncidentList('2handler');
            this.getIncidentList('3overtime');
          }else{
            this.incidentList['2handler'].name = '待处理';
            delete this.incidentList['3overtime'];
            this.getIncidentList('1pending');
            this.getIncidentList('2handler');
          }
        }else{
          this.config = {};
          this.showConfig();
        }
      });
  }
  // 计算可视区范围展示信息的条数
  pageSize = 0;
  computedNum(){
    let h = (document.querySelector('.lists_box') as HTMLElement).offsetHeight;
    this.pageSize = Math.floor((h / 145));
  }

  // 刷新故障工单列表
  refreshIncidentList() {
    if(this.config.showOvertime == 1){
      this.getIncidentList('1pending');
      this.getIncidentList('2handler');
      this.getIncidentList('3overtime');
    }else{
      this.getIncidentList('1pending');
      this.getIncidentList('2handler');
    }
  }

  // 获取故障工单状态
  incidentStatusList:any[] = [];
  getIncidentStatusList() {
    this.mainService.getDictionary("list", "incident_status").subscribe((result) => {
      this.incidentStatusList = result || [];
      this.getConfig();
    });
  }

  // 获取故障工单列表
  loading:boolean = false;
  incidentList:any = {
    '1pending': {
      name: '待接单',
      list: [],
    },
    '2handler': {
      name: '待处理',
      list: [],
    },
    // '3overtime': {
    //   name: '挂起',
    //   list: [],
    // }
  }
  getIncidentList(type: string) {
    this.loading = true;
    let postData: any = {
      idx: 0,
      sum: 99999,
      incident: {
        deleteFlag: 0,
				candidateGroups: this.config.groupIds ? this.config.groupIds.toString() : undefined,
				dutyIds: this.config.deptIds.toString(),
        queryTask: 'queryAll',
      },
    };
    if(type == '1pending'){
      postData.incident.statusId = this.incidentStatusList.find(v => v.value === 'pending').id;
    }else if(type == '2handler'){
      postData.incident.statusId = this.incidentStatusList.find(v => v.value === 'handler').id;
      postData.incident.overtime = this.config.showOvertime == 1 ? 0 : undefined;
    }else if(type == '3overtime'){
      postData.incident.statusId = this.incidentStatusList.find(v => v.value === 'handler').id;
      postData.incident.overtime = 1;
    }
    this.mainService
      .getFetchDataList("simple/data", "incident", postData)
      .subscribe((res:any) => {
        this.loading = false;

        let list = res.list || [];
        this.incidentList[type].list = chunk(list, this.pageSize);
        // console.log(this.incidentList)

        this.startSwiper(type);
        this.startGetList();
      });
  }

  // 优先级颜色
  priorityColor(priorityId) {
    // 极低|低
    if(priorityId == 1 || priorityId == 2){
      return '';
    } else if(priorityId == 3){
      return 'yellow';
    } else if(priorityId == 4 || priorityId == 5){
      return 'red';
    }
  }

  // 保存
  btnLoading:boolean = false;
  submitForm(){
    for (const i in this.validateForm.controls) {
      this.validateForm.controls[i].markAsDirty({ onlySelf: true });
      this.validateForm.controls[i].updateValueAndValidity();
    }
    if (this.validateForm.invalid) return;
    this.btnLoading = true;
    let postData = {
      id: this.config.id || undefined,
      hosId: this.tool.getCurrentHospital().id,
      userId: this.tool.getCurrentUserInfo().id,
      deptIds: this.validateForm.value.deptIds.toString(),
      groupIds: this.validateForm.value.groupIds.toString() || undefined,
      showOvertime: this.validateForm.value.showOvertime,
      refreshSeconds: this.validateForm.value.refreshSeconds,
      rollingSeconds: this.validateForm.value.rollingSeconds,
    }
    this.mainService
      .simplePost("addData", "incidentViewConfig", postData)
      .subscribe((data) => {
        this.btnLoading = false;
        this.hideModal();
        if (data.status == 200) {
          this.showDropdown = false;
          this.message.success("保存成功");
          this.getConfig();
        } else {
          this.message.error(data.msg || '保存失败');
        }
      });
  }

  // 详情-弹窗
  detailModalShow = false; //弹窗开关
  coopData:any = {};
  openItsmDetails(data) {
    this.coopData = data;
    this.detailModalShow = true;
  }
  // 关闭弹窗
  closeDetailModelOrder(e) {
    this.detailModalShow = JSON.parse(e).show;
  }
  // 弹窗确定
  confirmDetailModelOrder(e){
    console.log(e);
    this.detailModalShow = false;
  }

  // 回到系统管理
  toMain() {
    this.router.navigateByUrl("main");
  }

  // 退出
  logOut(): void {
    // 假退出
    let hospital = this.tool.getCurrentHospital();
    if(hospital){
      this.router.navigate(["login", hospital.id]);
    }else{
      this.router.navigateByUrl("login");
    }
    localStorage.removeItem("user");
    localStorage.removeItem("menu");
    localStorage.removeItem("index");

    // 假退出
    this.mainService.logOut().subscribe((data) => {
      if (data.status == 200) {
        if(hospital){
          this.router.navigate(["login", hospital.id]);
        }else{
          this.router.navigateByUrl("login");
        }
        localStorage.removeItem("user");
        localStorage.removeItem("menu");
        localStorage.removeItem("index");
      }
    });
  }

  // 处理人+协同人
  transferSynergetic(incidentData){
    let str = incidentData.groupORHandlerUser || "";
    if(incidentData.synergetic && incidentData.synergetic.length){
        str += '，' + incidentData.synergetic.map(v => v.name).join('，');
    }
    return str;
  }
}
