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

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

  coopData: any = {}; //当前操作列
	hosId:any;
	hospitals:any = [];
	isDeptLoading: boolean = false;

	currentHospital:any;
	malfunctionData:any = [];
	malfunctionInspectData:any = [];
	allUserGroup:any = [];
	userData:any = [];

  changeCommonInpSubject = new Subject();

  ngOnInit() {
		this.changeCommonInpSubject.pipe(debounceTime(500)).subscribe((v) => {
      if(v[0] === 'taskType'){
        this.getTaskTypeList(v[1]);
      }else if(v[0] === 'taskTypeInspect'){
        this.getTaskTypeInspectList(v[1]);
      }
    });

    // 优先级
    setTimeout(() => {
      this.tablePriorityHeight = document.querySelector('#priorityTable').clientHeight - document.querySelector('#priorityTable .list-template__top').clientHeight - 8 - document.querySelector('#priorityTable .thead').clientHeight;
    }, 100)
		this.hosId = this.tool.getCurrentHospital().id;
		this.currentHospital = this.tool.getCurrentHospital();
    this.getCommonFaultsList();
		this.getTaskTypeList();
		this.getTaskTypeInspectList();
    this.getPagePermissionIcon();
    this.getPagePermissionBussType();
    this.getPagePermissionQuickOperation();
  }

  // 新增优先级弹框
  modelName = ""; //模态框名称
  modalPriority: boolean = false; //新增/编辑模态框
  add: boolean; //true:新增；false:编辑
  addPriorityModal() {
    this.modelName = "新增";
    this.add = true; //新增
    this.modalPriority = true;
    this.initForm();
  }
  //关闭新增/编辑弹框
  hidePriorityModal() {
    this.modalPriority = false;
  }

  changeCommonInp(type, e) {
    this.changeCommonInpSubject.next([type, e]);
  }

	// 获取任务类型数据-标本，其他，万能
  isLoading:boolean = false;
	getTaskTypeList(keyWord?){
		let postData = {
      idx: 0,
      sum: 9999,
		  taskType: {
        taskName: keyWord,
        hosIds: this.hosId,
        assTypeValues: 'specimen,other,ordinary',
        simpleQuery: true,
		  },
		};
    this.isLoading = true;
		this.mainService.getFetchDataList('configuration', "taskType", postData).subscribe(data => {
		  this.isLoading = false;
      if (data.status == 200) {
        this.malfunctionData = data.list || [];
      }
		})
	}

	// 获取任务类型数据-陪检
	getTaskTypeInspectList(keyWord?){
		let postData = {
      idx: 0,
      sum: 9999,
		  taskType: {
        taskName: keyWord,
        hosIds: this.hosId,
        assTypeValues: 'inspect',
        simpleQuery: true,
		  },
		};
    this.isLoading = true;
		this.mainService.getFetchDataList('configuration', "taskType", postData).subscribe(data => {
		  this.isLoading = false;
      if (data.status == 200) {
        this.malfunctionInspectData = data.list || [];
      }
		})
	}

  // 获取字典数据-图标名称
  pagePermissionIconList: any[] = [];
  getPagePermissionIcon() {
    this.mainService
      .getDictionary("list", "page_permission_icon")
      .subscribe((data) => {
        this.pagePermissionIconList = data;
      });
  }

  // 获取字典数据-关联业务
  pagePermissionBussTypeList: any[] = [];
  getPagePermissionBussType() {
    this.mainService
      .getDictionary("list", "page_permission_buss_type")
      .subscribe((data) => {
        this.pagePermissionBussTypeList = data;
      });
  }

  // 获取字典数据-快捷操作
  pagePermissionQuickOperationList: any[] = [];
  getPagePermissionQuickOperation() {
    this.mainService
      .getDictionary("list", "page_permission_quick_operation")
      .subscribe((data) => {
        this.pagePermissionQuickOperationList = data;
      });
  }

  // 获取字典数据-是否显示标本数量
  gdEmergencyList: any[] = [
    { value: 1, label: '急标数量', checked: false },
    { value: 2, label: '普标数量', checked: false },
  ];

  // 修改关联业务
  changeBussType(e){
    console.log(e);
    this.validatePriorityForm.controls.quickOperation.setValue(null);
    this.validatePriorityForm.controls.taskTypeIds.setValue([]);
    this.validatePriorityForm.controls.taskTypeInspectIds.setValue(null);
    this.validatePriorityForm.controls.urgentIds.setValue(this.gdEmergencyList.map(v => {v.checked = false;return v;}));

    if(e === 'service'){
      this.requiredChange('quickOperation', true);
      this.requiredChange('taskTypeIds', false);
      this.requiredChange('taskTypeInspectIds', false);
      this.requiredChange('urgentIds', false);
    }else if(e === 'goods'){
      this.requiredChange('quickOperation', false);
      this.requiredChange('taskTypeIds', true);
      this.requiredChange('taskTypeInspectIds', false);
      this.requiredChange('urgentIds', false);
    }else if(e === 'inspect'){
      this.requiredChange('quickOperation', false);
      this.requiredChange('taskTypeIds', false);
      this.requiredChange('taskTypeInspectIds', true);
      this.requiredChange('urgentIds', false);
    }
  }

  // 修改任务类型
  hasSpecimen:boolean = false;
  changeTaskTypeIds(e){
    console.log(e);
    let o = this.malfunctionData.find(v => v.associationType.value === 'specimen');
    this.hasSpecimen = e.some(v => v === o.id);
    this.validatePriorityForm.controls.urgentIds.setValue(this.gdEmergencyList.map(v => {v.checked = false;return v;}));

    this.requiredChange('urgentIds', this.hasSpecimen);
  }

  requiredChange(field, required: boolean): void {
    if (!required) {
      this.validatePriorityForm.get(field)!.clearValidators();
      this.validatePriorityForm.get(field)!.markAsPristine();
    } else {
      this.validatePriorityForm.get(field)!.setValidators(Validators.required);
      this.validatePriorityForm.get(field)!.markAsDirty();
    }
    this.validatePriorityForm.get(field)!.updateValueAndValidity();
  }

  // 编辑
  editPriority(data) {
    console.log(data);
    this.modelName = "编辑";
    this.add = false;
    this.modalPriority = true;
    this.initForm();
    this.coopData = data;

    this.changeBussType(data.bussType.value);
    if(data.bussType.value === 'goods'){
      data.taskTypeIds && this.changeTaskTypeIds(data.taskTypeIds.split(',').map(v => +v));
    }

    this.validatePriorityForm.controls.orders.setValue(data.orders);
    this.validatePriorityForm.controls.icon.setValue(data.icon.id);
    this.validatePriorityForm.controls.name.setValue(data.name);
    this.validatePriorityForm.controls.bussType.setValue(data.bussType.value);
    data.quickOperation && this.validatePriorityForm.controls.quickOperation.setValue(data.quickOperation.id);
    if(data.bussType.value === 'goods'){
      data.taskTypeIds && this.validatePriorityForm.controls.taskTypeIds.setValue(data.taskTypeIds.split(',').map(v => +v));
    }else if(data.bussType.value === 'inspect'){
      data.taskTypeIds && this.validatePriorityForm.controls.taskTypeInspectIds.setValue(+data.taskTypeIds);
    }
    if(data.urgentIds){
      let ids = data.urgentIds.split(',').map(v => +v);
      let urgentIds = this.gdEmergencyList.map(v => {
        v.checked = ids.includes(v.value);
        return v;
      })
      this.validatePriorityForm.controls.urgentIds.setValue(urgentIds);
    }
    this.validatePriorityForm.controls.active.setValue(data.active);
  }

  // 新增/编辑表单提交
  btnLoading: boolean = false; //提交按钮loading状态
  submitPriorityForm(): void {
    for (const i in this.validatePriorityForm.controls) {
      this.validatePriorityForm.controls[i].markAsDirty();
      this.validatePriorityForm.controls[i].updateValueAndValidity();
    }
    if (this.validatePriorityForm.invalid) {
      return;
    }
    console.log(this.validatePriorityForm.value);
    this.btnLoading = true;
    let postData:any = {};
    let taskTypeIds;
    if(this.validatePriorityForm.value.bussType === 'goods'){
      taskTypeIds = this.validatePriorityForm.value.taskTypeIds.length ? this.validatePriorityForm.value.taskTypeIds.toString() : undefined
    }else if(this.validatePriorityForm.value.bussType === 'inspect'){
      taskTypeIds = this.validatePriorityForm.value.taskTypeInspectIds ? this.validatePriorityForm.value.taskTypeInspectIds.toString() : undefined
    }
    if (this.add) {
      //增加
      postData = {
        hosId: this.hosId,
        orders: this.validatePriorityForm.value.orders,
        icon: this.validatePriorityForm.value.icon ? { id: this.validatePriorityForm.value.icon } : undefined,
        name: this.validatePriorityForm.value.name,
        bussType: this.validatePriorityForm.value.bussType ? this.pagePermissionBussTypeList.find(v => v.value === this.validatePriorityForm.value.bussType) : undefined,
        quickOperation: this.validatePriorityForm.value.quickOperation ? { id: this.validatePriorityForm.value.quickOperation } : undefined,
        taskTypeIds,
        urgentIds: this.validatePriorityForm.value.urgentIds.length ? this.validatePriorityForm.value.urgentIds.filter(v => v.checked).map(v => v.value).toString() : undefined,
        active: this.validatePriorityForm.value.active,
      };
    } else {
      //编辑
      postData = {
				...this.coopData,
				orders: this.validatePriorityForm.value.orders,
        icon: this.validatePriorityForm.value.icon ? { id: this.validatePriorityForm.value.icon } : undefined,
        name: this.validatePriorityForm.value.name,
        bussType: this.validatePriorityForm.value.bussType ? this.pagePermissionBussTypeList.find(v => v.value === this.validatePriorityForm.value.bussType) : undefined,
        quickOperation: this.validatePriorityForm.value.quickOperation ? { id: this.validatePriorityForm.value.quickOperation } : undefined,
        taskTypeIds,
        urgentIds: this.validatePriorityForm.value.urgentIds.length ? this.validatePriorityForm.value.urgentIds.filter(v => v.checked).map(v => v.value).toString() : undefined,
        active: this.validatePriorityForm.value.active,
      };
    }
    console.log(postData);
    this.mainService
      .simplePost("addData", "pagePermissionConfig", postData)
      .subscribe((result) => {
        this.btnLoading = false;
        this.hidePriorityModal();
        let msg = "";
        if (this.add) {
          msg = "新增";
        } else {
          msg = "修改";
        }
        if (result.status == 200) {
          this.showPromptModal(msg, true, '');
        } else {
          this.showPromptModal(msg, false, result.msg);
        }
      });
  }

  // 初始化新增form表单
  validatePriorityForm: FormGroup; //新增/编辑表单
  initForm() {
    this.validatePriorityForm = this.fb.group({
      orders: [0, [Validators.required]],//排序号
      icon: [null, [Validators.required]],//图标名称
      name: [null, [Validators.required]],//按钮名称
      bussType: [null, [Validators.required]],//关联业务
      quickOperation: [null, [Validators.required]],//快捷操作
      taskTypeIds: [[], [Validators.required]],//关联任务类型-标本，其他，万能
      taskTypeInspectIds: [null, [Validators.required]],//关联任务类型-陪检
      urgentIds: [this.gdEmergencyList.map(v => {v.checked = false;return v;}), [Validators.required]],//是否显示标本数量
      active: [0, [Validators.required]],//是否启用
    });
    console.log(this.validatePriorityForm.controls)
  }

  // 获取列表
  loading1:boolean = false;
  commonFaultsList: any[] = []; //表格数据
  tablePriorityHeight:number = 0;
  getCommonFaultsList() {
    let data = {
			idx: 0,
			sum: 99999,
			pagePermissionConfig: {
        hosId: this.hosId,
      },
		};
		this.loading1 = true;
		this.mainService
			.getFetchDataList("simple/data", "pagePermissionConfig", data)
			.subscribe((data) => {
				this.loading1 = false;
				this.commonFaultsList = data.list || [];
			});
  }

  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;
    console.log(this.coopData);
    this.tipsMsg1 = tipsMsg1;
    this.tipsMsg2 = tipsMsg2;
  }
  // 隐藏删除框
  hideDelModal() {
    this.delModal = false;
  }
  // 确认删除
  confirmDel() {
    this.btnLoading = true;
		//删除-优先级
		this.mainService
			.simplePost("rmvData", "pagePermissionConfig", [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.getCommonFaultsList();
  }
}
