import { Component, OnInit, Input } from "@angular/core";
import { Subject } from 'rxjs';
import { debounceTime } from 'rxjs/operators';
import { Validators, FormGroup, FormBuilder } from '@angular/forms';
import { ToolService } from 'src/app/services/tool.service';
import { NzMessageService } from 'ng-zorro-antd';
import { MainService } from 'src/app/services/main.service';

@Component({
  selector: "app-configuration-special-specimen-marking",
  templateUrl: "./configuration-special-specimen-marking.component.html",
  styleUrls: ["./configuration-special-specimen-marking.component.less"],
})
export class ConfigurationSpecialSpecimenMarkingComponent implements OnInit {
  constructor(
    private mainService: MainService,
    private fb: FormBuilder,
    private tool: ToolService,
    private message: NzMessageService,
  ) {}

  coopData: any = {}; //当前操作列
  hosId: any = this.tool.getCurrentHospital().id;

  searchTimerSubject = new Subject();

  ngOnInit() {
    this.searchTimerSubject.pipe(debounceTime(500)).subscribe((v) => {
      let fun = v[0];
      fun.call(this, v[1]);
    });
    this.getTypes();
    this.getTubeTypeList();
    this.getList();
  }

  // 新增弹框
  modelName = ""; //模态框名称
  modalWechat: boolean = false; //新增/编辑模态框
  add: boolean; //true:新增；false:编辑
  addWechatModal() {
    this.modelName = "新增";
    this.add = true; //新增
    this.modalWechat = true;
    this.initWechatForm();
  }
  //关闭新增/编辑弹框
  hideWechatModal() {
    this.modalWechat = false;
  }

  // 防抖
  isLoading = false;
  isSelecting:boolean = false; // 是否在选中状态
  searchTimer(fun, e) {
    if (this.isSelecting) {
      this.isSelecting = false; // 重置标志
      return; // 跳过处理
    }
    this.isLoading = true;
    this.searchTimerSubject.next([fun, e]);
  }

  // 设置标志
  setIsSelecting(flag){
    this.isSelecting = flag; // 设置标志
  }

  openChangeDept(flag){
    flag && this.setIsSelecting(false);
    flag && this.getDeptList();
  }

  // 科室搜索
  changeDeptInp(e) {
    this.searchTimer(this.getDeptList, e);
  }

  // 获取申请科室
  deptList: any = [];
  getDeptList(e = undefined) {
    let postData = {
      idx: 0,
      sum: 20,
      department: {
        searchType: 1,// 简单查询
        cascadeHosId: this.hosId,
        dept: e,
      }
    };
    this.isLoading = true;
    this.mainService
      .getFetchDataList("simple/data", "department", postData)
      .subscribe((data) => {
        this.isLoading = false;
        this.deptList = data.list || [];
      });
  }

  // 编辑
  editWechat(data) {
    console.log(data);
    this.modelName = "编辑";
    this.add = false;
    this.modalWechat = true;
    this.initWechatForm();
    this.coopData = data;
    this.validateForm.controls.stype.setValue(data.stype ? data.stype.id : null);
    this.validateForm.controls.checkItem.setValue(data.checkItem);
    this.validateForm.controls.startDept.setValue(data.startDeptDTO ? data.startDeptDTO.id : null);
    this.validateForm.controls.tubeType.setValue(data.tubeType ? data.tubeType.id : null);
    this.validateForm.controls.urgent.setValue(data.urgent);

    data.startDeptDTO && (this.deptList = [data.startDeptDTO]);
  }

