import { Router } from '@angular/router';
import { Component, OnInit, ViewChild, AfterViewInit } from "@angular/core";
import { MainService } from 'src/app/services/main.service';
import { TabService } from '../../services/tab.service';
import { CustomChangeDateComponent } from '../../components/custom-change-date/custom-change-date.component';
@Component({
  selector: "app-synthesize-statistics",
  templateUrl: "./synthesize-statistics.component.html",
  styleUrls: ["./synthesize-statistics.component.less"],
})
export class SynthesizeStatisticsComponent implements OnInit, AfterViewInit {
  @ViewChild('customChangeDate', { static: false }) customChangeDateComponent!: CustomChangeDateComponent;
  constructor(
    private mainService: MainService,
    private tabService: TabService,
    public router: Router,
  ) {}

	isLoading:Boolean = false;
	workData:any = []; //工单统计
  listOfData: any[] = []; //表格数据
  pageIndex: number = 1; //表格当前页码
  pageSize: number = 10; //表格每页展示条数
  listLength: number = 10; //表格总数据量
	activeIndex:any = 0;
	maintainData:any = []; //维修处理数据
	repairsOptions:any={} //报修来源 option
	malfunctionOptions:any={} //一级故障 option
	buildingOptions:any={} //楼栋报修 option
	deptCostData:any = [
		{
			name:'王'
		},
		{
			name:'王'
		},
		{
			name:'王'
		},
		{
			name:'王'
		},
		{
			name:'王'
		}
	] //科室费用
	consumableData:any = [
		{
			name:'王'
		},
		{
			name:'王'
		},
		{
			name:'王'
		},
		{
			name:'王'
		},
		{
			name:'王'
		}
	] //报修耗材

  ngOnInit() {}

  ngAfterViewInit(){
    setTimeout(() => {
      this.search();
    }, 0)
  }
	
	/*========= 数据下钻 ========*/
	
	// 汇总
	viewDetail1(){
		let query = {
			
		}
		let path = '/newStatistics/maintenanceStatistics/incidentList'
		let flag = this.tabService.tabs.some(v => v.path === path);
		flag && this.tabService.deleteRouteSnapshot(path);
		this.tabService.setQueryParams('dateRange', [this.customChangeDateComponent.startDate, this.customChangeDateComponent.endDate]);
		this.tabService.setQueryParams('defRange', this.customChangeDateComponent.defRange);
		sessionStorage.setItem('maintenanceData', JSON.stringify(query))
		this.router.navigate([path], { replaceUrl: true });
		// this.router.navigateByUrl('/newStatistics/maintenanceStatistics/incidentList')
	}
	
	// 挂起
	viewDetail2(){
		let query = {
			startDate: this.customChangeDateComponent.startDate,
			endDate: this.customChangeDateComponent.endDate,
			searchQuery:{
				isHangId: 1,
				isHangDTO:{
					id: 1,
					name: "是"
				}
			}
		}
		let path = '/newStatistics/maintenanceStatistics/incidentList'
		let flag = this.tabService.tabs.some(v => v.path === path);
		flag && this.tabService.deleteRouteSnapshot(path);
		this.tabService.setQueryParams('dateRange', [this.customChangeDateComponent.startDate, this.customChangeDateComponent.endDate]);
		this.tabService.setQueryParams('defRange', this.customChangeDateComponent.defRange);
		sessionStorage.setItem('maintenanceData', JSON.stringify(query))
		this.router.navigate([path], { replaceUrl: true });
	}
	
	// 超时
	viewDetail3(){
		let query = {
			startDate: this.customChangeDateComponent.startDate,
			endDate: this.customChangeDateComponent.endDate,
			searchQuery:{
				overtimeId: 1,
				overtimeDTO:{
					id: 1,
					name: "是"
				}
			}
		}
		let path = '/newStatistics/maintenanceStatistics/incidentList'
		let flag = this.tabService.tabs.some(v => v.path === path);
		flag && this.tabService.deleteRouteSnapshot(path);
		this.tabService.setQueryParams('dateRange', [this.customChangeDateComponent.startDate, this.customChangeDateComponent.endDate]);
		this.tabService.setQueryParams('defRange', this.customChangeDateComponent.defRange);
		sessionStorage.setItem('maintenanceData', JSON.stringify(query))
		this.router.navigate([path], { replaceUrl: true });
	}
	
