import { Component, OnInit, AfterViewInit, HostListener, ElementRef, ViewChild } from "@angular/core";
import { ToolService } from 'src/app/services/tool.service';
import { MainService } from 'src/app/services/main.service';
import { ActivatedRoute } from '@angular/router';
import { FormGroup, Validators, FormBuilder } from '@angular/forms';
import { Subject } from 'rxjs';
import { debounceTime } from 'rxjs/operators';

@Component({
  selector: "app-washing-batch-view",
  templateUrl: "./washing-batch-view.component.html",
  styleUrls: ["./washing-batch-view.component.less"],
})
export class WashingBatchViewComponent implements OnInit, AfterViewInit {
  @ViewChild('printBtn', { static: false }) printBtn: ElementRef<HTMLElement>;
  constructor(
    public tool: ToolService,
    private mainService: MainService,
    public route: ActivatedRoute,
    private fb: FormBuilder,
  ){}

  ngOnInit() {
    //防抖
    this.changeInpSubject.pipe(debounceTime(500)).subscribe((v) => {
      if(v[1] === 'building'){
        this.getBuildingList(v[0]);
      }
    });
    this.hosId = this.tool.getCurrentHospital().id;
    this.getParentList();
    this.getBuildingList();
    this.getChildList();
    this.getDictionaryList();
    this.getList();
  }

  ngAfterViewInit(){
    this.resizeInit();
  }
  _timer = null;
  @HostListener('window:resize')
  resizeInit(){
    clearTimeout(this._timer);
    this._timer = setTimeout(() => {
      this.scrollY = window.innerHeight - 206 - document.querySelector('.head').clientHeight - document.querySelector('th').clientHeight;
    }, 500)
  }

  listOfData: any[] = []; //表格数据
  loading:boolean = false;
  isAllDisplayDataChecked = false; //当前页是否全选
  mapOfCheckedId: { [key: string]: boolean } = {};
  checkedDepIds = []; //已选中单列id
  scrollY:number = 0;
  hosId:any;
  searchDto:any = {
    parent: null,
    child: null,
    buildingId: null,
  }
  parentList: Array<any> = []; //父级分类数据字典信息
  childList: Array<any> = []; //分类数据字典信息
  rows:any[] = [['id', 'clothesState', ''], [], ['','件数', '费用/元']];
  totalData:any = {};

  createTime = this.route.snapshot.paramMap.get("createTime");

  //搜索
  changeInpSubject = new Subject(); //防抖
  changeInp(e, type) {
    this.isLoading = true;
    this.changeInpSubject.next([e, type]);
  }

  // 查看业务数据
  washingExceptionModalShow = false; //业务数据弹窗开关
  viewDetail() {
    this.washingExceptionModalShow = true;
  }
  // 关闭业务数据弹窗
  closeModelWashingException(e) {
    this.washingExceptionModalShow = JSON.parse(e).show;
  }

  // 全选
  checkAll(value: boolean): void {
    this.listOfData.forEach((item) => {
      if (item[0][1] == 4) {
        this.mapOfCheckedId[item[0][0]] = value;
      }
    });
    this.refreshStatus();
  }

  // 单选
  refreshStatus(): void {
    let listOfData = this.listOfData.filter(
      (item) => item[0][1] == 4
    );
    this.isAllDisplayDataChecked = listOfData.every(
      (item) => this.mapOfCheckedId[item[0][0]]
    );
    let arr = [];
    for (var k in this.mapOfCheckedId) {
      if (this.mapOfCheckedId[k]) {
        arr.push(Number(k));
      }
    }
    this.checkedDepIds = arr;
  }

  // 整行操作
  selectedListData(data) {
    if (data[0][1] != 4) {
      return;
    }
    this.mapOfCheckedId[data[0][0]] = !this.mapOfCheckedId[data[0][0]];
    this.refreshStatus();
  }

  // 获取父级分类
  getParentList() {
    let postData = {
      idx: 0,
      sum: 9999,
      dictionaryTree: {
        hosId: this.hosId,
        level: 1,
        key: 'clothes_type',
        deleted: 0,
      },
    };
    this.mainService
      .getFetchDataList("simple/data", "dictionaryTree", postData)
      .subscribe((result) => {
        if(result.status == 200){
          this.parentList = result.list || [];
        }
      });
  }

  // 获取楼栋
  buildingList:any[] = [];
  isLoading:boolean = false;
  getBuildingList(keyWord = '') {
    let postData = {
      idx: 0,
      sum: 9999,
      building: {
        simpleQuery: true,
        buildingName: keyWord,
        cascadeHosId: this.hosId,
      }
    };
    this.isLoading = true;
    this.mainService.getFetchDataList("simple/data", "building", postData)
    .subscribe((data) => {
      this.isLoading = false;
      if (data.status == 200) {
        this.buildingList = data.list;
      }
    });
  }

  reset(){
    this.searchDto = {
      parent: null,
      child: null,
      buildingId: null,
    }
    this.getList();
  }

