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-distribution-synthesize-statistics",
  templateUrl: "./distribution-synthesize-statistics.component.html",
  styleUrls: ["./distribution-synthesize-statistics.component.less"],
})
export class DistributionSynthesizeStatisticsComponent implements OnInit, AfterViewInit {
  @ViewChild('customChangeDate', { static: false }) customChangeDateComponent!: CustomChangeDateComponent;
  constructor(
    private mainService: MainService,
    private tabService: TabService,
    public router: Router,
  ) {}

	isLoading:Boolean = false;
	workData:any = []; //工单统计
	businessData:any = []; //业务统计
  listOfData: any[] = []; //表格数据
  pageIndex: number = 1; //表格当前页码
  pageSize: number = 10; //表格每页展示条数
  listLength: number = 10; //表格总数据量
	activeIndex:any = 'day';
	applyOptions:any={} //申请来源 option
	trendOptions:any={} //日趋势图 option
  businessOptions:any={} //业务分类 option
	deptTopData:any = [
		{
			name:'王'
		},
		{
			name:'王'
		},
		{
			name:'王'
		},
		{
			name:'王'
		},
		{
			name:'王'
		}
	] //科室top5
	userTopData:any = [
		{
			name:'王'
		},
		{
			name:'王'
		},
		{
			name:'王'
		},
		{
			name:'王'
		},
		{
			name:'王'
		}
	] //人员top5
  ngOnInit() {}
	
	/*========= 数据下钻 ========*/
	
	// 汇总
	viewDetail1(){
		let query = {
			isGdId: true,
		}
		let path = '/newStatistics/distributionInspectionStatistics/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('distributionData', JSON.stringify(query))
		this.router.navigate([path], { replaceUrl: true });
	}
	
	// 差评
	viewDetail4(){
		let query = {
			isGdId: true,
			startDate: this.customChangeDateComponent.startDate,
			endDate: this.customChangeDateComponent.endDate,
			searchQuery:{
				evaluateId: 358,
				evaluateDTO: {
					desc: "工单评价",
					id: 358,
					key: "workorderEvaluation",
					name: "极差",
					value: "1"
				}
			}
		}
		let path = '/newStatistics/distributionInspectionStatistics/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('distributionData', JSON.stringify(query))
		this.router.navigate([path], { replaceUrl: true });
	}
	
	// 科室top5
	viewMaintain1(data){
		let postData: any = {
		  idx: 0,
		  sum: 20,
		  department: {
		    statisticalHosId: this.getHosId,
		    dept: data.dept,
		    searchType: 1,
		  },
		};
		this.mainService.getFetchDataList("simple/data", "department", postData).subscribe(res => {
			let item = res.list.find(i => i.id == data.deptId)
			let query = {
				startDate: this.customChangeDateComponent.startDate,
				endDate: this.customChangeDateComponent.endDate,
				repairDeptId: data.deptId,
				searchQuery:{
					statusValue: 'close',
					deptDTO: item,
					deptId: data.deptId
				}
			}
			let path = '/newStatistics/distributionInspectionStatistics/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('distributionData', JSON.stringify(query))
			this.router.navigate([path], { replaceUrl: true });
		});
	}
	
	// 人员top5
	viewMaintain2(data){
		let query = {
			startDate: this.customChangeDateComponent.startDate,
			endDate: this.customChangeDateComponent.endDate,
			searchQuery:{
				statusValue: 'close',
				userDTO: {
					name: data.userName,
					id: data.userId?data.userId:-1
				},
				userId: data.userId?data.userId:-1
			}
		}
		let path = '/newStatistics/distributionInspectionStatistics/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('distributionData', JSON.stringify(query))
		this.router.navigate([path], { replaceUrl: true });
	}
	
  ngAfterViewInit(){
    setTimeout(() => {
      this.search();
    }, 0)
  }

	// 维修处理类型切换
	selectCheck(type){
		this.activeIndex = type
		this.trendChart();
	}

