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

@Component({
  selector: "app-configuration-system-security",
  templateUrl: "./configuration-system-security.component.html",
  styleUrls: ["./configuration-system-security.component.less"],
})
export class ConfigurationSystemSecurityComponent implements OnInit {
  loading:boolean = false; //页面加载的loading
  btnLoading:boolean = false; //提交按钮的loading
  tabModalName:string = 'characteristics'; //当前选中的tab
  hosId = this.tool.getCurrentHospital().id; //当前院区

	// tab类型
	dictionaryKeyList:any[] = [
		{
			name:'登录安全',key:'login'
		}
	];

  verificationCode:any = [{ label:'是否开启', value: 0 }];//是否需要验证码登录
  digitData:any = [
		{ name:'4位验证码', id: 4 },
		{ name:'6位验证码', id: 6 },
	];//验证码位数
	digit:any; //验证码位数
	validity:any; //验证码有效期
  isErrorTime:any = [{ label:'是否开启', value: 0 }];//是否限制账户错误登录次数
  errorTime:any;//支持错误次数
	verificationCodeNoiseLines:any;//验证码干扰线数量
  astrictIp:any = [{ label:'是否开启', value: 1 }];//终点科室支持核对
  drugsEndCheckScanIds:any = [];//是否限制单点登录ip
  rangeIp:any;//单点登录范围内IP
  // 配置
  configs:any = {};
  // 任务类型
  tasktype:any = {};
  searchTimerSubject = new Subject();
  constructor(private mainService: MainService,private tool: ToolService,private msg: NzMessageService) {}

  ngOnInit():void {
    // todo
    this.searchTimerSubject.pipe(debounceTime(500)).subscribe((v) => {
      let fun = v[0];
      fun.call(this, v[1]);
    });
		this.getConfig();
  }

	// 点击数据字典key
	activeDictionaryKey:any = 'login';
	clickDictionaryKey(item){
	  this.activeDictionaryKey = item.key;
		if(item.key=='login'){
			this.getConfig();
		}
	}

  isLoading: boolean = false;
  // 边输入边搜索节流阀
  searchTimer(fun, e) {
    this.isLoading = true;
    this.searchTimerSubject.next([fun, e]);
  }
	// 添加ip
	ipData:any= [{
		rangeIp:''
	}];
	addIp(){
		this.ipData.push({
			rangeIp:'',
		})
	}
	
	// 删除ip
	delIp(item, index){
		if(this.ipData.length==1){
			return
		}
		this.ipData.splice(index, 1)
	}
	
	// 验证是否有特殊字符
	containsSymbol(str) {
	    return /[^a-zA-Z0-9]/.test(str);
	}
	
  // 保存
  submitForm() {
		if(this.verificationCode[0].checked){
			if(!this.digit){
				this.msg.error('验证码位数不能为空')
				return 
			}
			if(!this.validity){
				this.msg.error('验证码有效期不能为空')
				return 
			}
			if(!this.verificationCodeNoiseLines){
				this.msg.error('验证码干扰线数量不能为空')
				return 
			}
		}
		
		if(this.isErrorTime[0].checked){
			if(!this.errorTime){
				this.msg.error('支持错误次数不能为空')
				return 
			}
		}
		
		// if(this.astrictIp[0].checked){
		// 	let isEmpty = this.ipData.filter(i=>i.rangeIp=='')
		// 	if(isEmpty.length>0){
		// 		this.msg.error('ip不能为空')
		// 		return 
		// 	}
		// }
		
		let filterData = this.initConfig;
		filterData.forEach((item) => {
		 if (item.configKey === "verificationCode") {
				let value = null
				if(this.verificationCode[0].checked){
					value = '1'
				}else{
					value = '0'
				}
		    item.configValue = value;
		  } else if (item.configKey === "verificationCodeLength") {
			  item.configValue = this.digit;
			}else if (item.configKey === "verificationCodeDuration") {
		    item.configValue = this.validity;
		  }else if (item.configKey === "verificationCodeNoiseLines") {
		    item.configValue = this.verificationCodeNoiseLines;
		  }else if (item.configKey === "limitIncorrectLogin") {
		    let value = null
		    if(this.isErrorTime[0].checked){
		    	value = '1'
		    }else{
		    	value = '0'
		    }
		    item.configValue = value;
		  }else if (item.configKey === "incorrectNum") {
				item.configValue = this.errorTime;
		  }else if (item.configKey === "limitSingleLoginIp") {
				// let value = null
				// if(this.astrictIp[0].checked){
				// 	value = '1'
				// }else{
				// 	value = '0'
				// }
				// item.configValue = value;
		  }else if (item.configKey === "ipWhiteList") {
				// let str = JSON.parse(JSON.stringify(this.ipData))
				// let data = str.map(i=>{
				// 	return i.rangeIp
				// })
				// console.log(4444, data)
				// item.configValue = data.join(';');
		  }
		});
		const postData = filterData;
    this.btnLoading = true;
    this.mainService
      .simplePost("addListData", "systemSafeConfig", postData)
      .subscribe((result) => {
        this.btnLoading = false;
        if (result.status == 200) {
          this.getConfig();
        }
      });
  }

  // 获取配置
	initConfig:any;
	config:any;
  getConfig() {
    this.loading = true;
		let postData = null;
		if(this.activeDictionaryKey=='login'){
			postData = {
			  idx: 0,
			  sum: 999,
			  type: 'login'
			};
		}

    this.mainService
      .getFetchDataList("simple/data", "systemSafeConfig", postData)
      .subscribe((result) => {
        this.loading = false;
        if (result.status == 200) {
					if (result.list && Array.isArray(result.list)) {
						this.initConfig = JSON.parse(JSON.stringify(result.list));
						this.config = result.list.map((item) => {
							return [item.configKey, item.configValue, item.id, item.label];
						});
						this.config.forEach((c) => {
							switch (c[0]) {
								case "verificationCode":
									if(c[1]=='1'){
										this.verificationCode[0].checked = true
									}else{
										this.verificationCode[0].checked = false
									}
									break;
								case "verificationCodeLength":
									this.digit = Number(c[1])
									break;	
								case "verificationCodeDuration":
									this.validity = c[1]
									break;
								case "verificationCodeNoiseLines":
									this.verificationCodeNoiseLines = c[1]
									break;
								case "limitIncorrectLogin":
									if(c[1]=='1'){
										this.isErrorTime[0].checked = true
									}else{
										this.isErrorTime[0].checked = false
									}
									break;
								case "incorrectNum":
									this.errorTime = c[1]
									break;	
								case "limitSingleLoginIp":
									// if(c[1]=='1'){
									// 	this.astrictIp[0].checked = true
									// }else{
									// 	this.astrictIp[0].checked = false
									// }
									break;
								case "ipWhiteList":
									// let data = c[1].split(';')
									// this.ipData = []
									// for(let i=0; i<data.length; i++){
									// 	this.ipData.push({
									// 		rangeIp: data[i]
									// 	}) 
									// }
									break;
							}
						});
					} else {
						this.initConfig = [];
						this.config = [];
					}
        }
      });
  }
}
