import { Component, OnInit } from "@angular/core";
import { ActivatedRoute, Router } from "@angular/router";
import { MainService } from "../../services/main.service";
import { ToolService } from "../../services/tool.service";
import { NzMessageService } from 'ng-zorro-antd';
import { THIS_EXPR } from '@angular/compiler/src/output/output_ast';
import { format, startOfDay, endOfDay } from 'date-fns';
import { DateService } from 'src/app/services/date.service';

@Component({
  selector: "app-questionnaire-answer",
  templateUrl: "./questionnaire-answer.component.html",
  styleUrls: ["./questionnaire-answer.component.less"],
})
export class QuestionnaireAnswerComponent implements OnInit {
  constructor(
    private mainService: MainService,
    private route: ActivatedRoute,
    private router: Router,
    private tool: ToolService,
    private message: NzMessageService,
		private dateService: DateService,
  ) {}

  userInfo: any = JSON.parse(localStorage.getItem("user")) || {}; //登录用户信息
  listOfData: any[] = []; //表格数据
  listOfDataTh: any[] = []; //表格数据
  pageIndex: number = 1; //表格当前页码
  pageSize: number = 10; //表格每页展示条数
  listLength: number = 10; //表格总数据量
  currentHospital; //当前院区
	listBaseInfoTh: any[] = []; //陪检患者表格表头
	listBaseInfos: any[] = []; //陪检患者表格数据
  ngOnInit() {
    this.currentHospital = this.tool.getCurrentHospital();
    this.getList(1);
  }

  // 初始化增删改按钮
  coopBtns: any = {};
  // 导出
  loading2 = false;
  export() {
    let postData = {
      idx: 0,
      sum: 99999,
      qmId: this.route.snapshot.queryParams.id,
			startTime: this.startDate || undefined,
			endTime: this.endDate || undefined,
    };
    this.loading2 = true;
    this.mainService.exportReport("survey", postData).subscribe(
      (data) => {
        this.loading2 = false;
        this.message.create('success', `导出成功`);
        var file = new Blob([data], {
          type: "application/vnd.ms-excel",
        });
        //trick to download store a file having its URL
        var fileURL = URL.createObjectURL(file);
        var a = document.createElement("a");
        a.href = fileURL;
        a.target = "_blank";
        a.download = `回收数据.xls`;
        document.body.appendChild(a);
        a.click();
      },
      (err) => {
        this.loading2 = false;
        this.message.create('error', `导出失败`);
      }
    );
  }
	
	// 日期选择
	startDate: string; //发起时间开始
	endDate: string; //发起时间结束
	dateRange: any = [];
	changeDate(result?): void {
	  if (result.length==0) {
	    this.startDate = this.endDate = null;
	    return;
	  }
		this.startDate = format(result[0], 'yyyy-MM-dd HH:mm:ss');
		this.endDate = format(result[1], 'yyyy-MM-dd HH:mm:ss');
	  this.dateRange = [this.startDate,this.endDate]
	}
	
	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.dateRange = [dateStart,dateEnd];
	  }
	}
	
	monthValue:any;
	// 快捷选择 1：本月 2：上月
	changeMonth(e){
		if(e==2){
			let lastmonthstartdate = this.dateService.date().lastMonthStartDate;
			let lastmonthenddate = this.dateService.date().lastMonthEndDate;
			this.startDate = format(lastmonthstartdate, 'yyyy-MM-dd HH:mm:ss');
			this.endDate = format(lastmonthenddate, 'yyyy-MM-dd HH:mm:ss');
			this.dateRange = [this.startDate,this.endDate]
		}else if(e==1){
			let thismonthstartdate = this.dateService.date().thisMonthStartDate;
			let thismonthenddate = this.dateService.date().thisMonthEndDate;
			this.startDate = format(thismonthstartdate, 'yyyy-MM-dd HH:mm:ss');
			this.endDate = format(thismonthenddate, 'yyyy-MM-dd HH:mm:ss');
			this.dateRange = [this.startDate,this.endDate]
		}else{
			this.startDate = null;
			this.endDate = null;
			this.dateRange = []
		}
	}
	
	// 重置
	reset(){
		this.pageIndex = 1;
		this.startDate = null;
		this.endDate = null;
		this.dateRange = [];
		this.monthValue = null;
		this.getList(1);
	}
	
  // 表格数据
  loading1 = false;
  getList(type) {
    if (type == 1) {
      this.pageIndex = 1;
    }
    let postData = {
      idx: this.pageIndex - 1,
      sum: this.pageSize,
      qmId: this.route.snapshot.queryParams.id,
			startTime: this.startDate || undefined,
			endTime: this.endDate || undefined,
    };
    this.loading1 = true;
    this.mainService
      .listQuestionnaire(postData)
      .subscribe((data:any) => {
        this.loading1 = false;
        if (data.status == 200) {
          this.listOfData = data.data?data.data.answers:[];
          this.listOfDataTh = data.data?data.data.infos:[];
					this.listBaseInfos = data.data?data.data.baseInfos:[];
					if(this.listBaseInfos&&this.listBaseInfos.length>0){
						this.listBaseInfoTh = [
							{describe:'患者姓名'},
							{describe:'住院号'},
							{describe:'工单编号/任务类型'},
							{describe:'执行人员'},
						]
						for(let i in this.listBaseInfos){
							this.listOfData[i].data = this.listBaseInfos[i]
						}
					}else{
						this.listBaseInfoTh = []
					}	
          this.listLength = data.totalNum;
        }
      });
  }
}