  // 获取分类
  getChildList() {
    let postData = {
      idx: 0,
      sum: 9999,
      clothesDept: {
        hosId: this.hosId,
      },
    };
    this.mainService
      .getFetchDataList("simple/data", "clothesDept", postData)
      .subscribe((result) => {
        if(result.status == 200){
          this.childList = result.list || [];
        }
      });
  }

  //批量送回
  loading3 = false;
  delModal: boolean = false; //模态框
  content:string = '';
  showDelModal() {
    this.delModal = true;
    this.content = `您选择了${this.checkedDepIds.length}个科室批量送回被服，您确认吗？`;
  }
  hideDelModal() {
    this.delModal = false;
  }
  confirmDel() {
    this.loading3 = true;
    let postData: any = {
      hosId: this.hosId,
      batchId: this.route.snapshot.paramMap.get("id"),
      deptIds: this.checkedDepIds.toString(),
      type: 'clothingSend',
      orderId: 0,
    };
    this.mainService.transflow(postData, 'createRemandOrder').subscribe((data) => {
      this.loading3 = false;
      this.delModal = false;
      if (data.data && data.data.state == 200) {
        this.showPromptModal("操作", true, "");
      } else {
        this.showPromptModal("操作", false, data.data && data.data.msg);
      }
    });
  }

  //修改数量
  btnLoading = false;
  washingModal: boolean = false; //模态框
  washingCoopData:any = {};
  showWashingModal(row) {
    this.washingCoopData = row;
    this.washingModal = true;
    this.initForm();
  }
  hideWashingModal() {
    this.washingModal = false;
  }
  confirmWashing() {
    for (const i in this.validateForm.controls) {
      this.validateForm.controls[i].markAsDirty();
      this.validateForm.controls[i].updateValueAndValidity();
    }
    if (this.validateForm.invalid) return;
    this.btnLoading = true;
    let postData: any = {
      hosId: this.hosId,
      id: this.washingCoopData.id,
      sendBackNum: this.validateForm.value.sendBackNum,
      clothesExceptionResId: this.validateForm.value.clothesExceptionResId,
      remarks: this.validateForm.value.remarks,
    };
    this.mainService.simplePost("addData", "clothesWashing", postData).subscribe((data) => {
      this.btnLoading = false;
      this.washingModal = false;
      if (data.status == 200) {
        this.showPromptModal("操作", true, "");
      } else {
        this.showPromptModal("操作", false, data.msg);
      }
    });
  }

  // 初始化form表单
  validateForm: FormGroup;
  initForm() {
    this.validateForm = this.fb.group({
      sendBackNum: [0, [Validators.required]],
      clothesExceptionResId: [null, [Validators.required]],
      remarks: [null, [Validators.required]],
    });
  }

  // 展示信息提示框（con:提示信息，success:操作是否成功，promptInfo:操作结果提示信息）
  promptContent: string; //操作提示框提示信息
  ifSuccess: boolean; //操作成功/失败
  promptInfo: string; //操作结果提示信息
  promptModalShow: boolean; //操作提示框是否展示
  showPromptModal(con, success, promptInfo?) {
    this.promptModalShow = false;
    this.promptContent = con;
    this.ifSuccess = success;
    this.promptInfo = promptInfo;
    setTimeout(() => {
      this.promptModalShow = true;
    }, 100);
    this.getList();
  }

  // 点击数字
  clickNum(e, row){
    e.stopPropagation();
    this.showWashingModal(row)
  }

  dictionaryList: Array<any> = []; //数据字典信息
  // 数据字典列表
  getDictionaryList() {
    this.mainService.getDictionary("list", "clothes_exception").subscribe((data:any) => {
      this.dictionaryList = data || [];
    })
  }

  // 打印
  printAll(){
    setTimeout(()=>{
      this.printBtn.nativeElement.click();
    },0)
  }

  // 表格数据
  getList() {
    if(!this.searchDto.child){
      this.rows = [['id', 'clothesState', ''], [], ['','总件数', '总费用/元']];
      this.listOfData = [];
      this.totalData = {};
      return;
    }
    let postData: any = {
      hosId: this.hosId,
      batchId: this.route.snapshot.paramMap.get("id"),
      clothesTypeParent: this.searchDto.parent,
      clothesDeptId: this.searchDto.child,
      buildingId: this.searchDto.buildingId,
    };
    this.loading = true;
    this.mapOfCheckedId = {};
    this.checkedDepIds = [];
    this.isAllDisplayDataChecked = false;
    this.mainService
      .clothesWashing(postData, 'view')
      .subscribe((result) => {
        this.loading = false;
        if(result.status == 200){
          let rows = result.head || [];
          this.rows = [['id', 'clothesState', ''], rows.map(v => v.name), ['','件数', '费用/元']];
          let listOfData_res = result.data || [];
          this.listOfData = listOfData_res.map(v => ([
            [v.id, v.clothesState.value, v.dept],
            v.clothesWashingDTOS,
            ['', v.nums, v.price]
          ]))
          this.totalData = result.totalData || {};
        }
      });
  }
}

