import { Component, OnInit, Output, Input } from '@angular/core';
import { EventEmitter } from '@angular/core';
import { MainService } from 'src/app/services/main.service';
import { ToolService } from 'src/app/services/tool.service';
import { NzMessageService } from 'ng-zorro-antd';
import { Router, ActivatedRoute } from "@angular/router";

@Component({
  selector: 'app-order-scope',
  templateUrl: './order-scope.component.html',
  styleUrls: ['./order-scope.component.less']
})
export class OrderScopeComponent implements OnInit {
  @Input() hsmsData:any = {
    checkedHos: undefined,
    scopeGroups: [],
    orderScopeRadio: undefined,
		crossHospital: '0',
  }
  @Input() itsmData:any = {
    checkedHos: undefined,
    scopeGroups: [],
    orderScopeRadio: undefined,
  }
	@Input() coopBtns:any;
	@Input() showGovDutyConfig:any;
  @Output() confirmModal = new EventEmitter();
  @Output() cancelModal = new EventEmitter();
  constructor(
    private mainService: MainService,
    private tool: ToolService,
    private message: NzMessageService,
		public router: Router,
		public route: ActivatedRoute
  ) { }

  user = JSON.parse(localStorage.getItem("user")); //用户信息
  checkedHos;//转运-院区
  orderScopeRadio:any = '0';//转运-工单范围
	crossHospital:any = '0';//转运-是否支持跨院区
  itsmCheckedHos:any[] = [];//运维-院区
  itsmCheckedGroup:any[] = [];//运维-分组
  itsmOrderScopeRadio:any = '0';//运维-工单范围
  isAllItsmGroupChecked:boolean = false;//运维-是否全选分组
	isAllItsmReasonGroupChecked:boolean = false;//运维-根据分组显示工单
	itsmCheckedReasonGroup:any[] = [];//运维-根据分组显示工单
	// 工单范选项卡
	scopeTabs:any[] = [];
	activeScopeTab:any;
	//#region 工单范围-运维start
	allDuty:number = 1;
	showReassign:any = 0;
	showGovDuty:any = 0;
	menuList:any;

  ngOnInit() {
		let btn = this.tool.initCoopBtns(this.route)
		console.log(77777,btn)
		let menuItem = JSON.parse(localStorage.getItem("menuItem"))
		this.menuList = menuItem.find(i=>i.link=='gongdanfanwei')
    this.initItsm();
  }

  initHsms(){
    console.log('hsmsData：', this.hsmsData);
    let index = this.scopeTabs.findIndex(v => v.value === 2);
		if(index!=-1){
			this.scopeTabs[index].checked = this.hsmsData.hsmsSwitch;
		}
    this.checkedHos = this.hsmsData.checkedHos;
    this.orderScopeRadio = this.hsmsData.orderScopeRadio;
		this.crossHospital = this.hsmsData.crossHospital+"" || '0';
    this.initOrderScope();
    this.getOrderScope();
  }

  initItsm(){
		if(this.menuList && this.menuList.childrens){
			for(let i of this.menuList.childrens){
				if(i.link=='maintenance'){
					this.scopeTabs.push({ name: '运维', value: 1, checked: false })
				}
				if(i.link=='distributionPj'){
					this.scopeTabs.push({ name: '配送陪检', value: 2, checked: false })
				}
			}
		}

		if(this.scopeTabs.length>0){
			this.activeScopeTab = this.scopeTabs[0]
		}
		this.initHsms();
		this.itsmInitOrderScope();
    console.log('itsmData', this.itsmData);
  }

    itsmInitOrderScope(){
			if(this.scopeTabs.length == 1){
				this.scopeTabs[0].checked = true
			}else if(this.scopeTabs.length == 2){
				let index = this.scopeTabs.findIndex(v => v.value === 1);
				this.scopeTabs[index].checked = this.itsmData.mdv2Switch;
			}
			this.itsmOrderScopeRadio = this.itsmData.orderScopeRadio;
			this.itsmGetOrderScope();
    }
    // 工单范围数据
    itsmGetOrderScope() {
			console.log(444,this.itsmData)
      // 是否不限制部门
      this.allDuty = this.itsmData.allDuty === undefined ? 1 : this.itsmData.allDuty;
      this.showReassign = this.itsmData.showReassign || 0;
			this.showGovDuty = this.itsmData.showGovDuty || 0;
			// 权限内的院区和组
      let hosList = this.user.infoPermission.dutyList || [];
      let groups = this.user.infoPermission.dutyGroupList || [];

      // 选中的院区和组
      let itsmCheckedHos = this.itsmData.checkedHos || [];
      let itsmCheckedGroup = this.itsmData.scopeGroups || [];
			let itsmCheckedReasonGroup = this.itsmData.groupIds || [];
      let hosIds = itsmCheckedHos.map(v => v.id);
      let groupIds = itsmCheckedGroup.map(v => v.id);
			let groupIds2 = itsmCheckedReasonGroup.map(v => v.id);
      this.itsmCheckedHos = hosList.map(v => ({ label: v.hosName, value: v.id, checked: hosIds.includes(v.id) }));
      this.itsmCheckedGroup = groups.filter(v => hosIds.includes(v.hospital.id)).map(v => ({ label: v.hospital.hosName + '-' + v.groupName, value: v.id, checked: groupIds.includes(v.id) }));
      this.isAllItsmGroupChecked = this.itsmCheckedGroup.length ? this.itsmCheckedGroup.every(v => v.checked) : false;
			
			this.itsmCheckedReasonGroup = groups.filter(v => hosIds.includes(v.hospital.id)).map(v => ({ label: v.hospital.hosName + '-' + v.groupName, value: v.id, checked: groupIds2.includes(v.id) }));
			this.isAllItsmReasonGroupChecked = this.itsmCheckedReasonGroup.length ? this.itsmCheckedReasonGroup.every(v => v.checked) : false;
		}

