import { Component, OnInit, ViewChild, ElementRef } from "@angular/core";
import { ActivatedRoute, Router } from "@angular/router";
import { FormBuilder, Validators, FormGroup, FormControl } from "@angular/forms";

import { MainService } from "../../services/main.service";
import { OverlayScrollbarsComponent } from "overlayscrollbars-ngx";
import { ToolService } from "../../services/tool.service";
import { NzMessageService } from "ng-zorro-antd";
import { Subject } from 'rxjs';
import { debounceTime } from 'rxjs/operators';
import { format } from 'date-fns';

@Component({
  selector: "app-barcode-prefabrication",
  templateUrl: "./barcode-prefabrication.component.html",
  styleUrls: ["./barcode-prefabrication.component.less"],
})
export class BarcodePrefabricationComponent implements OnInit {
  @ViewChild('printBtn', { static: false }) printBtn: ElementRef<HTMLElement>;
  @ViewChild("osComponentRef1", {
    read: OverlayScrollbarsComponent,
    static: false,
  })
  osComponentRef1: OverlayScrollbarsComponent;
  constructor(
    private message: NzMessageService,
    private fb: FormBuilder,
    private route: ActivatedRoute,
    private router: Router,
    private mainService: MainService,
    private tool: ToolService
  ) {}

  listOfData: any[] = []; //表格数据

  modal: boolean = false; //新增/编辑模态框
  add: boolean; //true:新增；false:编辑
  validateForm: FormGroup; //新增/编辑表单
  coopId: number; //表格中执行操作的id
  hosId: any; //院区（搜索）
  codeTypes: Array<any> = []; //所有条码样式
  pageIndex: number = 1; //页码
  listLength: number = 10; //总条数
  pageSize: number = 10; //每页条数

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

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

  changeInpSubject = new Subject(); //防抖

  ngOnInit() {
    //防抖
    this.changeInpSubject.pipe(debounceTime(500)).subscribe((v) => {
      this.getSnConfigs(v[0]);
    });
    this.coopBtns = this.tool.initCoopBtns(this.route);
    this.initForm();
    this.getAllHospital();
    this.getCodeType();
    this.getSnConfigs();
    this.getClinicalWasteType();
  }

  // 初始化增删改按钮
  coopBtns: any = {};
  // 表格数据
  loading1 = false;
  getList() {
    let data = {
      idx: this.pageIndex - 1,
      sum: this.pageSize,
      precastCode: {
        hosId: this.hosId,
      },
    };
    this.loading1 = true;
    this.mainService
      .getFetchDataList("simple/data", "precastCode", data)
      .subscribe((data) => {
        this.loading1 = false;
        this.listOfData = data.list;
        this.listLength = data.totalNum;
      });
  }

  // 获取所有条码样式
  getCodeType() {
    this.mainService.getDictionary("list", "precastCode_code_type").subscribe((data) => {
      this.codeTypes = data;
    });
  }

  // 获取相应的院区
  getAllHospital() {
    this.hosId = this.tool.getCurrentHospital().id;
    this.getList();
  }

  // 获取序号名称
  snConfigs: Array<any> = [];
  getSnConfigs(keyword = "") {
    this.mainService.getFetchDataList("simple/data", "serialnumberConfig", {idx: 0, sum: 9999, serialnumberConfig: { hosId: this.hosId, title: keyword }}).subscribe((data) => {
      this.isLoading = false;
      this.snConfigs = data.list || [];
    });
  }

  // 获取废物类型
  clinicalWasteTypes: Array<any> = [];
  getClinicalWasteType(keyword = "") {
    this.mainService.getFetchDataList("simple/data", "clinicalWasteType", {idx: 0, sum: 9999, clinicalWasteType: { hosId: this.hosId }}).subscribe((data) => {
      this.clinicalWasteTypes = data.list || [];
    });
  }

  // 边输边搜节流阀
  isLoading = false;
  changeInp(e) {
    this.isLoading = true;
    this.changeInpSubject.next([e]);
  }

  // 新增弹框
  showModal() {
    this.add = true;
    this.initForm();
    this.modal = true;
  }
  hideModal() {
    this.modal = false;
    this.initForm();
  }

