import { Component, OnInit } from "@angular/core";
import { Router, NavigationStart } from "@angular/router";
import { FormBuilder, Validators, FormGroup, FormControl } from "@angular/forms";
import { NzMessageService } from "ng-zorro-antd/message";
import { MainService } from "../../services/main.service";
import http from "../../../assets/js/http";
import { AES, mode, pad, enc } from "crypto-js";
import { baseUrlType } from "src/app/type/types";
import { ToolService } from 'src/app/services/tool.service';
import { Title } from '@angular/platform-browser';
import { MarkingService } from 'src/app/services/marking.service';

declare var MediaRecorder: any;
@Component({
  selector: "app-login",
  templateUrl: "./login.component.html",
  styleUrls: ["./login.component.less"],
})
export class LoginComponent implements OnInit {
  http: baseUrlType;
  validateForm: FormGroup;
  loading: boolean = false; // 加载状态
  isSingleSignOn: boolean = false; // 是否单点登录
  rooterChange
  constructor(
    private router: Router,
    private fb: FormBuilder,
    private mainService: MainService,
    private msg: NzMessageService,
    private tool: ToolService,
    private titleService: Title,
    private markingService: MarkingService,
  ) {}
  ngOnDestroy() {
    if (this.rooterChange) {
      this.rooterChange.unsubscribe();
    }
  }
  ngOnInit() {
    this.http = http;
		this.getSysConfig();
    this.isSingleSignOn = location.href.includes("?");
		localStorage.removeItem("scanCodeData");
		localStorage.removeItem("pathologyActiveIndex");
    if (this.isSingleSignOn) {
      this.singleSignOn();
    } else {
      this.rooterChange = this.router.events.subscribe(event => {
        if(event instanceof NavigationStart) {
          console.log(event, 'NavigationStart')
          let reg = /^\/login\/?(\d*)$/;
          let isHosIdLogin = reg.test(event.url);
          console.log(isHosIdLogin)
          if(isHosIdLogin){
            // 登录页
            location.reload(true);
          }
        }
      })
      this.initForm();
    }
  }
  //单点登录
	paramsData:any= {};
  singleSignOn() {
    let url = location.href;
    let paramsStr = url.split("?")[1];
    let paramsObj = {};
    paramsStr.split("&").forEach((item) => {
      let arr = item.split("=");
      paramsObj[arr[0] + 1] = arr[1];
    });
		this.paramsData = paramsObj;
		console.log(99999,paramsObj)
    this.singleSignOnLogin(paramsObj);
  }
  // 单点登录
  singleSignOnLogin(paramsObj): void {
    const loadingId = this.msg.loading("登录中..", { nzDuration: 0 }).messageId;
    this.loading = true;
    this.mainService.singleSignOnLogin(paramsObj).subscribe(
      (data) => {
        this.loading = false;
        this.msg.remove(loadingId);
				if(data.status==500){
					this.msg.error(data.remarks, {
					  nzDuration: 2000,
					});
				}else{
					this.apiLogin(data.userId, data.pwd, "", "", true);
				}
      },
      (err) => {
        this.loading = false;
        this.msg.remove(loadingId);
        this.msg.error("登录失败", {
          nzDuration: 2000,
        });
        this.router.navigateByUrl("/login");
      }
    );
  }
  //aes加密
  encryptByEnAES(data: string): string {
    let Key = "dsadmin";
    let tmpAES = AES.encrypt(data, Key, {
      mode: mode.CBC,
      padding: pad.Pkcs7,
    });
    return tmpAES.toString();
  }
  //aes解密
  encryptByDeAES(data: string): string {
    let Key = "dsadmin";
    let tmpDeAES = AES.decrypt(data, Key, {
      mode: mode.CBC,
      padding: pad.Pkcs7,
    });
    return tmpDeAES.toString(enc.Utf8);
  }
  // 初始化菜单
  initMenu(menu) {
    let menuLis = this.transform(menu);
    menuLis.forEach((item) => {
      item.flag = false;
      item.flagBg = false;
      if (item.childrens) {
        item.childrens.forEach((value) => {
          value.flag = false;
        });
      }
    });
    localStorage.setItem("menu", JSON.stringify(menuLis));
    localStorage.setItem("index", "true"); //首页默认高亮
  }
  // 初始化登录表单
  initForm() {
    let username, passsword;
    // 如果本地存储的有remember字段(记住密码功能)
    if (localStorage.getItem("remember")) {
      let remember = JSON.parse(localStorage.getItem("remember"));
      // 比较记住密码的功能是否在有效期内
      if (remember.date > new Date().getTime()) {
        username = this.encryptByDeAES(remember.username);
        passsword = this.encryptByDeAES(remember.password);
      }
    }
    // 初始化登录表单
    this.validateForm = this.fb.group({
      userName: [username || null, [Validators.required]],
      password: [passsword || null, [Validators.required]],
      remember: [Boolean(localStorage.getItem("remember"))],
			code: [null, [Validators.required]]
    });
		
		if(this.isSingleSignOn){
			this.validateForm.removeControl('code');
		}else{
			this.validateForm.addControl('code', new FormControl(null, Validators.required));
		}
  }
	// 重新请求验证码
	resetCode(){
		this.getCode()
	}
	