    // 全选、全不选分组
    updateAllItsmGroupChecked(){
      this.itsmCheckedGroup.forEach(v => v.checked = this.isAllItsmGroupChecked);
    }
    // 选择分组
    changeItsmGroup(e){
      this.isAllItsmGroupChecked = this.itsmCheckedGroup.length ? this.itsmCheckedGroup.every(v => v.checked) : false;
    }
		
		// 全选、全不选根据分组显示工单
		updateReasonAllItsmGroupChecked(){
		  this.itsmCheckedReasonGroup.forEach(v => v.checked = this.isAllItsmReasonGroupChecked);
		}
		// 选择根据分组显示工单
		changeItsmReasonGroup(e){
		  this.isAllItsmReasonGroupChecked = this.itsmCheckedReasonGroup.length ? this.itsmCheckedReasonGroup.every(v => v.checked) : false;
		}
    // 选择院区
    changeItsmHospital(hospitalList){
      console.log('hospitalList:', hospitalList)
      // 权限内的院区和组
      let groups = this.user.infoPermission.dutyGroupList || [];

      // 选中的院区和组
      let itsmCheckedHos = this.itsmCheckedHos || [];
      let itsmCheckedGroup = this.itsmCheckedGroup || [];
			let itsmCheckedReasonGroup = this.itsmCheckedReasonGroup|| [];
      let hosIds = itsmCheckedHos.filter(v => v.checked).map(v => v.value);
      let groupIds = itsmCheckedGroup.filter(v => v.checked).map(v => v.value);
			let groupIds2 = itsmCheckedReasonGroup.filter(v => v.checked).map(v => v.value);
      this.itsmCheckedGroup = groups.filter(v => hosIds.includes(v.hospital.id)).map(v => ({ label: v.hospital.hosName + '-' + v.groupName, value: v.id, checked: groupIds.includes(v.id) }));
      console.log('this.itsmCheckedGroup:', this.itsmCheckedGroup)
      this.isAllItsmGroupChecked = this.itsmCheckedGroup.length ? this.itsmCheckedGroup.every(v => v.checked) : false;
			
			this.itsmCheckedReasonGroup = groups.filter(v => hosIds.includes(v.hospital.id)).map(v => ({ label: v.hospital.hosName + '-' + v.groupName, value: v.id, checked: groupIds2.includes(v.id) }));
			this.isAllItsmReasonGroupChecked = this.itsmCheckedReasonGroup.length ? this.itsmCheckedReasonGroup.every(v => v.checked) : false;
		}
    //#endregion 工单范围-运维end

    //#region 工单范围-配送start
    // 工单范围数据
    hosList = []; //院区
    taskTypes = []; //当前权限下所有工单类型
    userGroups = []; //当前权限下所有人员分组
    hosTaskTypes = {}; //当前权限下所有院区对应的任务类型
    hosGroups = {}; //当前权限下所有院区对应的人员分组
    getOrderScope() {
      let hospitals = this.user.infoPermission.hospitals || []
      this.hosList = hospitals.filter(v => !this.tool.isDuty(v));
      this.taskTypes = this.user.infoPermission.taskTypes || [];
      let userGroups = this.user.infoPermission.groups || [];
      this.userGroups = userGroups.filter(v => v.type !== 3);
      this.hosList.forEach((e) => {
        let arrT = [],
          arrG = [];
        this.taskTypes.forEach((el) => {
          if (el.hosId.id == e.id) {
            arrT.push(el);
            this.hosTaskTypes["hos" + e.id] = arrT;
          }
        });

        this.userGroups.forEach((ele) => {
          if (ele.hospital.id == e.id) {
            arrG.push(ele);
            this.hosGroups["hos" + e.id] = arrG;
          }
        });
      });
      console.log(this.hosTaskTypes, this.hosGroups);

      // 工单范围全选按钮是否选中
      this.allTypeChecked = false;
      if (this.user.user.scope && this.user.user.scope.typeIds) {
        if (
          this.user.user.scope.typeIds.length ==
          this.hosTaskTypes["hos" + this.checkedHos].length
        ) {
          this.allTypeChecked = true;
        }
      }
      this.allGroupChecked = false;
      if (this.user.user.scope && this.user.user.scope.groupIds) {
        if (
          this.user.user.scope.groupIds.length ==
          this.hosGroups["hos" + this.checkedHos].length
        ) {
          this.allGroupChecked = true;
        }
      }
    }

