import { Component, OnInit, Input, Output, EventEmitter } from "@angular/core";
import { ActivatedRoute } from "@angular/router";

import { Subject } from "rxjs";
import { debounceTime } from "rxjs/operators";
import { format, addDays, addHours } from 'date-fns';
import { FormGroup, FormBuilder } from '@angular/forms';
import cloneDeep from 'lodash-es/cloneDeep'
import { MainService } from 'src/app/services/main.service';
import { ToolService } from 'src/app/services/tool.service';
@Component({
  selector: 'app-incident-ser-visit',
  templateUrl: './incident-ser-visit.component.html',
  styleUrls: ['./incident-ser-visit.component.less']
})
export class IncidentSerVisitComponent implements OnInit {
  @Input() itsmData:any;
  @Output() closeModelHs = new EventEmitter<any>();//1.组件暴露一个 EventEmitter 属性，当事件发生时，子组件利用该属性 emits(向上弹射)事件

  constructor(
    public route: ActivatedRoute,
    private mainService: MainService,
    private tool: ToolService,
    private fb: FormBuilder,
  ) {}

  listOfData: any[] = []; //表格数据
  coopId: string; //表格中执行操作的id
  hospital: string; //选中院区
  alldepart: any = []; //当前院区所属科室
  worker: number; //选择执行配送人员
  gdState: number; //选择工单状态
  gdStates: any; //工单状态列表
  overdueStates: any; //逾期查询列表
  pageIndex: number = 1; //页码
  listLength: number = 0; //总条数
  pageSize: number = 5; //每页条数

  promptContent: string; //操作提示框提示信息
  ifSuccess: boolean; //操作成功/失败
  promptInfo: string; //操作结果提示信息
  promptModalShow: boolean; //操作提示框是否展示

  btnLoading: boolean = false; //提交按钮loading状态

  tabs:any[] = [
    {key: 'all', value: '全部故障', num: 0, isRed: false},
    {key: 'callback', value: '待我回访', num: 0, isRed: false},
    {key: 'owns', value: '与我关联', num: 0, isRed: false},
  ]

  searchDTO: any = {};

  searchTimerSubject = new Subject();
  debounceSubject = new Subject(); //防抖
	maintainDept:any = []; //维修科室
	hosIds:any; //当前院区
  // 初始化增删改按钮
  coopBtns: any = {};
  // 选择tab
  queryTask:string = 'callback';//默认待我回访
  changeTab(key){
    this.queryTask = key;
		this.getDeparts();
    this.loading1 = true;
    this.debounceSubject.next(true);
  }

  ngOnInit() {
		this.hosIds = this.tool.getCurrentHospital().id
    console.log(this.itsmData)
    this.searchTimerSubject.pipe(debounceTime(500)).subscribe((v) => {
      let fun = v[0];
      fun.call(this, v[1], v[2]);
    });
    this.debounceSubject.pipe(debounceTime(500)).subscribe((v:boolean) => {
      this.getList(v);
    });
    this.coopBtns = this.tool.initCoopBtns(this.route);
    if(this.itsmData.allDuty == 1){
      this.maintainDept = this.tool.getUserInfoPermission().dutyList || [];
    }else{
      this.maintainDept = this.itsmData.checkedHos || [];
      // if(this.coopBtns.strideLook){
      //   this.defaDept()
      // }
    }
    this.getGdStates();
    this.getHospitalType();
    this.getOverdueStates();
    this.loading1 = true;
    this.debounceSubject.next(true);
  }

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

  // 获取所有的责任部门
  getMaintainDeptList(){
    let type = this.hospitalTypes.find(v => v.value == 6);
    let postData: any = {
      idx: 0,
      sum: 99999,
      hospital: {
        type: type || undefined,
      },
    };
    this.mainService.getFetchDataList("data", "hospital", postData).subscribe(result => {
      if(result.status == 200){
        this.maintainDept = result.list || [];
        // if(this.coopBtns.strideLook){
        //   this.defaDept()
        // }
      }else{
        this.maintainDept = [];
      }
    });
  }

	defaDept(){
		let itemDept = this.maintainDept.find(i=>i.id == this.hosIds)
		if(itemDept){
			this.searchDTO.maintainDepartment = itemDept.id
		}
		this.getDeparts();
	}

