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 { WebsocketIncomingService } from 'src/app/services/websocket-incoming.service';
import { Router } from "@angular/router";

@Component({
  selector: 'app-bind-extension-number',
  templateUrl: './bind-extension-number.component.html',
  styleUrls: ['./bind-extension-number.component.less']
})
export class BindExtensionNumberComponent implements OnInit {
  @Input() websocketLoading:boolean = false;
  @Input() hsmsData:any = {
    checkedHos: undefined,
    scopeGroups: [],
    orderScopeRadio: undefined,
  }
  @Input() itsmData:any = {
    checkedHos: undefined,
    scopeGroups: [],
    orderScopeRadio: undefined,
  }
  @Output() confirmModal = new EventEmitter();
  @Output() cancelModal = new EventEmitter();
	@Input() coopBtns:any;
  constructor(
    private mainService: MainService,
    private tool: ToolService,
    private message: NzMessageService,
    private icomingService: WebsocketIncomingService,
		public router: Router
  ) { }

  user = JSON.parse(localStorage.getItem("user")); //用户信息
  isLoading:boolean = false;
  formData1:any = {};
  formData2:any = {};
  hospitalList:any[] = [];

  // 工单范选项卡
  scopeTabs:any[] = [];
  activeScopeTab:any;
	menuList:any;

  ngOnInit() {
    // console.log('itsmData', this.itsmData);
    // console.log('hsmsData', this.hsmsData);
		let menuItem = JSON.parse(localStorage.getItem("menuItem"))
		this.menuList = menuItem.find(i=>i.link=='bangdingfenji')
		// console.log(111, this.menuList);
		this.init()
    this.getHospitalList();
    this.getHjzxCornetList();
    this.getCallCenterConfig();
  }

	init(){
		if(this.menuList && this.menuList.childrens){
			for(let i of this.menuList.childrens){
				if(i.link=='extension'){
					this.scopeTabs.push({ name: '分机绑定', value: 1, checked: false })
				}
				if(i.link=='callCenter'){
					this.scopeTabs.push({ name: '呼叫中心', value: 2, checked: false })
				}
			}
		}
		if(this.scopeTabs.length>0){
			this.activeScopeTab = this.scopeTabs[0]
		}
		if(this.scopeTabs.length == 1){
			this.scopeTabs[0].checked = true
		}
	}

  // 获取院区列表
  getHospitalList() {
    // 工单范围
    // 运维不限制部门，则取权限下的所有院区和部门
    // 运维限制部门，则取运维选中的部门和配送选中的院区
    if(this.itsmData.mdv2Switch){
      // 开通运维
      if(this.itsmData.allDuty === 1){
        // 不限制部门
        this.hospitalList = this.user.infoPermission.hospitals || [];
        // let hospitals = this.user.infoPermission.hospitals || [];
        // let dutyList = this.user.infoPermission.dutyList || [];
        // this.hospitalList = hospitals.concat(dutyList);
      }else{
        // 限制部门
        if(this.hsmsData.hsmsSwitch){
          // 开通配送
          this.hospitalList = this.itsmData.checkedHos.concat(this.hsmsData.checkedHosDTO);
        }else{
          // 未开通配送
          this.hospitalList = this.itsmData.checkedHos;
        }
      }
    }else{
      // 未开通运维
      if(this.hsmsData.hsmsSwitch){
        // 开通配送
        this.hospitalList = [this.hsmsData.checkedHosDTO];
      }else{
        // 未开通配送
        this.hospitalList = [];
      }
    }
  }

  //获取呼叫中心分机号码
  hjzxCornetList:any[] = [];
  getHjzxCornetList() {
    this.isLoading = true;
    this.mainService.getDictionary('list', 'hjzx_cornet').subscribe((data) => {
      this.isLoading = false;
      this.hjzxCornetList = data || [];
    });
  }

  // 获取呼叫中心服务连接地址
  callCenterConfigObj:any = {};
  getCallCenterConfig() {
    let data = {
      idx: 0,
      sum: 9999,
      callCenterConfig: {},
    };
    this.mainService
      .getFetchDataList("simple/data", "callCenterConfig", data)
      .subscribe((data) => {
        if (data.status == 200) {
          let list = data.list || [];
          this.callCenterConfigObj = list.length ? list[0] : {};
        }else{
          this.message.error(data.msg || "请求数据失败");
        }
      });
  }

  // 修改院区
  changeHospital(hosId){
    this.phoneNumList = [];
    this.getPhoneNumList(hosId);
  }



  // 修改选项卡-是否启动
  changeFlag(flag, item){
    this.activeScopeTab = item;
    if(flag){
      this.scopeTabs.forEach(v => {
        if(v.value != item.value){
          v.checked = false;
        }
      })
    }
  }

  //获取所有分机号码列表
  phoneNumList:any[] = [];
  getPhoneNumList(hosId) {
    this.isLoading = true;
    let postData = {
      idx: 0,
      sum: 100,
      hospitalConfig: { hosId },
    };
    this.mainService
      .getFetchDataList("simple/data", "hospitalConfig", postData)
      .subscribe((result) => {
        this.isLoading = false;
        this.phoneNumList = result.list.filter((item) => item.key.includes("phone_num_port") && item.value);
        console.log('this.phoneNumList:', this.phoneNumList)
      });
  }

  // 保存工单范围设置
  saveOrderScope() {
    let startObj = this.scopeTabs.find((item) => item.checked);
    if(startObj){
      if(startObj.value == 1){
        // 录音盒
        if(!this.formData1.number){
          this.message.warning('请选择【分机绑定】分机号码')
          return;
        }
        this.icomingService.setSign('box');
        this.confirmModal.emit(this.formData1.number);
      }else if(startObj.value == 2){
        // 呼叫中心
        if(!this.formData2.number){
          this.message.warning('请选择【呼叫中心】分机号码')
          return;
        }
        if(!this.callCenterConfigObj.socketUrl.trim()){
          this.message.warning('呼叫中心服务连接地址未配置，请前往配置中心->三方配置中配置')
          return;
        }
        this.icomingService.setSign('callCenter');
        this.icomingService.setSocketUrl(this.callCenterConfigObj.socketUrl);
        this.confirmModal.emit(this.formData2.number);
      }
    }else{
      this.message.warning('请启动分机号码或呼叫中心')
    }
  }

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