	// 差评
	viewDetail4(){
		let query = {
			startDate: this.customChangeDateComponent.startDate,
			endDate: this.customChangeDateComponent.endDate,
			searchQuery:{
				evaluateId: 20424,
				evaluateDTO: {
						"id": 20424,
						"key": "incident_degree",
						"name": "不满意",
						"value": "1",
						"orders": 5,
						"extra1": "",
						"extra2": ""
				}
			}
		}
		let path = '/newStatistics/maintenanceStatistics/incidentList'
		let flag = this.tabService.tabs.some(v => v.path === path);
		flag && this.tabService.deleteRouteSnapshot(path);
		this.tabService.setQueryParams('dateRange', [this.customChangeDateComponent.startDate, this.customChangeDateComponent.endDate]);
		this.tabService.setQueryParams('defRange', this.customChangeDateComponent.defRange);
		sessionStorage.setItem('maintenanceData', JSON.stringify(query))
		this.router.navigate([path], { replaceUrl: true });
	}
	
	// 维修处理top5
	viewMaintain1(data){
		let query = {
			startDate: this.customChangeDateComponent.startDate,
			endDate: this.customChangeDateComponent.endDate,
			searchQuery:{
				statusValue: 'close',
				groupId:null,
				groupDTO:null,
				userId:null,
				userDTO:null
			}
		}
		if(this.activeIndex==0){
			query.searchQuery.userId = data.userId ? data.userId : -1
			query.searchQuery.userDTO = {
				name: data.name,
				id: data.userId
			}
			delete query.searchQuery.groupId
			delete query.searchQuery.groupDTO
		}else{
			query.searchQuery.groupId = data.groupId ? data.groupId: -1
			query.searchQuery.groupDTO = {
				groupName: data.name,
				id: data.groupId
			}
			delete query.searchQuery.userId
			delete query.searchQuery.userDTO
		}
		let path = '/newStatistics/maintenanceStatistics/incidentList'
		let flag = this.tabService.tabs.some(v => v.path === path);
		flag && this.tabService.deleteRouteSnapshot(path);
		this.tabService.setQueryParams('dateRange', [this.customChangeDateComponent.startDate, this.customChangeDateComponent.endDate]);
		this.tabService.setQueryParams('defRange', this.customChangeDateComponent.defRange);
		sessionStorage.setItem('maintenanceData', JSON.stringify(query))
		this.router.navigate([path], { replaceUrl: true });
	}
	
	viewMaintain2(data){
		let query = {
			startDate: this.customChangeDateComponent.startDate,
			endDate: this.customChangeDateComponent.endDate,
			searchQuery:{
				statusValue: 'close',
				groupId:null,
				userId:null,
				groupDTO:null,
				userDTO:null,
				overtimeId: 1,
				overtimeDTO:{
					id: 1,
					name: "是"
				}
			}
		}
		
		if(this.activeIndex==0){
			query.searchQuery.userId = data.userId ? data.userId : -1
			query.searchQuery.userDTO = {
				name: data.name,
				id: data.userId
			}
			delete query.searchQuery.groupId
			delete query.searchQuery.groupDTO
		}else{
			query.searchQuery.groupId = data.groupId ? data.groupId: -1
			query.searchQuery.groupDTO = {
				groupName: data.name,
				id: data.groupId
			}
			delete query.searchQuery.userId
			delete query.searchQuery.userDTO
		}
		let path = '/newStatistics/maintenanceStatistics/incidentList'
		let flag = this.tabService.tabs.some(v => v.path === path);
		flag && this.tabService.deleteRouteSnapshot(path);
		this.tabService.setQueryParams('dateRange', [this.customChangeDateComponent.startDate, this.customChangeDateComponent.endDate]);
		this.tabService.setQueryParams('defRange', this.customChangeDateComponent.defRange);
		sessionStorage.setItem('maintenanceData', JSON.stringify(query))
		this.router.navigate([path], { replaceUrl: true });
	}
	