	// 选择维修科室
	deptChange(e){
		this.searchDTO.department = null;
		this.getDeparts();
	}

  // 搜索
  search() {
    this.loading1 = true;
    this.debounceSubject.next(true);
  }
  // 重置
  reset() {
    this.searchDTO = {};
		if(this.coopBtns.strideLook){
			this.defaDept()
		}
    this.loading1 = true;
    this.debounceSubject.next(true);
  }

  onCalendarChangeDate(dateArr){
    console.log(dateArr)
    if(dateArr.length == 2){
      let dateStart = new Date(dateArr[0]);
      let dateEnd = new Date(dateArr[1]);
      dateStart.setHours(0,0,0);
      dateEnd.setHours(23,59,59);
      this.searchDTO.dateRange = [dateStart,dateEnd];
    }
  }

  // 优先级颜色
  priorityColor(priorityId) {
    // 极低|低
    if(priorityId == 1 || priorityId == 2){
      return '';
    } else if(priorityId == 3){
      return 'yellow';
    } else if(priorityId == 4 || priorityId == 5){
      return 'red';
    }
  }
  // 处理人+协同人
  transferSynergetic(incidentData){
    let str = incidentData.groupORHandlerUser || "";
    if(incidentData.synergetic && incidentData.synergetic.length){
        str += '，' + incidentData.synergetic.map(v => v.name).join('，');
    }
    return str;
  }

  // 延期记录
  transferHandlerLog = function (currentLog) {
    if(!currentLog){
        return '无';
    }
    currentLog = cloneDeep(currentLog);
    if(currentLog.extra1DTO && currentLog.extra2 && currentLog.startTime){
        if(currentLog.extra2==0.5){
          currentLog.extra2 = 4;
          return currentLog.extra1DTO.name+"<br>"+ format(addHours(currentLog.startTime, +currentLog.extra2), "MM月dd日")+"<br>"+ format(addHours(currentLog.startTime, +currentLog.extra2), "HH时mm分前完成");
        }else{
          return currentLog.extra1DTO.name+"<br>"+ format(addDays(currentLog.startTime, +currentLog.extra2), "MM月dd日前完成");
        }
    }else{
        return '无';
    }
  }

  // 是否显示回访按钮
  computedVisit(data){
    return this.coopBtns.visit && data.state.value == 'close' && data.deleteFlag !== 1;
  }

  // 表格数据
  loading1 = false;
  getList(isInit = false) {
    let postData: any = {
      idx: isInit ? 0 : (this.pageIndex - 1),
      sum: this.pageSize,
      incident: {
        assignee: this.tool.getCurrentUserId(),
        acceptDate: (this.searchDTO.dateRange && this.searchDTO.dateRange[0]) ? format(this.searchDTO.dateRange[0], 'yyyy-MM-dd HH:mm:ss') : undefined,
        acceptDateEnd: (this.searchDTO.dateRange && this.searchDTO.dateRange[1]) ? format(this.searchDTO.dateRange[1], 'yyyy-MM-dd HH:mm:ss') : undefined,
        incidentsign: this.searchDTO.incidentsign,
        department: this.searchDTO.department ? { id: this.searchDTO.department } : undefined,
        statusId: this.searchDTO.statusId || undefined,
        todoingUser: this.searchDTO.todoingUser ? { id: this.searchDTO.todoingUser } : undefined,
        deleteFlag: 0,
        "dutyIds": this.itsmData.allDuty == 1 ? undefined : (this.itsmData.checkedHos.map(v => v.id).toString() || undefined),
        "urgentType": +this.itsmData.orderScopeRadio + 1,
      },
    };

		if(this.queryTask!='todo' && this.queryTask!='doing' && this.queryTask!='storage'){
			if(this.searchDTO.maintainDepartment){
				let itemDept = this.maintainDept.find(i=>i.id == this.searchDTO.maintainDepartment)
				postData.incident.duty = itemDept;
				delete postData.incident.dutyIds;
			}
		}

    postData.incident.queryTask = this.queryTask;

    if(this.queryTask === 'todo' || this.queryTask === 'owns'){
      postData.incident.candidateGroups = this.tool.getCurrentGroupList().map(v => v.id).toString();
    }else{
      delete postData.incident.candidateGroups;
    }

    this.loading1 = true;
    this.mainService
      .getFetchDataList("simple/data", "incident", postData)
      .subscribe((result) => {
        this.loading1 = false;
        let list = result.list || [];
        list.forEach((item) => {
          item.endDeptsName = item.endDepts ? item.endDepts.map(v => v.dept).toString() : '';
          item.computedVisitFlag = this.computedVisit(item);
        });
        this.listOfData = list;
        this.listLength = result.totalNum;
      });

    // 获取数量
    this.getCount(postData.incident);
  }