    // 工单类型全选
    allTypeChecked: boolean = false; //工单类型全选框
    updateAllTypeChecked() {
      let arr = [];
      this.hosTaskTypes["hos" + this.checkedHos].forEach((e) => {
        arr.push(e.id);
      });
      this.changeTaskTypes(this.allTypeChecked ? arr : [], false);

    }

    // 修改院区
    changeCheckedHos(e){
      this.getTypeAndGroup();
    }

    // 工单类型
    checkedTypes = []; //已选中taskTypes的ID数组
    changeType: boolean = false; //是否改变工单类型
    hosTypesChecked = {}; //当前权限下所有院区下选中的工单类型
    changeTaskTypes(val, isOwn = true) {
      this.checkedTypes = val;
      this.changeType = true;
      this.hosTypesChecked["hos" + this.checkedHos] = val;
      console.log(this.hosTypesChecked);
      if (val.length == this.hosTaskTypes["hos" + this.checkedHos].length) {
        this.allTypeChecked = true;
      } else {
        this.allTypeChecked = false;
      }

      if(isOwn){
        let obj = {};
        console.log('arr:', val)
        console.log('hosTaskTypes:', this.hosTaskTypes)
        val.forEach((e) => {
          obj[e] = true;
        });
        this.initTypes = obj;
      }else{
        let obj = {};
        console.log('arr:', val)
        console.log('hosTaskTypes:', this.hosTaskTypes)
        val.forEach((e) => {
          obj[e] = this.allTypeChecked;
        });
        this.initTypes = obj;
      }
    }

    // 人员分组全选
    allGroupChecked: boolean = false; //工单类型全选框
    updateAllGroupChecked() {
      let arr = [];
      this.hosGroups["hos" + this.checkedHos].forEach((e) => {
        arr.push(e.id);
      });
      this.changeGroups(this.allGroupChecked ? arr : [], false);

    }
    // 人员分组
    checkedGroups = [];
    changeGroup: boolean = false; //是否改变分组
    hosGroupsChecked = {}; //当前权限下所有院区下选中的人员分组
    changeGroups(val, isOwn = true) {
      this.checkedGroups = val;
      this.changeGroup = true;
      this.hosGroupsChecked["hos" + this.checkedHos] = val;
      console.log(this.hosGroupsChecked);
      if (val.length == this.hosGroups["hos" + this.checkedHos].length) {
        this.allGroupChecked = true;
      } else {
        this.allGroupChecked = false;
      }

      if(isOwn){
        let obj = {};
        val.forEach((e) => {
          obj[e] = true;
        });
        this.initGroups = obj;
      }else{
        let obj = {};
        val.forEach((e) => {
          obj[e] = this.allGroupChecked;
        });
        this.initGroups = obj;
      }
    }

    // 工单范围院区切换
    getTypeAndGroup() {
      this.allTypeChecked = false;
      this.allGroupChecked = false;
      for (let k1 in this.initTypes) {
        this.initTypes[k1] = false;
      }
      for (let k1 in this.initGroups) {
        this.initGroups[k1] = false;
      }
      // this.orderScopeRadio = "0";
    }

    // 切换是否不限制部门
    changeAllDuty(e){
      console.log(e);
      this.itsmCheckedHos.forEach(v => (v.checked = false));
      this.itsmCheckedGroup = [];
			this.itsmCheckedReasonGroup = [];
    }