	// 课科室费用top5
	viewDept(data){
		let query = {
			startDate: this.customChangeDateComponent.startDate,
			endDate: this.customChangeDateComponent.endDate,
			repairDeptId: data.repairDeptId ? data.repairDeptId : -1,
			searchQuery:{
				statusValue: 'close',
			}
		}
		let path = '/newStatistics/maintenanceStatistics/incidentList'
		let flag = this.tabService.tabs.some(v => v.path === path);
		flag && this.tabService.deleteRouteSnapshot(path);
		this.tabService.setQueryParams('dateRange', [this.customChangeDateComponent.startDate, this.customChangeDateComponent.endDate]);
		this.tabService.setQueryParams('defRange', this.customChangeDateComponent.defRange);
		sessionStorage.setItem('maintenanceData', JSON.stringify(query))
		this.router.navigate([path], { replaceUrl: true });
	}
	
	// 维修处理类型切换
	selectCheck(type){
		this.activeIndex = type
		this.getMaintainData();
	}

	// 故障来源
	repairsChart() {
		let postData:any = {
		  startDate: this.customChangeDateComponent.startDate || undefined,
      endDate: this.customChangeDateComponent.endDate || undefined,
			type: 'sourceTop5',
		  hosId: this.hosId,
		  dutyId: this.dutyId,
		  parentDutyId: this.parentDutyId,
		};
		this.mainService
		  .getReportData(postData)
		  .subscribe((result:any) => {
		    let datas = result.data.map(i=>{
					return{
						name:i.name,
						value:i.sum
					}
				});
				this.repairsOptions = {
				  tooltip: {
				    trigger: "item",
				    formatter: "{b}: {c} ({d}%)",
				  },
				  legend: {
				    data: datas,
						left: 'left',
				  },
				  series: [
				    {
				      name: "",
				      type: "pie",
				      radius: ["30%", "50%"],
							center:["50%","55%"],
				      data: datas,
							emphasis: {
								itemStyle: {
									shadowBlur: 10,
									shadowOffsetX: 0,
									shadowColor: 'rgba(0, 0, 0, 0.5)'
								}
							},
							label: {
									show: true,
									formatter: '{b}: {c} {d}%'
							},
				      itemStyle: {
				        normal: {
				          //每根柱子颜色设置
				          color: function (params) {
				            let colorList = [
				              "#33CC85",
				              "#72C0DD",
				              "#FAC958",
											"#546FC6",
											"#d35b7e",
											"#778ccC",
											"#fad354",
											"#aldee0",
											"#ee84a8",
											"#8475c5",
											"#b0d097",
											"#ffadbb",
											"#fd8c67",
											"#d495e0",
				            ];
				            return colorList[params.dataIndex];
				          },
				        },
				      },
				    },
				  ],
				};
		  });
	}

	// 一级故障
	malfunctionChart(){
		let postData:any = {
		  startDate: this.customChangeDateComponent.startDate || undefined,
      endDate: this.customChangeDateComponent.endDate || undefined,
			type: 'firstCategoryTop5',
		  hosId: this.hosId,
		  dutyId: this.dutyId,
		  parentDutyId: this.parentDutyId,
		};
		this.mainService
		  .getReportData(postData)
		  .subscribe((result:any) => {
		    let datas = []
				let title = []
				for(let i of result.data){
					datas.push(i.sum)
					title.push(i.category)
				}
				this.malfunctionOptions = {
					tooltip: {
					    trigger: 'axis',
					    axisPointer: {
					      type: 'shadow'
					    }
					  },
						grid: {
							top: '10%',
							left: '3%',  // grid布局设置适当调整避免X轴文字只能部分显示
							right: '3%', // grid布局设置适当调整避免X轴文字只能部分显示
							bottom: '6%',
							containLabel: true
						},
					  xAxis: [
					    {
					      type: 'category',
					      data: title,
					      axisTick: {
									show:false,
					        alignWithLabel: true
					      },
								axisLabel: {
									show: true, // 是否显示刻度标签，默认显示
									interval: 0, // 坐标轴刻度标签的显示间隔，在类目轴中有效；默认会采用标签不重叠的策略间隔显示标签；可以设置成0强制显示所有标签；如果设置为1，表示『隔一个标签显示一个标签』，如果值为2，表示隔两个标签显示一个标签，以此类推。
									rotate: 0, // 刻度标签旋转的角度，在类目轴的类目标签显示不下的时候可以通过旋转防止标签之间重叠；旋转的角度从-90度到90度
									inside: false, // 刻度标签是否朝内，默认朝外
									margin: 6, // 刻度标签与轴线之间的距离
								}
					    }
					  ],
					  yAxis: [
					    {
					      type: 'value',
								axisLine: {
									show:false
								},
								axisTick:{
									show:false
								}
					    }
					  ],
					  series: [
					    {
					      type: 'bar',
					      barWidth: '30%',
								color: '#FFD68D',
					      data: datas,
								label:{
									show:true,
									position: "top",  // 展示在柱子的上方
									color: "#333"
								}
					    }
					  ]
				}
		  });
	}