  // 调用接口-查数量
  getCount = function (incident = {}){
    let postData = {
        incidentList: [],
    }
    this.tabs.forEach(v => {
        postData.incidentList.push({...incident, ...{queryTask: v.key}});
    })
    postData.incidentList.forEach(incident => {
        // 请求参数调整
        if(!incident){
            incident = {
              "dutyIds": this.itsmData.allDuty == 1 ? undefined : (this.itsmData.checkedHos.map(v => v.id).toString() || undefined),
              "urgentType": +this.itsmData.orderScopeRadio + 1,
            };
        }

				if(incident.queryTask!='todo' && incident.queryTask!='doing' && incident.queryTask!='storage'){
					if(this.searchDTO.maintainDepartment){
						let itemDept = this.maintainDept.find(i=>i.id == this.searchDTO.maintainDepartment)
						incident.duty = itemDept;
						delete incident.dutyIds;
					}
				}

        incident.assignee = this.tool.getCurrentUserId();

        if(incident.queryTask === 'todo' || incident.queryTask === 'owns'){
          incident.candidateGroups = this.tool.getCurrentGroupList().map(v => v.id).toString();
        }else{
          delete incident.candidateGroups;
        }
    })
    this.mainService
      .getCount(postData)
      .subscribe((result) => {
        let myData = result.data || {};
        this.tabs.forEach(v => {
            v.num = myData[v.key];
        })
      });
}

  // 获取所有科室
  getDeparts(dept?) {
    let data = {
      department: {
        searchType: 1,// 简单查询
        cascadeHosId: this.searchDTO.maintainDepartment?this.searchDTO.maintainDepartment:this.tool.getCurrentHospital().id,
        dept: dept,
      },
      idx: 0,
      sum: 20,
    };
    this.isLoading = true;
    this.mainService
      .getFetchDataList("data", "department", data)
      .subscribe((data) => {
        this.alldepart = data.list;
        this.isLoading = false;
      });
  }

  // 获取工单状态
  getGdStates() {
    this.mainService.getDictionary("list", "incident_status").subscribe((data) => {
      this.gdStates = data || [];
    });
  }

  // 获取逾期查询
  getOverdueStates() {
    this.mainService.getDictionary("list", "overdue_state").subscribe((data) => {
      this.overdueStates = data || [];
    });
  }

  // 展示信息提示框（con:提示信息，success:操作是否成功，promptInfo:操作结果提示信息）
  showPromptModal(con, success, promptInfo?) {
    this.promptModalShow = false;
    this.promptContent = con;
    this.ifSuccess = success;
    this.promptInfo = promptInfo;
    setTimeout(() => {
      this.promptModalShow = true;
    }, 100);
    this.loading1 = true;
    this.debounceSubject.next(false);
  }

  // 回访-弹窗
  coopData: any = {}; //当前操作列
  visitModalShow = false; //弹窗开关
  visit(e, data) {
    e.stopPropagation();
    this.coopData = data;
    this.visitModalShow = true;
  }
  // 关闭弹窗
  closeVisitModelOrder(e) {
    this.visitModalShow = JSON.parse(e).show;
  }
  // 弹窗确定
  confirmVisitModelOrder(e){
    console.log(e);
    this.visitModalShow = false;
    this.getList(true);
  }

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

  // 科室边输边搜节流阀
  isLoading = false;
  changeInp(e) {
    this.searchTimer(this.getDeparts, e);
  }

  // 边输入边搜索节流阀
  searchTimer(fun, e, type?) {
    this.isLoading = true;
    this.searchTimerSubject.next([fun, e, type]);
  }

  // 关闭弹窗
  hideModal() {
    this.closeModelHs.emit(JSON.stringify({ show: false }));//emits(向上弹射)事件
  }
}
