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

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

@Component({
  selector: "app-drug-info",
  templateUrl: "./drug-info.component.html",
  styleUrls: ["./drug-info.component.less"],
})
export class DrugInfoComponent implements OnInit {
  @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
  department: any; //所属科室
  drugCode; //编号
  name; //名称
  userType: any; //用户类型
  hosId: any; //院区（搜索）
  userGroup; //所属组
  userGroup1; //所属组(搜索)
  userTypes: Array<any>; //所有用户类型
  alldepart: any = []; //所有所属科室
  alldepart1: any = []; //所有所属科室(搜索)
  hospitals1: any = []; //院区列表(搜索)
	drugTypeData: any = []; //药品类型
  allUserGroup: Array<any>; //所有用户组
  allUserGroup1: Array<any>; //用户组(搜索)
  allUserRole: Array<any>; //所有角色
  pageIndex: number = 1; //页码
  listLength: number = 10; //总条数
  pageSize: number = 10; //每页条数

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

  btnLoading: boolean = false; //提交按钮loading状态
  wxRequired = false; //新增或编辑用户的时候，微信号是否必填
  changeInpSubject = new Subject(); //防抖
  changeInpHospitalSubject = new Subject(); //防抖
  ngOnInit() {
    this.coopBtns = this.tool.initCoopBtns(this.route);
		this.hosId = this.tool.getCurrentHospital().id;
    this.initForm();
		this.getDrugType()
  }

  // 初始化增删改按钮
  coopBtns: any = {};
  // 搜索
  search() {
    this.pageIndex = 1;
    this.getList();
  }
  // 重置
  reset() {
    this.pageIndex = 1;
    this.name = "";
    this.drugCode = "";
    this.getList();
  }
  // 表格数据
  loading1 = false;
  getList() {
    let data = {
      idx: this.pageIndex - 1,
      sum: this.pageSize,
      drugsInfo: {
        drugName: this.name || "",
        drugCode: this.drugCode || "",
        hosId: this.hosId || "" ,
				drugType:{
					id:this.drugTypeData.id
				}
      },
    };
    this.loading1 = true;
    this.mainService
      .getFetchDataList("data", "drugsInfo", data)
      .subscribe((data) => {
        this.loading1 = false;
        this.listOfData = data.list;
        this.listLength = data.totalNum;
      });
  }
	
	// 获取药品类型
	getDrugType(){
		this.mainService.getDictionary("list", "drug_type").subscribe((data) => {
			this.drugTypeData = data.find(i=>i.value=='infusion_solutions')
			this.getList();
		});
	}
	
	lowerChange(e){
		this.validateForm.controls.upperRound.setValue(e+1);
	}
	
	// 监听标识输入
	handleInput(event: KeyboardEvent){
		const input = event.target as HTMLInputElement;
		// 如果输入的不是中文，则允许输入
		if (!input.validity.patternMismatch) {
			this.validateForm.value.drugCode = input.value;
		} else {
			// 重置输入值，不允许输入中文
			input.value = this.validateForm.value.drugCode;
		}
	}
	
  // 新增弹框
  showModal() {
    this.add = true;
		this.modal = true
    this.initForm();
  }
  hideModal() {
    this.modal = false;
    this.initForm();
  }
	
  // 初始化新增form表单
  initForm() {
    this.validateForm = this.fb.group({
      drugName: [null, [Validators.required]],
      drugCode: [null, [Validators.required]],
      specs: [null, [Validators.required]],
      unit: [null, [Validators.required]],
			unitPrice:[null, [Validators.required]],
			packingSpecs:[null, [Validators.required]],
			lowerRound:[null, [Validators.required]],
			upperRound:[null, [Validators.required]],
    });
  }
  // 表单提交
  submitForm(): void {
    var that = this;
		for (const i in that.validateForm.controls) {
		  that.validateForm.controls[i].markAsDirty();
		  that.validateForm.controls[i].updateValueAndValidity();
		}
		if (that.validateForm.invalid) return;
		let form = this.validateForm.value
		if(form.lowerRound >= form.upperRound){
			this.message.error('低舍不能大于或者等于高入')
			return 
		}
		if(form.upperRound >= form.packingSpecs){
			this.message.error('高入不能大于或者等于包装规格')
			return
		}
    let data = {
			...this.validateForm.value,
			id:0,
			drugType:{
				id:this.drugTypeData.id
			},
			hosId:that.hosId
    };
    if (!that.add) {
      data.id = that.coopId;
    }else{
			delete data.id
		}
		that.btnLoading = true;
    that.mainService
      .simplePost("addData", "drugsInfo", 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);
        }
      });
  }

  // 编辑
  edit(data) {
		this.add = false
		this.coopId = data.id;
    this.validateForm.controls.drugName.setValue(data.drugName);
    this.validateForm.controls.drugCode.setValue(data.drugCode);
    this.validateForm.controls.specs.setValue(data.specs);
    this.validateForm.controls.unit.setValue(data.unit);
    this.validateForm.controls.unitPrice.setValue(data.unitPrice);
    this.validateForm.controls.packingSpecs.setValue(data.packingSpecs);
    this.validateForm.controls.lowerRound.setValue(data.lowerRound);
		this.validateForm.controls.upperRound.setValue(data.upperRound);
		this.modal = true
  }

  // 删除
  delModal: boolean = false; //删除模态框
  del(data) {
    let that = this;
    that.coopId = data.id;
    that.delModal = true;
  }
	
	// 取消删除弹框
	cancelDel(){
		this.hideDelModal();
	}
	
  // 确认删除
  confirmDel() {
    let that = this;
    that.btnLoading = true;
    that.mainService
      .coopTypeConfig('rmvData', 'drugsInfo', [this.coopId])
      .subscribe((data) => {
        that.btnLoading = false;
        that.hideDelModal();
        if (data["status"] == 200) {
          that.showPromptModal("删除", true, "");
        } else {
          that.showPromptModal("删除", false, data["msg"]);
        }
      });
  }
	
	// 展示信息提示框（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();
	}
	
  // 关闭删除模态框
  hideDelModal() {
    this.delModal = false;
  }

  // 查看
  detail(id) {
    this.router.navigateByUrl("/main/clinicalUsersManagement/userDetail/" + id);
  }
}