	// 获取系统安全配置
	verificationCode:any;
	getSysConfig(){
		this.tool.getSysNameAndLogoAsync().subscribe(result => {
			this.verificationCode = result.verificationCode;
			if(this.verificationCode==1){
				this.getCode();
			}
		})
	}
	
	// 获取验证码
	loginImg:any;
	captchaId:any;
	getCode(){
		this.mainService.getLoginCode({}).subscribe((data:any)=> {
			if(data.status==200){
				this.captchaId = data.data.captchaId
				this.loginImg = data.data.image
			}
		})
	}
	
  // enter触发
  enterUp(e): void {
    let keyCode = e.which || e.keyCode || 0;
    if (keyCode == 13) {
      this.submitForm();
    }
  }
  // 登录
  submitForm(): void {
    for (const i in this.validateForm.controls) {
      this.validateForm.controls[i].markAsDirty();
      this.validateForm.controls[i].updateValueAndValidity();
    }
    // 用户名和密码必填
    if (
      !this.validateForm.value.userName ||
      !this.validateForm.value.password
    ) {
      this.msg.info("用户名或密码不能为空！");
      return;
    }
		if(!this.isSingleSignOn && this.verificationCode==1){
			if (
			  !this.validateForm.value.code) {
			  this.msg.info("验证码不能为空！");
			  return;
			}
			this.apiLogin(
			  this.validateForm.value.userName,
			  this.validateForm.value.password,
				this.validateForm.value.code,
				this.captchaId
			);
		}else{
			this.apiLogin(
			  this.validateForm.value.userName,
			  this.validateForm.value.password
			);
		}

  }
  // 登录接口,true是单点登录
	errorTip:any;
  apiLogin(user, pwd, captcha="", captchaId="", flag = false) {
    const loadingId = this.msg.loading("登录中..", { nzDuration: 0 }).messageId;
    this.loading = true;
    this.mainService.login(user, pwd, captcha, captchaId).subscribe((data) => {
      this.loading = false;
      this.msg.remove(loadingId);
      if (data.status == 200) {
        if (!flag) {
          // 记住密码勾选中
          if (this.validateForm.value.remember) {
            let remember = {
              username: this.encryptByEnAES(this.validateForm.value.userName),
              password: this.encryptByEnAES(this.validateForm.value.password),
              date: new Date().getTime() + 90 * 24 * 3600 * 1000, //3个月
            };
            localStorage.setItem("remember", JSON.stringify(remember));
          } else {
            localStorage.removeItem("remember");
          }
        }
        // 重置系统名称和大屏名称
        console.log(data.user);
        let hosId = data.user.user.currentHospital ? data.user.user.currentHospital.id : ''
        this.tool.getSysNameAndLogoAsync(hosId).subscribe(result => {
					// this.verificationCode = result.verificationCode;
          let marking = result.project || '';
          let logoTitle = result.sysName || '';
          let logoUrl = location.origin + '/file' + result.logo || '';
          let faviconUrl = location.origin + '/file' + result.favicon || '';
          this.markingService.setMarking(marking);
          this.tool.setSysName(logoTitle);
          this.tool.setLogo(logoUrl);
          this.tool.setFavicon(faviconUrl);
          this.titleService.setTitle(this.tool.logoTitle);
          (document.querySelector('#favicon') as any).href = this.tool.faviconUrl;
					this.toRoute2(data);
          this.initMenu(data.user.menu);
        })
				this.errorTip = null;
      } else if(data.status == 501){
				this.msg.error('验证码错误', {
				  nzDuration: 2000,
				});
				this.errorTip = null;
      } else if(data.status == 506){
				this.errorTip = data.tips
				this.msg.error(data.remarks, {
				  nzDuration: 2000,
				});
				this.resetCode()
      }else {
				this.errorTip = null;
				this.resetCode()
				this.msg.error(data.remarks, {
				  nzDuration: 2000,
				});
			}
    });
  }
  // 页面跳转
  toRoute2(data) {
    let roleMenus = data.user.menu;
    let canLogin = false; //是否可以进入系统主页面(无护士端，调度台，药房端权限)
    let successLoginMsg = true; //登录成功提示,true是提示，false不提示
		let sy = false;
    let fwt = false;
    let ddt = false;
		let bbj = false;
		let mzbl = false;
		let bljjb = false;
		let blk = false;
		let web = false;
    let yfang = false;
		let gglb = false;
		let gzgd = false;
    roleMenus.forEach((e) => {
			if (e.link == "home") {
			  sy = true;
			  console.log("首页");
			}else if (e.link == "pharmacy") {
        yfang = true;
        console.log("药房端");
      } else if (e.link == "nurse") {
				console.log(44,e.link)
        fwt = true;
        console.log("护士端");
      } else if (e.link == "dispatchingDesk") {
        ddt = true;
        console.log("调度台");
      } else if (e.link == "specimenRoomView") {
        bbj = true;
        console.log("标本间端");
      } else if (e.link == "pathologySample") {
        mzbl = true;
        console.log("门诊病理采样端");
      } else if (e.link == "pathologyCommunicationBook") {
        bljjb = true;
        console.log("病理交接本");
      } else if (e.link == "pathology") {
        blk = true;
        console.log("病理科端");
      } else if (e.link == "webRepairs") {
        web = true;
        console.log("web报修");
      }else if (e.link == "orderManagement") {
        gglb = true;
        console.log("工单列表");
      }else if (e.link == "incidentManagement") {
        gzgd = true;
        console.log("故障工单");
      }
      canLogin = true;
    });
		localStorage.setItem("bookBatchNo",'')
		localStorage.setItem("specimenBatchNo",'')
		if(this.paramsData.toPage1 && (this.paramsData.cardNO1 || this.paramsData.pathologyFormCode1)){
			this.msg.success("登录成功！", {
			  nzDuration: 2000,
			});
			successLoginMsg = false;
			localStorage.setItem("user", JSON.stringify(data.user));
			let query = {
				cardNO:'',
				pathologyFormCode:''
			}
			if(this.paramsData.cardNO1){
				query.cardNO = this.paramsData.cardNO1
				delete query.pathologyFormCode
			}else{
				query.pathologyFormCode = this.paramsData.pathologyFormCode1
				delete query.cardNO
			}
			this.router.navigate([`/${this.paramsData.toPage1}`, query])
			return
		}
    if (fwt) {
      // 护士角色跳护士端
      if (successLoginMsg) {
        this.msg.success("登录成功！", {
          nzDuration: 2000,
        });
      }
      successLoginMsg = false;
      localStorage.setItem("user", JSON.stringify(data.user));
      this.router.navigateByUrl("/nurse");

      return;
    } else if (ddt) {
      // 调度台
      if (successLoginMsg) {
        this.msg.success("登录成功！", {
          nzDuration: 2000,
        });
      }
      successLoginMsg = false;
      localStorage.setItem("user", JSON.stringify(data.user));
      this.router.navigateByUrl("/dispatchingDesk");
      return;
    } else if (bbj) {
      // 标本间端
      if (successLoginMsg) {
        this.msg.success("登录成功！", {
          nzDuration: 2000,
        });
      }
      successLoginMsg = false;
      localStorage.setItem("user", JSON.stringify(data.user));
      this.router.navigateByUrl("/specimenRoomView");
      return;
    }else if (mzbl) {
      // 门诊病理采样端
      if (successLoginMsg) {
        this.msg.success("登录成功！", {
          nzDuration: 2000,
        });
      }
      successLoginMsg = false;
      localStorage.setItem("user", JSON.stringify(data.user));
      this.router.navigateByUrl("/pathologySample");
      return;
    }else if (bljjb) {
      // 病理交接本
      if (successLoginMsg) {
        this.msg.success("登录成功！", {
          nzDuration: 2000,
        });
      }
      successLoginMsg = false;
      localStorage.setItem("user", JSON.stringify(data.user));
      this.router.navigateByUrl("/pathologyCommunicationBook");
      return;
    }else if (blk) {
      // 病理科端
      if (successLoginMsg) {
        this.msg.success("登录成功！", {
          nzDuration: 2000,
        });
      }
      successLoginMsg = false;
      localStorage.setItem("user", JSON.stringify(data.user));
      this.router.navigateByUrl("/pathology");
      return;
    }else if (web) {
      // web报修
      if (successLoginMsg) {
        this.msg.success("登录成功！", {
          nzDuration: 2000,
        });
      }
      successLoginMsg = false;
      localStorage.setItem("user", JSON.stringify(data.user));
      this.router.navigateByUrl("/webRepairs");
      return;
    }else if (yfang) {
      // 药房端2
      if (successLoginMsg) {
        this.msg.success("登录成功！", {
          nzDuration: 2000,
        });
      }
      successLoginMsg = false;
      localStorage.setItem("user", JSON.stringify(data.user));
      this.router.navigateByUrl("/pharmacy2");
      return;
    }
    // 有菜单可以进入系统主页面
    if (!canLogin) {
      this.msg.error("暂无权限进入系统！", {
        nzDuration: 2000,
      });
    } else {
			if(!gglb && !gzgd && !sy){
				this.msg.error("暂无权限进入系统！", {
				  nzDuration: 2000,
				});
				return
			}
      if (successLoginMsg) {
        this.msg.success("登录成功！", {
          nzDuration: 2000,
        });
      }
      successLoginMsg = false;
			localStorage.setItem("user", JSON.stringify(data.user));
			if(gglb){
				this.router.navigateByUrl("/main/orderManagement");
				return
			}else if(gzgd){
				this.router.navigateByUrl("/main/incidentManagement");
				return
			}
			if(gglb && gzgd && sy){
				this.router.navigateByUrl("/main/home");
			}
			if(!gglb && !gzgd && sy){
				this.router.navigateByUrl("/main/home");
			}
    }
  }
  // 处理树数据（parent格式转为children格式）
  transform(nodes): any {
    let parents = [];
    const idMapping = nodes.reduce((acc, el, i) => {
      acc[el.id] = i;
      return acc;
    }, {});
    nodes.forEach((el) => {
      if (el.parentid === null || el.parentid === undefined) {
        parents.push(el);
      } else {
        const parentEl = nodes[idMapping[el.parentid]];
        parentEl.childrens = [...(parentEl.childrens || []), el];
      }
    });
    return parents;
  }

  // 录屏
  isRecording:boolean = false;
  async showScreen(e){
    if(this.isRecording || !navigator.mediaDevices){
      return;
    }
    e.preventDefault();
    let stream = await (navigator.mediaDevices as any).getDisplayMedia({ video: true });
    let mime = MediaRecorder.isTypeSupported("video/webm; codecs=vp9") ? "video/webm; codecs=vp9" : "video/webm";

    let mediaRecorder = new MediaRecorder(stream, { mimeType: mime });
    let chunks = [];
    //录制
    mediaRecorder.addEventListener('dataavailable', (e) => {
      this.isRecording = true;
      chunks.push(e.data)
    })
    //停止
    mediaRecorder.addEventListener('stop', () => {
      let blob = new Blob(chunks, { type: chunks[0].type });
      let url = URL.createObjectURL(blob);
      let a = document.createElement('a');
      a.href = url;
      a.download = 'video.webm';
      a.click();
      this.isRecording = false;
    })
    //手动启动
    mediaRecorder.start()
  }
}
