import { Component, OnInit, AfterViewInit, OnDestroy } from '@angular/core';
import { debounceTime } from 'rxjs/operators';
import { ToolService } from 'src/app/services/tool.service';
import { MainService } from 'src/app/services/main.service';
import { Subject } from 'rxjs';
import { NzMessageService } from 'ng-zorro-antd';
import chunk from 'lodash-es/chunk';
import { Swiper, Autoplay } from 'swiper';
Swiper.use([Autoplay]);
@Component({
  selector: 'app-disinfection-supply',
  templateUrl: './disinfection-supply.component.html',
  styleUrls: ['./disinfection-supply.component.less']
})
export class DisinfectionSupplyComponent implements OnInit, OnDestroy {

  constructor(
    private mainService: MainService,
    private tool: ToolService,
    private message: NzMessageService,
  ) { }

  tasktype = null; //任务类型
  refreshTime: number = 60; //刷新时间
  screenCuttingTime: number = 10; //切屏时间

  taskTypeName:string = '';
  buildings: any[] = [];
  taskTypeList: any[] = [];
  hosId;
  onSearchOtherTaskTypeSubject = new Subject(); //搜索防抖
  searchLoading: boolean = false;
  isMask: boolean = true;
  mySwiper:Swiper;
  timer = null;
  resizeTimer = null;
  activeIndex: number = 0;

  ngOnDestroy(){
    clearTimeout(this.timer);
    clearTimeout(this.resizeTimer);
    this.mySwiper && this.mySwiper.destroy();
    window.onresize = null;
  }

  ngOnInit() {
    let _this = this;
    window.onresize = function(){
      clearTimeout(_this.resizeTimer);
      _this.resizeTimer = setTimeout(() => {
        !_this.isMask && _this.getList();
      }, 200);
    }

    this.hosId = this.tool.getCurrentHospital().id;

    this.onSearchOtherTaskTypeSubject.pipe(debounceTime(500)).subscribe((v) => {
      this.getOtherTasktype(v).then((result) => {
        this.searchLoading = false;
        if (result.status == 200) {
          this.taskTypeList = result.list;
        }
      });
    });

    this.getOtherTasktype().then((result) => {
      this.searchLoading = false;
      if (result.status == 200) {
        this.taskTypeList = result.list;
      }
    });
  }

  // 详情
  detailModel:boolean = false;
  order = {};
  toDetail(department){
    this.detailModel = true;
    this.order = department.orders ? department.orders[0] : {};
  }

  closeDetail(){
    this.detailModel = false;
  }

  swiperEnter(){
    this.mySwiper && this.mySwiper.autoplay.stop();
  }

  swiperLeave(){
    this.mySwiper && this.mySwiper.autoplay.start();
  }

  setActiveIndex(i:number){
    this.activeIndex = i;
    this.mySwiper.slideToLoop(i, 1000, false);
  }

  startGetList(){
    clearTimeout(this.timer);
    this.timer = setTimeout(() => {
      this.getList();
    }, this.refreshTime * 1000)
  }

  // 轮播
  startSwiper(){
    let _this = this;
    setTimeout(() => {
      // this.mySwiper && this.mySwiper.destroy();
      if(this.mySwiper){
        this.mySwiper.loopDestroy()
        this.mySwiper.loopCreate()
        return;
      }
      this.mySwiper = new Swiper('#mySwiper', {
        autoplay: {
          delay: this.screenCuttingTime * 1000,
          stopOnLastSlide: false,
          disableOnInteraction: false,
        },
        observer: true, //修改swiper自己或子元素时，自动初始化swiper
        observeParents: true, //修改swiper的父元素时，自动初始化swiper
        loop: true,
        pagination: {
          el: '.swiper-pagination',
          clickable: true, //轮播按钮支持点击
        },
        on: {
          slideChangeTransitionEnd: function(swiper) {
            _this.activeIndex = swiper.realIndex;
          },
          click: function(swiper, event){
            const id = (event as any).target.getAttribute('data-id');
            const screentIndex = (event as any).target.getAttribute('data-screentIndex');
            const buildingIndex = (event as any).target.getAttribute('data-buildingIndex');
            if(id !== null && screentIndex !== null && buildingIndex !== null){
              let department = _this.buildings[screentIndex][buildingIndex].departments.find(v => v.id == id);
              _this.toDetail(department);
            }
          }
        },
      });
    }, 0)
  }

  // 获取列表数据
  getList(){
    let maskFlag = this.message.loading("加载中", { nzDuration: 0 }).messageId;
    this.mainService.listMsgByMain('reserveView', {
      taskTypeId: this.tasktype
    }).subscribe((result: any) => {
      this.message.remove(maskFlag);
      const data = result.data || {};
      console.log(data);
      if(result.state == 200){
        if(Object.keys(data).length > 0){
          // 楼栋-楼层-科室-工单 转成前端可用的 楼栋-科室-工单
          let buildings = Object.keys(data)
          .map(v => ({
            id: v,
            name: Object.values(Object.values(data[v])[0])[0][0][3],
            departments: (
              Object.values(data[v]).map(vv => Object.keys(vv).map(vvv => ({id: vvv, name: vv[vvv][0][6], orders: vv[vvv], checked: false, isDisabled: vv[vvv].every(vvvv => !(vvvv[12] == 2 || (!vvvv[8] && vvvv[12] != 2 && vvvv[12] != 6 && vvvv[12] != 7 && vvvv[12] != 11)))}))) as any
            ).flat()
          }));
          console.log(buildings);
          let oItemH = 80;
          let oItemW = 464;
          let oBodyH = window.innerHeight - 289;
          let oBodyW = window.innerWidth - 46;
          let n = Math.floor(oBodyH / oItemH); //有效个数
          let n_width = Math.floor(oBodyW / oItemW); //有效个数
          if(buildings.length){
            let arr = [];
            buildings.forEach(v => {
              let item = chunk(v.departments, n).map(vv => ({id: v.id, name: v.name, departments: vv}));
              arr.push(item);
            })
            arr = chunk((arr as any).flat(), n_width);
            let m = arr[arr.length - 1].length;
            for (let index = 0; index < n_width - m; index++) {
              arr[arr.length - 1].push({});
            }
            this.buildings = arr;
            console.log(this.buildings);
            this.startSwiper();
            this.startGetList();
          }else{
            this.buildings = [];
          }
        }else{
          this.buildings = [];
        }
      }else{
        this.buildings = [];
      }
    })
  }

  // 获取其他临床服务
  getOtherTasktype(keyword?) {
    let postData: any = {
      idx: 0,
      sum: 10,
      taskType: {
        hosId: {id: this.hosId},
        taskName: keyword,
        simpleQuery: true,
        associationType: {key: "association_types", value: "other"},
      },
    };
    return this.mainService
      .getFetchDataList("configuration", "taskType", postData)
      .toPromise();
  }

  //其他临床服务任务类型
  onSearchOtherTaskType(e){
    this.searchLoading = true;
    this.onSearchOtherTaskTypeSubject.next(e);
  }

  // 确定
  saveScreen(){
    if(!this.tasktype || !this.refreshTime || !this.screenCuttingTime){
      this.message.info('请填写必选项！');
      return;
    }
    this.taskTypeName = this.taskTypeList.find(v => v.id == this.tasktype).taskName;
    this.isMask = false;
    this.getList();
  }
}
