import { Component, OnInit, ViewChild, ElementRef } 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 { subDays, startOfHour, format } from 'date-fns';
@Component({
  selector: "app-form-management",
  templateUrl: "./form-management.component.html",
  styleUrls: ["./form-management.component.less"],
})
export class FormManagementComponent implements OnInit {
  @ViewChild('printBtn', { static: false }) printBtn: ElementRef<HTMLElement>;
  constructor(
    private mainService: MainService,
    private route: ActivatedRoute,
    private tool: ToolService,
    private msg: NzMessageService,
    private router: Router,
  ) {}

  userInfo: any = JSON.parse(localStorage.getItem("user")) || {}; //登录用户信息
  hosId;
  listOfData: any[] = []; //表格数据
  pageIndex: number = 1; //表格当前页码
  pageSize: number = 10; //表格每页展示条数
  listLength: number = 10; //表格总数据量

  dateRange: any = [startOfHour(subDays(new Date().setHours(9), 1)), startOfHour(new Date().setHours(9))]; //日期选择

  ngOnInit() {
    this.hosId = this.tool.getCurrentHospital().id;
    this.getList();
    this.coopBtns = this.tool.initCoopBtns(this.route);
    this.getTaskTypes();
    this.getBuildings();
  }

  // 初始化权限按钮
  coopBtns: any = {};

  // 核酸打印
  formManagementLoading = false;
  formManagementList: any = [];
  formManagementListPageIndex: number = 1;//表格当前页码
  formManagementListPageSize: number = 10;//表格每页展示条数
  formManagementListLength: number = 0;//表格总数据量
  // 获取列表数据
  getOtherTasktype() {
    this.formManagementLoading = true;
    let postData = {
      idx: this.formManagementListPageIndex - 1,
      sum: this.formManagementListPageSize,
      workOrder: {
        buildingIds: this.buildings.filter(v => v.checked).map(v => v.value).toString() || undefined,
        hosId: this.hosId,
        gdState: {id: "433"},
        serTaskTypes: this.tasktypeId,
        time: 0,
        reserveDate: format(new Date(), 'yyyy-MM-dd HH:mm:ss'),
        startTime1: this.dateRange[0] ? format(this.dateRange[0], 'yyyy-MM-dd HH:mm:ss') : undefined,
        endTime1:  this.dateRange[1] ? format(this.dateRange[1], 'yyyy-MM-dd HH:mm:ss') : undefined,
      },
    };
    this.mainService.getFetchDataList("simple/data", "workOrder", postData).subscribe((data:any) => {
      this.formManagementLoading = false;
      this.formManagementList = data.list || [];
      this.formManagementListLength = data.totalNum || 0;
    })
  }

  // 确认表单生成
  saveFormManagement(){
    if(!this.tasktypeId){
      this.msg.info('请选择其他临床服务任务类型！');
      return;
    }
    this.fixedTab = 'formManagementTable';
    this.getOtherTasktype();
  }

  // 取消表单生成
  formManagementCancel():void {
    this.fixedTab = '';
  }

  //获取其他临床服务任务类型
  isLoading: boolean = false;
  tasktypeId:any;
  taskTypes:any[] = [];
  getTaskTypes(e:string = '') {
    let postData:any = {
      idx: 0,
      sum: 10,
      taskType: {
        taskName: e,
        simpleQuery: true,
        hosId: {
          id: this.hosId
        }
      }
    };
    postData.taskType.associationType = {
      key: 'association_types',
      value: 'other'
    }
    this.isLoading = true;
    this.mainService
      .getFetchDataList("simple/data", "taskType", postData)
      .subscribe((result) => {
        this.isLoading = false;
        if (result.status == 200) {
          this.taskTypes = result.list || [];
        }
      });
  }

  //获取楼栋
  buildings:any[] = [];
  getBuildings() {
    let postData:any = {
      idx: 0,
      sum: 9999,
      building: {
        cascadeHosId: this.hosId
      }
    };
    this.isLoading = true;
    this.mainService
      .getFetchDataList("simple/data", "building", postData)
      .subscribe((result) => {
        this.isLoading = false;
        if (result.status == 200) {
          let buildings = result.list || [];
          this.buildings = buildings.map(v => ({
            value: v.id,
            label: v.buildingName,
            checked: false,
          }))
        }
      });
  }

  // 切换右侧菜单Tab
  fixedTab: string = "";
  checkFixedTab(type: string) {
    this.dateRange = [startOfHour(subDays(new Date().setHours(9), 1)), startOfHour(new Date().setHours(9))];
    this.tasktypeId = undefined;
    this.buildings.forEach(v => {
      v.checked = false;
    });
    this.fixedTab = type;
  }

  // 表格数据
  loading1 = false;
  getList() {
    let postData = {
      idx: this.pageIndex - 1,
      sum: this.pageSize,
      reserveForm: {
        hosId: this.hosId,
        deleteFlag: 0,
      },
    };
    this.loading1 = true;
    this.mainService
      .getFetchDataList("simple/data", "reserveForm", postData)
      .subscribe((data) => {
        this.loading1 = false;
        if (data.status == 200) {
          this.listOfData = data.list;
          this.listLength = data.totalNum;
        }
      });
  }

  // 确认生成
  isOkLoading:boolean = false;
  formManagementOk(){
    let postData = {
      idx: 0,
      sum: 9999,
      workOrder: {
        exportQuery: true,
        buildingIds: this.buildings.filter(v => v.checked).map(v => v.value).toString() || undefined,
        hosId: this.hosId,
        gdState: {id: "433"},
        serTaskTypes: this.tasktypeId,
        time: 0,
        reserveDate: format(new Date(), 'yyyy-MM-dd HH:mm:ss'),
        startTime1: this.dateRange[0] ? format(this.dateRange[0], 'yyyy-MM-dd HH:mm:ss') : undefined,
        endTime1:  this.dateRange[1] ? format(this.dateRange[1], 'yyyy-MM-dd HH:mm:ss') : undefined,
      },
    };
    this.isOkLoading = true;
    this.mainService.getFetchDataList("simple/data", "workOrder", postData).subscribe((data:any) => {
      // 获取所有的工单
      let formManagementList = data.list || [];

      let postData:any = {
        taskType: this.tasktypeId,
        hosId: this.hosId,
        deleteFlag: 0,
        startTime: this.dateRange[0] ? format(this.dateRange[0], 'yyyy-MM-dd HH:mm:ss') : undefined,
        endTime:  this.dateRange[1] ? format(this.dateRange[1], 'yyyy-MM-dd HH:mm:ss') : undefined,
        workOrderIds: formManagementList.map(v => v.id).toString(),
      };

      this.mainService
        .simplePost("addData", "reserveForm", postData)
        .subscribe((result) => {
          this.isOkLoading = false;
          if (result.status == 200) {
            this.formManagementCancel();
            this.pageIndex = 1;
            this.getList();
            this.msg.success('生成表单成功！');
          }else{
            this.msg.error('生成表单失败！');
          }
        });
    })
  }

  // 查看视图
  lookView(data){
    this.router.navigateByUrl(
      `/main/formManagementDetail/${data.id}/${data.taskType}`
    );
  }
}