  // 初始化新增form表单
  initForm() {
    this.validateForm = this.fb.group({
      title: [null, [Validators.required]],
      snConfig: [null, [Validators.required]],
      codeType: [null, [Validators.required]],
    });
  }
  // 表单提交
  submitForm(): void {
    var that = this;
    for (const i in that.validateForm.controls) {
      that.validateForm.controls[i].markAsDirty({ onlySelf: true });
      that.validateForm.controls[i].updateValueAndValidity();
    }
    if (that.validateForm.invalid) return;
    that.btnLoading = true;
    let data:any = {
      title: that.validateForm.value.title,
      snConfig: that.validateForm.value.snConfig,
      codeType: that.validateForm.value.codeType ? { id: that.validateForm.value.codeType } : undefined,
      hosId: that.hosId,
    };
    if (!that.add) {
      data = {...this.coopData, ...data};
    }
    that.mainService
      .simplePost("addData", "precastCode", data)
      .subscribe((data) => {
        that.btnLoading = false;
        that.hideModal();
        that.initForm();
        if (data.status == 200) {
          that.showPromptModal(that.add ? "新增" : "编辑", true, "");
        } else {
          that.showPromptModal(that.add ? "新增" : "编辑", false, data.msg);
        }
      });
  }

  // 编辑
  maskFlag: any = false;
  coopData:any = {};
  edit(data) {
    this.modal = true;
    this.add = false;
    this.coopId = data.id;
    this.coopData = data;
    this.validateForm.controls.title.setValue(data.title);
    this.validateForm.controls.snConfig.setValue(data.snConfig);
    this.validateForm.controls.codeType.setValue(data.codeType? data.codeType.id : null);
  }

  // 删除
  delModal: boolean = false; //删除模态框
  del(data) {
    this.coopId = data.id;
    this.delModal = true;
  }
  // 确认删除
  confirmDel() {
    let that = this;
    that.btnLoading = true;
    that.mainService
      .simplePost("rmvData", "precastCode", [that.coopId])
      .subscribe((data) => {
        that.btnLoading = false;
        that.hideDelModal();
        if (data["status"] == 200) {
          if (
            that.listOfData.length == 1 &&
            that.pageIndex == Math.ceil(that.listLength / that.pageSize)
          ) {
            that.listLength--;
            that.pageIndex = Math.ceil(that.listLength / that.pageSize) || 1;
          }
          that.showPromptModal("删除", true, "");
        } else {
          that.showPromptModal("删除", false, data["msg"]);
        }
      });
  }
  // 关闭删除模态框
  hideDelModal() {
    this.delModal = false;
  }

  // 展示信息提示框（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.getList();
  }

  // 生成
  dateText: string = '';
  isYear: boolean = false;
  isMonth: boolean = false;
  isDay: boolean = false;
  generateQRcode(data) {
    this.coopData = data;
    if(this.coopData.snConfigDTO.dateType){
      this.dateText = '';
      this.isYear = false;
      this.isMonth = false;
      this.isDay = false;
      if(this.coopData.snConfigDTO.dateType.name.includes('y')){
        this.dateText += '年';
        this.isYear = true;
      }
      if(this.coopData.snConfigDTO.dateType.name.includes('m')){
        this.dateText += '月';
        this.isMonth = true;
      }
      if(this.coopData.snConfigDTO.dateType.name.includes('d')){
        this.dateText += '日';
        this.isDay = true;
      }
    }
    this.showGenerateModal();
  }

  // 新增弹框
  generateModal: boolean = false; //新增/编辑模态框
  validateGenerateForm: FormGroup; //新增/编辑表单
  showGenerateModal() {
    this.initGenerateForm();
    this.generateModal = true;
  }
  hideGenerateModal() {
    this.generateModal = false;
    this.initGenerateForm();
  }
  // 初始化新增form表单
  initGenerateForm() {
    this.validateGenerateForm = this.fb.group({
      date: [null, [Validators.required]],
      count: [1, [Validators.required]],
    });
    if(this.coopData.snConfigDTO.dateType){
      this.validateGenerateForm.addControl(
        'date',
        new FormControl(null, Validators.required)
      );
    }else{
      this.validateGenerateForm.removeControl('date');
    }
  }
  // 生成表单提交
  codeList: any[] = [];
  submitGenerateForm(): void {
    console.log(this.validateGenerateForm.value)
    for (const i in this.validateGenerateForm.controls) {
      this.validateGenerateForm.controls[i].markAsDirty({ onlySelf: true });
      this.validateGenerateForm.controls[i].updateValueAndValidity();
    }
    if (this.validateGenerateForm.invalid) return;
    this.btnLoading = true;
    let postData:any = {
      count: this.validateGenerateForm.value.count,
      date: this.validateGenerateForm.value.date ? format(this.validateGenerateForm.value.date, 'yyyy-MM-dd HH:mm:ss') : undefined,
      id: this.coopData.id,
    };
    this.mainService
      .coopWorkerOrder("generatePrecastCode", postData)
      .subscribe((data) => {
        this.btnLoading = false;
        this.hideGenerateModal();
        this.initGenerateForm();
        if (data.state == 200) {
          this.codeList = data.data || [];
          // 打印
          setTimeout(()=>{
            this.printBtn.nativeElement.click();
          }, )
        } else {
          this.showPromptModal("生成", false, data.msg);
        }
      });
  }
}