	// 楼栋报修
	buildingChart(){
		let postData:any = {
		  startDate: this.customChangeDateComponent.startDate || undefined,
      endDate: this.customChangeDateComponent.endDate || undefined,
			type: 'buildingTop5',
		  hosId: this.hosId,
		  dutyId: this.dutyId,
		  parentDutyId: this.parentDutyId,
		};
		this.mainService
		  .getReportData(postData)
		  .subscribe((result:any) => {
		    let datas = []
		    let title = []
		    for(let i of result.data){
		    	datas.push(i.sum)
		    	title.push(i.name)
		    }
		    this.buildingOptions = {
		    	tooltip: {
		    	    trigger: 'axis',
		    	    axisPointer: {
		    	      type: 'shadow'
		    	    }
		    	  },
						grid: {
							top: '10%',
							left: '3%',  // grid布局设置适当调整避免X轴文字只能部分显示
							right: '3%', // grid布局设置适当调整避免X轴文字只能部分显示
							bottom: '6%',
							containLabel: true
						},
		    	  xAxis: [
		    	    {
		    	      type: 'category',
		    	      data: title,
		    	      axisTick: {
		    	  			show:false,
		    	        alignWithLabel: true
		    	      },
								axisLabel: {
									show: true, // 是否显示刻度标签，默认显示
									interval: 0, // 坐标轴刻度标签的显示间隔，在类目轴中有效；默认会采用标签不重叠的策略间隔显示标签；可以设置成0强制显示所有标签；如果设置为1，表示『隔一个标签显示一个标签』，如果值为2，表示隔两个标签显示一个标签，以此类推。
									rotate: 0, // 刻度标签旋转的角度，在类目轴的类目标签显示不下的时候可以通过旋转防止标签之间重叠；旋转的角度从-90度到90度
									inside: false, // 刻度标签是否朝内，默认朝外
									margin: 6, // 刻度标签与轴线之间的距离
								}
		    	    }
		    	  ],
		    	  yAxis: [
		    	    {
		    	      type: 'value',
		    	  		axisLine: {
		    	  			show:false
		    	  		},
		    	  		axisTick:{
		    	  			show:false
		    	  		}
		    	    }
		    	  ],
		    	  series: [
		    	    {
		    	      type: 'bar',
		    	      barWidth: '30%',
		    				color: '#72C0DD',
		    	      data: datas,
								label:{
									show:true,
									position: "top",  // 展示在柱子的上方
									color: "#333"
								}
		    	    }
		    	  ]
		    }
		  });
	}

	// 科室费用
	getDeptCostData() {
	  let postData:any = {
	    startDate: this.customChangeDateComponent.startDate || undefined,
      endDate: this.customChangeDateComponent.endDate || undefined,
			type: 'deptTop5',
	    hosId: this.hosId,
	    dutyId: this.dutyId,
	    parentDutyId: this.parentDutyId,
	  };
	  this.mainService
	    .getReportData(postData)
	    .subscribe((result:any) => {
	      this.deptCostData = result.data || [];
	    });
	}

	// 耗材
	getConsumableData() {
	  let postData:any = {
	    startDate: this.customChangeDateComponent.startDate || undefined,
      endDate: this.customChangeDateComponent.endDate || undefined,
			type: 'consumableTop5',
	    hosId: this.hosId,
	    dutyId: this.dutyId,
	    parentDutyId: this.parentDutyId,
	  };
	  this.mainService
	    .getReportData(postData)
	    .subscribe((result:any) => {
				this.isLoading = false;
	      this.consumableData = result.data || [];
	    });
	}

