import { Component, OnInit, Output, Input, ViewChild, ElementRef } from '@angular/core';
import { EventEmitter } from '@angular/core';
import { OverlayScrollbarsComponent } from 'overlayscrollbars-ngx';
import { FormGroup, FormBuilder, FormControl } from '@angular/forms';
import { MainService } from 'src/app/services/main.service';
import { ToolService } from 'src/app/services/tool.service';
import { Subject } from 'rxjs';
import { debounceTime } from 'rxjs/operators';

@Component({
  selector: 'app-build-quick-confirm',
  templateUrl: './build-quick-confirm.component.html',
  styleUrls: ['./build-quick-confirm.component.less']
})
export class BuildQuickConfirmComponent implements OnInit {
  @ViewChild("osComponentRef1", {
    read: OverlayScrollbarsComponent,
    static: false,
  })
  osComponentRef1: OverlayScrollbarsComponent;
  @ViewChild("remarksEle", { static: false }) remarksEle: ElementRef;
  @Output() cancelModal = new EventEmitter();
  @Output() confirmModal = new EventEmitter();
  @Input() buildQuickConfirmData: any = {};//数据
  @Input() loading5: boolean = false;//loading
  hosLoading: boolean = false;//确定按钮的loading
  configurationCenterMenus: any[] = [];//配置中心菜单
  searchAccountSubject = new Subject(); //查工号防抖
  constructor(
    private mainService: MainService,
    private fb: FormBuilder,
    public tool: ToolService,
  ) { }

  ngOnInit() {
    this.getPagePermissionConfigById();
    //防抖
    this.getAccountList();
    this.searchAccountSubject.pipe(debounceTime(500)).subscribe((v:any) => {
      this.getAccountList(v);
    });
  }

  activeTabId:any;
  clickTab(data){
    this.activeTabId = data.id;
    this.newShortcutOrder(data, data.associationType.value);
  }

  // 建单条件
  workOrderRemark = ""; //备注
  customRemarks = []; //备注快速输入
  shortcutMsg; //一键发起信息
  buildMsg: any = {}; //一键发起返回信息
  buildType: string = ""; //快捷建单类型
  historyCustomRemarks = []; //历史快捷输入
  workOrderRemarkTips = ""; //备注提示
  nLoading = false;
	isEndFixedType: boolean = false;
	isStartFixedType: boolean = false;
	msgId:any;
  newShortcutOrder(data, type) {
    this.workOrderRemark = "";
    this.customRemarks = [];
    this.historyCustomRemarks = [];
    console.log(data, type);
    this.buildType = type;
    this.shortcutMsg = data;
    this.initForm();
    this.buildMsg = {};
		this.msgId = data.id;
    let postData:any = {
      taskTypeId: data.id,
    };
    if(data.associationType.value === 'specimen'){
      postData.deptId = this.tool.getCurrentUserDept().id;
    }
    this.nLoading = true;
    this.mainService
      .postCustom("nurse", "workOrder/buildTrip", postData)
      .subscribe((result) => {
        this.buildMsg = result;
				if(result.end){
					if(result.end.end.departmentStrategy==202 ||
					result.end.end.departmentStrategy==204 ||
					result.end.end.departmentStrategy==205){
						this.isEndFixedType = true
					}else{
						this.isEndFixedType = false
					}
				}
				if(result.start){
					if(result.start.start.departmentStrategy==202 ||
					result.start.start.departmentStrategy==204 ||
					result.start.start.departmentStrategy==205){
						this.isStartFixedType = true
					}else{
						this.isStartFixedType = false
					}
				}
        if (result.remarksSwitch == 1) {
          if (result.customRemarks === null || result.customRemarks === "") {
            this.customRemarks = [];
          } else {
            this.customRemarks = result.customRemarks.split("$");
          }
          this.workOrderRemarkTips =
            result.remarksPrompts || "请填写工单备注,不超过100个字符";
          let user = JSON.parse(localStorage.getItem("user"));
          this.mainService
            .postCustom("nurse", "workOrder/recentRemarks", {
              deptId: user.user.dept.id,
              taskTypeId: data.id,
            })
            .subscribe((result1) => {
              this.nLoading = false;
              if (result1.state == 200) {
                this.historyCustomRemarks = result1.data;
              }
            });
        } else {
          this.nLoading = false;
        }
      });
  }

  // 初始化form表单
  shortcutForm: FormGroup; //一键发起建单表单
  initForm() {
    // 初始化一键发起建单表单
    this.shortcutForm = this.fb.group({
      targetOffice: [null, [this.targetOfficeShortCutValidator]],
      originOffice: [null, [this.originOfficeShortCutValidator]],
    });
  }

  // 起点科室校验
  originOfficeShortCutValidator = (control: FormControl): { [s: string]: boolean } => {
    if (this.shortcutForm && this.shortcutForm.value && !control.value && (this.buildMsg.status == 100013 || this.buildMsg.status == 100015)) {
      return { required: true };
    }
  };
  // 目标科室校验
  targetOfficeShortCutValidator = (control: FormControl): { [s: string]: boolean } => {
    if (this.shortcutForm && this.shortcutForm.value && !control.value && (this.buildMsg.status == 100014 || this.buildMsg.status == 100015)) {
      return { required: true };
    }
  };