    // 保存工单范围设置
    saveLoading: boolean = false; //保存按钮loading状态
    saveOrderScope() {
      // 配送的院区必填
      let value2 = this.scopeTabs.find(v => v.value == 2 );
			if(value2){
				if(value2.checked && !this.checkedHos){
				  this.message.warning('【配送】的院区必填！')
				  return;
				}
			}

      // 运维限制部门的时候，部门必填
      let value1 = this.scopeTabs.find(v => v.value == 1 );
			if(value1){
				if(value1.checked && !this.itsmCheckedHos.filter(v => v.checked).length && this.allDuty != 1){
				  this.message.warning('【运维】的部门必填！')
				  return;
				}
			}

      this.saveLoading = true;
      let types = [];
      if (!this.changeType) {
        // 没有改变当前工单类型设置，取初始化设置，
        for (var i in this.initTypes) {
          if (this.initTypes[i]) {
            types.push(Number(i));
          }
        }
      } else {
        let arr = this.hosTypesChecked["hos" + this.checkedHos] || [];
        arr.forEach(function (val) {
          types.push(Number(val));
        });
      }

      let groups = [];
      if (!this.changeGroup) {
        // 没有改变当前分组设置，取初始化设置，
        for (var k in this.initGroups) {
          if (this.initGroups[k]) {
            groups.push(Number(k));
          }
        }
      } else {
        let arr = this.hosGroupsChecked["hos" + this.checkedHos] || [];
        arr.forEach(function (val) {
          groups.push(Number(val));
        });
      }
      types = [...new Set(types)];
      groups = [...new Set(groups)];

      let groupsId = [];
      groups.forEach((e) => {
        groupsId.push({ id: e });
      });
      let typesId = [];
      types.forEach((e) => {
        typesId.push({ id: e });
      });

      let itsm = this.scopeTabs.find(v => v.value == 1);
      let hsms = this.scopeTabs.find(v => v.value == 2);

      let postData:any = {
        workerOrderScope: {
          userId: this.user.user.id,
          mdv2Switch: itsm?Number(itsm.checked):null,
          hsmsSwitch: hsms?Number(hsms.checked):null,
          range: 0,
          dutyRange: 0,
        },
      };

      if(itsm && itsm.checked){
        postData.workerOrderScope.allDuty = this.allDuty;
				postData.workerOrderScope.showReassign = this.showReassign;
				postData.workerOrderScope.showGovDuty = this.showGovDuty;
        postData.workerOrderScope.dutyIds = this.itsmCheckedHos.filter(v => v.checked).map(v => v.value).toString() || undefined;
        postData.workerOrderScope.dutyGroupUserRangeIds = this.itsmCheckedGroup.filter(v => v.checked).map(v => v.value).toString() || undefined;
        postData.workerOrderScope.dutyGroupIds = this.itsmCheckedReasonGroup.filter(v => v.checked).map(v => v.value).toString() || undefined;
				postData.workerOrderScope.dutyRange = this.itsmOrderScopeRadio - 0;
      }

      if(hsms && hsms.checked){
        postData.workerOrderScope.hospitalId = this.checkedHos ? { id: this.checkedHos - 0 } : undefined;
        postData.workerOrderScope.typeIds = typesId || undefined;
        postData.workerOrderScope.groupIds = groupsId || undefined;
        postData.workerOrderScope.range = this.orderScopeRadio - 0;
				postData.workerOrderScope.crossHospital = this.crossHospital - 0;
      }
      if (this.user.user.scope && this.user.user.scope.id) {
        postData.workerOrderScope["id"] = this.user.user.scope.id;
      }
			console.log('88888', this.itsmCheckedReasonGroup)
			console.log('999999', postData.workerOrderScope.groupIds)
      console.log('itsmCheckedHos', this.itsmCheckedHos)
      console.log('itsmCheckedGroup', this.itsmCheckedGroup)
      console.log('itsmOrderScopeRadio', this.itsmOrderScopeRadio)
      console.log(postData);
      this.mainService
        .coopTypeConfig("addData", "workerOrderScope", postData)
        .subscribe((data) => {
          this.saveLoading = false;
          this.confirmModal.emit(data);
        });
    }

    // 关闭弹窗
    cancelInit() {
      this.cancelModal.emit();
    }

    // 工单范围设置回显
    initTypes = {}; //工单类型
    initGroups = {}; //人员分组
    initOrderScope() {
      if (!this.user || !this.user.user || !this.user.user.scope) return;
      let scopeInfo = this.user.user.scope;
      if (!this.taskTypes.length) {
        this.initTypes = {};
      } else {
        this.taskTypes.forEach((val, idx) => {
          this.initTypes[val.id] = false;
        });
      }
      if (!scopeInfo.typeIds) {
        this.initTypes = {};
        this.allTypeChecked = false;
      } else {
        scopeInfo.typeIds.forEach((val, idx) => {
          this.initTypes[val.id] = true;
        });
      }

      console.log(this.initTypes);

      if (!this.userGroups || !this.userGroups.length) {
        this.initGroups = {};
      } else {
        this.userGroups.forEach((val, idx) => {
          this.initGroups[val.id] = false;
        });
      }
      if (!scopeInfo.groupIds || !scopeInfo.groupIds.length) {
        this.initGroups = {};
      } else {
        scopeInfo.groupIds.forEach((val, idx) => {
          this.initGroups[val.id] = true;
        });
      }
      console.log(this.initGroups);
      console.log(this.initTypes);
    }
    //#endregion 工单范围-配送end
}