	// 申请来源
	applyChart() {
		let postData:any = {
	    startDate: this.customChangeDateComponent.startDate || undefined,
      endDate: this.customChangeDateComponent.endDate || undefined,
			type: 'sourceCount',
	    hosId: this.getHosId,
	    businessType: 'hsms',
	  };
		this.mainService
		  .getReportData(postData)
		  .subscribe((result:any) => {
		    let datas = result.data.map(i=>{
					return{
						name:i.name,
						value:i.sum
					}
				});
				this.applyOptions = {
				  tooltip: {
				    trigger: "item",
				    formatter: "{b}: {c} ({d}%)",
				  },
				  legend: {
				    data: datas,
						left: 'left',
				  },
				  series: [
				    {
				      name: "",
				      type: "pie",
				      radius: ["30%", "50%"],
							center:["50%","60%"],
				      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];
				          },
				        },
				      },
				    },
				  ],
				};
		  });
	}

	// 日趋势图
	trendChart(){
		let postData:any = {
	    startDate: this.customChangeDateComponent.startDate || undefined,
      endDate: this.customChangeDateComponent.endDate || undefined,
			type: 'dateTimeTrend',
	    hosId: this.getHosId,
	    businessType: 'hsms',
	    dateType: this.activeIndex,
      statisticsTypeId: this.statisticsTypeId || undefined,
	  };
		this.mainService
		  .getReportData(postData)
		  .subscribe((result:any) => {
		    let datas = []
				let title = []
				for(let i of result.data){
					datas.push(i.sum)
					title.push(i.date)
				}
				this.trendOptions = {
					tooltip: {
					    trigger: 'axis',
					    axisPointer: {
					      type: 'cross'
					    }
					  },
						grid: {
							top: '10%',
							left: '0%',  // grid布局设置适当调整避免X轴文字只能部分显示
							right: 20, // grid布局设置适当调整避免X轴文字只能部分显示
							bottom: '2%',
							containLabel: true,
						},
            dataZoom: {
              type: "inside"
            },
					  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: 8, // 刻度标签与轴线之间的距离
								}
					    }
					  ],
					  yAxis: [
					    {
					      type: 'value',
								axisLine: {
									show:false
								},
								axisTick:{
									show:false
								},
                splitLine: {
                  lineStyle: {
                    type: 'dotted',
                  }
                }
					    }
					  ],
					  series: [
					    {
					      type: 'line',
								color: '#3AACFF',
					      data: datas,
								label:{
									show: true,
									position: "top",  // 展示在上方
									color: "#333",
								},
					    }
					  ]
				}
		  });
	}

  // 业务分类
	businessChart(){
    let postData:any = {
	    startDate: this.customChangeDateComponent.startDate || undefined,
      endDate: this.customChangeDateComponent.endDate || undefined,
			type: 'statisticsDateTypeTop5',
	    hosId: this.getHosId,
	    businessType: 'hsms',
	  };
		this.mainService
		  .getReportData(postData)
		  .subscribe((result:any) => {
		    let datas = []
		    let title = []
		    for(let i of result.data){
		    	datas.push(i.sum)
		    	title.push(i.statisticsDateType)
		    }
		    this.businessOptions = {
		    	tooltip: {
		    	    trigger: 'axis',
		    	    axisPointer: {
		    	      type: 'shadow'
		    	    }
		    	  },
						grid: {
							top: '10%',
							left: '0%',  // grid布局设置适当调整避免X轴文字只能部分显示
							right: '0%', // 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
		    	  		},
                splitLine: {
                  lineStyle: {
                    type: 'dotted',
                  }
                }
		    	    }
		    	  ],
		    	  series: [
		    	    {
		    	      type: 'bar',
		    	      barWidth: 20,
		    				color: '#FFD68D',
		    	      data: datas,
								label:{
									show:true,
									position: "top",  // 展示在柱子的上方
									color: "#333"
								}
		    	    }
		    	  ]
		    }
		  });
	}

	// 科室Top5
	getDeptTopData() {
	  let postData:any = {
	    startDate: this.customChangeDateComponent.startDate || undefined,
      endDate: this.customChangeDateComponent.endDate || undefined,
			type: 'deptTop5',
	    hosId: this.getHosId,
	    businessType: 'hsms',
	  };
	  this.mainService
	    .getReportData(postData)
	    .subscribe((result:any) => {
	      this.deptTopData = result.data || [];
	    });
	}

	// 人员Top5
	getUserTopData() {
	  let postData:any = {
	    startDate: this.customChangeDateComponent.startDate || undefined,
      endDate: this.customChangeDateComponent.endDate || undefined,
			type: 'userTop5',
	    hosId: this.getHosId,
	    businessType: 'hsms',
	  };
	  this.mainService
	    .getReportData(postData)
	    .subscribe((result:any) => {
				this.isLoading = false;
	      this.userTopData = 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.router.navigate([path], { replaceUrl: true });
	}

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

  get getHosId(){
    return this.parentDutyId || this.dutyId || this.hosId;
  }

  // 初始化缓存数据
  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.getStatisticsTypeList();
		this.getWorkData();
		// this.getBusinessData();
		this.applyChart();
		this.trendChart();
    this.businessChart();
		this.getDeptTopData();
		this.getUserTopData();
  }

  // 表格数据
  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.getHosId,
	    businessType: 'hsms',
	  };
	  this.mainService
	    .getReportData(postData)
	    .subscribe((result:any) => {
	      this.workData = result.data[0] || [];
	    });
	}

  // 头部业务数据
	getBusinessData() {
	  let postData:any = {
	    startDate: this.customChangeDateComponent.startDate || undefined,
      endDate: this.customChangeDateComponent.endDate || undefined,
			type: 'businessCount',
	    hosId: this.getHosId,
	    businessType: 'hsms',
	  };
	  this.mainService
	    .getReportData(postData)
	    .subscribe((result:any) => {
	      this.businessData = result.data[0] || [];
	    });
	}

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

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

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

  // 获取统计分类列表
  statisticsTypeList:any[] = [];
  statisticsTypeId;//统计分类id
  getStatisticsTypeList(keyword?) {
    this.mainService
      .getDictionary("list", "statistics_date_type")
      .subscribe((data) => {
        this.statisticsTypeList = data;
      });
  }

  changeStatisticsType(id){
    this.trendChart();
  }
}