  // 新增/编辑表单提交
  btnLoading: boolean = false; //提交按钮loading状态
  submitWechatForm(): void {
    for (const i in this.validateForm.controls) {
      this.validateForm.controls[i].markAsDirty();
      this.validateForm.controls[i].updateValueAndValidity();
    }
    if (this.validateForm.invalid) {
      return;
    }
    console.log(this.validateForm.value);
    this.btnLoading = true;
    let postData:any = {};

    if (this.add) {
      //增加
      postData = {
        // speUrgentMarkConfig: {
          hosId: this.hosId,
          stype: this.validateForm.value.stype ? { id: this.validateForm.value.stype } : undefined,
          checkItem: this.validateForm.value.checkItem || undefined,
          startDept: this.validateForm.value.startDept || undefined,
          tubeType: this.validateForm.value.tubeType ? { id: this.validateForm.value.tubeType } : undefined,
          urgent: this.validateForm.value.urgent || undefined,
        // }
      };
    } else {
      //编辑
      postData = {
        // speUrgentMarkConfig: {
          ...this.coopData,
          stype: this.validateForm.value.stype ? { id: this.validateForm.value.stype } : undefined,
          checkItem: this.validateForm.value.checkItem || undefined,
          startDept: this.validateForm.value.startDept || undefined,
          tubeType: this.validateForm.value.tubeType ? { id: this.validateForm.value.tubeType } : undefined,
          urgent: this.validateForm.value.urgent || undefined,
        // }
      };
    }
    this.mainService
      .simplePost("addData", "speUrgentMarkConfig", postData)
      .subscribe((result) => {
        this.btnLoading = false;
        this.hideWechatModal();
        let msg = "";
        if (this.add) {
          msg = "新增";
        } else {
          msg = "修改";
        }
        if (result.status == 200) {
          this.showPromptModal(msg, true, '');
        } else {
          this.showPromptModal(msg, false, result.msg);
        }
      });
  }

  // 初始化新增form表单
  validateForm: FormGroup; //新增/编辑表单
  initWechatForm() {
    this.validateForm = this.fb.group({
      stype: [null, [Validators.required]],
      checkItem: [null, [Validators.required]],
      startDept: [null],
      tubeType: [null],
      urgent: [null, [Validators.required]],
    });
  }

  // 获取列表
  loading1:boolean = false;
  dataList: any[] = []; //表格数据
  getList() {
    let data = {
      idx: 0,
      sum: 9999,
      speUrgentMarkConfig: {
        hosId: this.hosId,
      },
    };
    this.loading1 = true;
    this.mainService
      .getFetchDataList("simple/data", "speUrgentMarkConfig", data)
      .subscribe((data) => {
        this.loading1 = false;
        if (data.status == 200) {
          this.dataList = data.list || [];
        }else{
          this.message.error(data.msg || "请求数据失败");
        }
      });
  }

  // 获取试管类型
  tubeTypeList: any = [];
  getTubeTypeList() {
    this.mainService.getDictionary('list', 'specimen_tube_type').subscribe((data) => {
      this.isLoading = false;
      this.tubeTypeList = data || [];
    });
  }

  // 获取标本类型
  typeList: any = [];
  getTypes() {
    this.mainService.getDictionary('list', 'specimen_type').subscribe((data) => {
      this.isLoading = false;
      this.typeList = data || [];
    });
  }

  delModal: boolean = false; //删除模态框
  tipsMsg1: string; //提示框信息
  tipsMsg2: string; //操作后信息
  confirmDelType: string; //确认的类型（启用/停用，删除）
  showDelModal(
    data,
    tipsMsg1: string,
    tipsMsg2: string,
    type: string,
  ) {
    this.confirmDelType = type;
    this.delModal = true;
    this.coopData = data;
    this.tipsMsg1 = tipsMsg1;
    this.tipsMsg2 = tipsMsg2;
  }
  // 隐藏删除框
  hideDelModal() {
    this.delModal = false;
  }
  // 确认删除
  confirmDel() {
    this.btnLoading = true;
    if (this.confirmDelType === "del") {
      //删除
      this.mainService
        .simplePost("rmvData", "speUrgentMarkConfig", [this.coopData.id])
        .subscribe((data) => {
          this.btnLoading = false;
          this.delModal = false;
          if (data.status == 200) {
            this.showPromptModal(this.tipsMsg2, true, "");
          } else {
            this.showPromptModal(this.tipsMsg2, false, data.msg);
          }
        });
    }
  }

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