	// 更多跳转
	toPath(path){
    let flag = this.tabService.tabs.some(v => v.path === path);
    flag && this.tabService.deleteRouteSnapshot(path);
    this.tabService.setQueryParams('dateRange', [this.customChangeDateComponent.startDate, this.customChangeDateComponent.endDate]);
    this.tabService.setQueryParams('defRange', this.customChangeDateComponent.defRange);
    this.router.navigate([path], { replaceUrl: true });
	}

  // 判断更多是否显示
  showMore(path){
    let menus = JSON.parse(localStorage.getItem("menu"));
    return menus.find(v => v.link === 'maintenanceStatistics').childrens.some(v => v.link === path);
  }

  // 初始化缓存数据
  queryType:any;
  hosId:any;
  dutyId:any;
  parentDutyId:any;
  initSessionData(){
    let newStatistics = JSON.parse(sessionStorage.getItem('newStatistics'));
    let queryType:any = newStatistics.queryType;
    let hosId:any = newStatistics.hospitalId;
    let dutyId:any = newStatistics.dutyId;

    queryType = queryType ? +queryType : undefined;
    hosId = hosId ? +hosId : undefined;
    dutyId = dutyId ? +dutyId : undefined;

    this.queryType = queryType;
    if(queryType == 1){
      this.hosId = undefined;
      this.dutyId = undefined;
      this.parentDutyId = undefined;
    }else if(queryType == 2){
      this.hosId = hosId;
      this.dutyId = undefined;
      this.parentDutyId = undefined;
    }else if(queryType == 3){
      this.hosId = undefined;
      this.dutyId = dutyId;
      this.parentDutyId = undefined;
    }else if(queryType == 4){
      this.hosId = undefined;
      this.dutyId = undefined;
      this.parentDutyId = dutyId;
    }

		this.isLoading = true
		this.getWorkData();
		this.getMaintainData();
		this.repairsChart();
		this.malfunctionChart();
		this.buildingChart();
		this.getDeptCostData();
		this.getConsumableData();
  }

  // 表格数据
  loading1 = false;
  getList(num?: number, field?: string, sort?: string) {
    if (num !== undefined) {
      this.pageIndex = num;
    }
    let postData:any = {
      idx: this.pageIndex - 1,
      sum: this.pageSize,
      startDate: this.customChangeDateComponent.startDate || undefined,
      endDate: this.customChangeDateComponent.endDate || undefined,
      hosId: this.hosId,
      dutyId: this.dutyId,
      parentDutyId: this.parentDutyId,
    };
    this.loading1 = true;
    this.mainService
      .postCustom("itsm/report", "incidentWorkOrder", postData)
      .subscribe((result) => {
        this.loading1 = false;
        this.listOfData = result.dataList || [];
        this.listLength = result.totalCount;
      });
  }

	// 头部工单数据
	getWorkData() {
	  let postData:any = {
	    startDate: this.customChangeDateComponent.startDate || undefined,
      endDate: this.customChangeDateComponent.endDate || undefined,
			type: 'headerCount',
	    hosId: this.hosId,
	    dutyId: this.dutyId,
	    parentDutyId: this.parentDutyId,
	  };
	  this.mainService
	    .getReportData(postData)
	    .subscribe((result:any) => {
	      this.workData = result.data[0] || [];
	    });
	}

	// 维修处理
	getMaintainData() {
	  let postData:any = {
	    startDate: this.customChangeDateComponent.startDate || undefined,
      endDate: this.customChangeDateComponent.endDate || undefined,
			type: 'userHandleTop5',
			groupType: this.activeIndex==0?'user':'group',
	    hosId: this.hosId,
	    dutyId: this.dutyId,
	    parentDutyId: this.parentDutyId,
	  };
	  this.mainService
	    .getReportData(postData)
	    .subscribe((result:any) => {
	      this.maintainData = result.data || [];
	    });
	}

	// 重置
	reset(){
		this.dateRange = [];
		this.activeIndex = 0;
    this.customChangeDateComponent.resetByDate();
		sessionStorage.removeItem('maintenanceData');
		setTimeout(_=>{
			this.search();
		})
	}

  // 搜索
  search() {
		this.initSessionData();
  }

  // 日期选择 日
  dateRange: any = []; //发起时间区间 天
}