  // 添加备注
  addRemarks(item) {
    this.remarksEle.nativeElement.focus();
    this.workOrderRemark += item;
  }

  // 目标科室输入搜索
  searchDept(type, msg, e) {
    this.getDeptList(type, msg, e);
  }

  // 获取科室
  isLoading:boolean = false;
  getDeptList(type, msg, key?): void {
    // 返回值的status是201 则是默认发起科室
    // 返回值的status是202 则是固定科室范围
    // 返回值的status是203 则是固定科室
    // 返回值的status是204 则是自主填写
    // 返回值的status是205 则是固定科室类型
    if (
      (type == "start" && msg.start.start.departmentStrategy == 202) ||
      (type == "target" && msg.end.end.departmentStrategy == 202)
    ) {
			let data = [];
			let postData = {
			  taskTypeId: this.msgId
			};
			if(type == "start"){
				this.mainService
				.postCustom("nurse", "workOrder/buildTrip", postData)
				.subscribe((result) => {
					let arr = result.start.start.list;
					if(key!=''){
						data = arr.filter(i=>i.dept.indexOf(key) !=-1)
						msg.start.start.list = data
					}else{
						msg.start.start.list = arr
					}
				});
			}else{
				this.mainService
				.postCustom("nurse", "workOrder/buildTrip", postData)
				.subscribe((result) => {
					let arr = result.end.end.list;
					if(key!=''){
						data = arr.filter(i=>i.dept.indexOf(key) !=-1)
						msg.end.end.list = data
					}else{
						msg.end.end.list = arr
					}
				});
			}
      return; //固定科室范围禁用搜索
    }
    let postData: any = {
      idx: 0,
      sum: 20,
      department: {
        searchType: 1,
        cascadeHosId: this.tool.getCurrentHospital().id
      },
    };
    if (key) {
      postData.department["keyWord"] = key;
    }
    if (type == "start" && msg.start.start.departmentStrategy == 205) {
      postData.department["type"] = { id: msg.start.start.startTypeId };
    } else if (type == "target" && msg.end.end.departmentStrategy == 205) {
      postData.department["type"] = { id: msg.end.end.endTypeId };
    }
    if (type == "start") {
      postData.department["ids"] = msg.start.deptIds || "";
    } else if (type == "target") {
      postData.department["ids"] = msg.end.deptIds || "";
    }
    postData.department.nurseSign = 1;
    this.isLoading = true;
    this.mainService
      .getFetchDataList("data", "department", postData)
      .subscribe((data) => {
        this.isLoading = false;
        if (type == "target") {
          msg.end.end.list = data.list;
        } else if (type == "start") {
          msg.start.start.list = data.list;
        }
      });
  }

  // 工号输入搜索
  searchAccount(e) {
    this.searchAccountSubject.next(e);
  }

  // 根据工号获取用户
  account = null;
  accountList = [];
  getAccountList(key = ''): void {
    let postData = {
      idx: 0,
      sum: 10,
      user: {
        account: key,
        hospital: {
          id: this.tool.getCurrentHospital().id
        }
      }
    };
    this.isLoading = true;
    this.mainService
      .getFetchDataList("data", "user", postData)
      .subscribe((data) => {
        this.isLoading = false;
        this.accountList = data.list || [];
      });
  }

  // 修改工号
  userAccount = null;
  changeAccount(e){
    this.userAccount =this.accountList.find(v => v.id == e);
  }

  // 根据ID获取快捷配置
  pagePermissionConfig: any = {};
  getPagePermissionConfigById() {
    let data = {
			idx: 0,
			sum: 99999,
			pagePermissionConfig: {
        id: this.buildQuickConfirmData.id,
        taskTypeDeptId: this.tool.getCurrentUserDept().id,
      },
		};
		this.mainService
			.getFetchDataList("simple/data", "pagePermissionConfig", data)
			.subscribe((data) => {
				let pagePermissionConfigList = data.list || [];
        if(pagePermissionConfigList.length){
          this.pagePermissionConfig = pagePermissionConfigList[0];

          // 默认选中第一项
          this.pagePermissionConfig.taskTypeList = this.pagePermissionConfig.taskTypeList || [];
          if(this.pagePermissionConfig.taskTypeList.length > 0){
            this.clickTab(this.pagePermissionConfig.taskTypeList[0]);
          }
        }else{
          this.pagePermissionConfig = {};
        }
			});
  }

  // 取消
  cancel() {
    this.cancelModal.emit(false)
  }
  // 确认
  confirm() {
    let taskType = this.pagePermissionConfig.taskTypeList.find(item => item.id == this.activeTabId);
    this.confirmModal.emit({taskType, shortcutForm: this.shortcutForm, buildMsg: this.buildMsg, workOrderRemark: this.workOrderRemark, userAccount: this.userAccount})
  }
}
