import { Component, OnInit, ViewChild } from "@angular/core";
import { ActivatedRoute, Router } from "@angular/router";
import { FormBuilder, Validators, FormGroup } from "@angular/forms";

import { MainService } from "../../services/main.service";
import { OverlayScrollbarsComponent } from "overlayscrollbars-ngx";
import { ToolService } from "../../services/tool.service";
import { forkJoin, Subject } from "rxjs";
import { debounceTime, filter } from "rxjs/operators";
import { NzMessageService } from "ng-zorro-antd";

import host from "../../../assets/js/http";
import { HttpRequest, HttpResponse, HttpClient } from '@angular/common/http';

@Component({
  selector: "app-users-management",
  templateUrl: "./users-management.component.html",
  styleUrls: ["./users-management.component.less"],
})
export class UsersManagementComponent implements OnInit {
  @ViewChild("osComponentRef1", {
    read: OverlayScrollbarsComponent,
    static: false,
  })
  osComponentRef1: OverlayScrollbarsComponent;
  constructor(
    private message: NzMessageService,
    private fb: FormBuilder,
    private route: ActivatedRoute,
    private router: Router,
    private mainService: MainService,
    private tool: ToolService,
    private http: HttpClient,
  ) {}

  listOfData: any[] = []; //表格数据

  modal: boolean = false; //新增/编辑模态框
  add: boolean; //true:新增；false:编辑
  validateForm: FormGroup; //新增/编辑表单
  coopId: number; //表格中执行操作的id
  department: any; //所属科室
  num; //工号
  name; //姓名
  userType: any; //用户类型
  hosId: any; //院区（搜索）
  userGroup; //所属组
  userGroup1; //所属组(搜索)
  userTypes: Array<any> = []; //所有用户类型
  alldepart: any = []; //所有所属科室
  alldepart1: any = []; //所有所属科室(搜索)
  allcompany: any = []; //所有所属公司
  allUserGroup: Array<any>; //所有用户组
  allUserGroup1: Array<any>; //用户组(搜索)
  allUserRole: Array<any>; //所有角色
  pageIndex: number = 1; //页码
  listLength: number = 10; //总条数
  pageSize: number = 10; //每页条数

  promptContent: string; //操作提示框提示信息
  ifSuccess: boolean; //操作成功/失败
  promptInfo: string; //操作结果提示信息
  promptModalShow: boolean; //操作提示框是否展示

  btnLoading: boolean = false; //提交按钮loading状态
	recoverLoading: boolean = false; //提交按钮loading状态
	recoverModal: boolean = false; //恢复模态框
  wxRequired = false; //新增或编辑用户的时候，微信号是否必填
  changeInpSubject = new Subject(); //防抖
  changeInpCompanySubject = new Subject(); //防抖
	checkOptionsOne: Array<any> = [
	  { label: "已删除", value: "0", checked: false },
	];
	
  ngOnInit() {
    //防抖
    this.changeInpSubject.pipe(debounceTime(500)).subscribe((v) => {
      this.getDeparts(v[0], v[1], v[2]);
    });
    //防抖
    this.changeInpCompanySubject.pipe(debounceTime(500)).subscribe((v) => {
      this.getCompany(v[0], v[1], v[2]);
    });
    this.coopBtns = this.tool.initCoopBtns(this.route);
    this.getAllRole();
    this.getUserTypes();
    this.getGender();
		this.getPrioritys();
  }

  // 初始化增删改按钮
  coopBtns: any = {};

  // 模板导出
  excelExport(){
    this.maskFlag = this.message.loading("下载模板中..", {
      nzDuration: 0,
    }).messageId;
    this.mainService.exportExcel("user", {}).subscribe(
      (data) => {
        this.message.remove(this.maskFlag);
        this.maskFlag = false;
        this.message.success('下载模板成功');
        var file = new Blob([data], {
          type: "application/vnd.ms-excel",
        });
        //trick to download store a file having its URL
        var fileURL = URL.createObjectURL(file);
        var a = document.createElement("a");
        a.href = fileURL;
        a.target = "_blank";
        a.download = "用户导入模板.xls";
        document.body.appendChild(a);
        a.click();
      },
      (err) => {
        this.message.remove(this.maskFlag);
        this.maskFlag = false;
        this.message.error('下载模板失败');
      }
    );
  }

  // 导入---start
  // model-取消
  isShow = false;
  hideExcelImport() {
    this.isShow = false;
  }
  // 触发
  excelImport() {
    this.isShow = true;
  }
  submitExcelImport({fileList}){
    this.isShow = false;
    const formData = new FormData();
    fileList.forEach((file: any) => {
      formData.append('file', file);
    });
    this.maskFlag = this.message.loading("正在导入中..", {
      nzDuration: 0,
    }).messageId;
    const req = new HttpRequest('Post', this.mainService.returnImportExcelUrl('user'), formData, {
      reportProgress: true
    });
    this.http
      .request(req)
      .pipe(filter(e => e instanceof HttpResponse))
      .subscribe(
        (res:any) => {
          if(res.body.status == 200){
            this.message.remove(this.maskFlag);
            this.maskFlag = false;
            this.message.success('导入成功');
            this.getList();
          }else{
            this.message.remove(this.maskFlag);
            this.maskFlag = false;
            this.showPromptModal("导入", false, res.body.msg);
          }
        },
        () => {
          this.message.remove(this.maskFlag);
          this.maskFlag = false;
          this.message.error('导入失败');
        },
      );
  }
  // 导入---end
	
	// 表格筛选
	log(value: object[]): void {
	  console.log(value);
	  this.pageIndex = 1;
	  this.getList();
	}
	
	// 恢复
	itemData:any;
	recover(data){
		this.itemData = data;
		this.recoverModal = true;
	}
	
  // 搜索
  search() {
    this.pageIndex = 1;
    this.getList();
  }
  // 重置
  reset() {
    this.pageIndex = 1;
    this.name = "";
    this.num = "";
    this.userType = null;
    this.department = null;
    this.userGroup1 = null;
    this.changeHosp1(this.hosId);
    this.getList();
  }
  // 表格数据
  loading1 = false;
  getList() {
    let data = {
      idx: this.pageIndex - 1,
      sum: this.pageSize,
      user: {
        name: this.name || "",
        dept: { id: this.department || "" },
        usertype: { id: this.userType || "" },
        account: this.num || "",
        groupdata: { id: this.userGroup1 || "" },
        hospital: { id: this.hosId || "" },
        userTypeIds: String(this.userTypes.map(v => v.id)),
				deleted: this.checkOptionsOne[0].checked ? 1 : undefined
      },
    };
    if (!data.user.dept || !data.user.dept.id) {
      delete data.user.dept;
    }
    if (!data.user.usertype || !data.user.usertype.id) {
      delete data.user.usertype;
    }
    if (!data.user.groupdata || !data.user.groupdata.id) {
      delete data.user.groupdata;
    }
    if (!data.user.hospital || !data.user.hospital.id) {
      delete data.user.hospital;
    }
    this.loading1 = true;
    this.mainService
      .getFetchDataList("data", "user", data)
      .subscribe((data) => {
        this.loading1 = false;
        this.listOfData = data.list;
        this.listLength = data.totalNum;
      });
  }

  // 获取所有用户类型
  getUserTypes() {
    this.mainService.getDictionary("list", "usertype").subscribe((data) => {
      this.userTypes = data;
      this.getAllHospital();
    });
  }

  // 获取相应的院区
  getAllHospital() {
    this.hosId = this.tool.getCurrentHospital().id + "";
    this.changeHosp1(this.hosId);
    this.getList();
  }

  // 角色列表
  getAllRole() {
    var that = this;
    let data = {
      idx: 0,
      sum: 1000,
    };
    that.mainService
      .getFetchDataList("data", "role", data)
      .subscribe((data) => {
        that.allUserRole = data.list;
      });
  }

  // 切换院区选项获取对应科室列表
  changeHosp() {
    let hid = this.hosId - 0;
    let data = {
      department: {
        // hospital: { id: hid },
				cascadeHosId: hid
      },
      idx: 0,
      sum: 20,
    };
    let groupData = {
      group2: {
        hospitals: this.coopBtns.crossHospital ? undefined : hid,
        typeIds: '1,3',
        crossHospital: this.coopBtns.crossHospital ? hid : undefined,
      },
      idx: 0,
      sum: 9999,
    };
    let companyData = {
      company: {
        busiType: {key: "company_busi_type", value: "2"},
        statisticalHosId: hid,
      },
      idx: 0,
      sum: 20,
    };
    this.maskFlag = this.message.loading("正在加载中..", {
      nzDuration: 0,
    }).messageId;
    let department$ = this.mainService.getFetchDataList(
      "data",
      "department",
      data
    );
    let group$ = this.mainService.getFetchDataList("data", "group2", groupData);
    let company$ = this.mainService.getFetchDataList("simple/data", "company", companyData);
    forkJoin(department$, group$, company$).subscribe((res) => {
      this.message.remove(this.maskFlag);
      this.maskFlag = false;
      this.modal = true;
      this.alldepart = res[0]["list"];
      this.allUserGroup = res[1]["list"];
      this.allcompany = res[2]["list"];
    });
  }
  // 切换院区选项获取对应科室列表(搜索)seimin
  changeHosp1(id) {
    this.department = null;
    this.userGroup1 = null;
    let departmentData = {
      department: {
        // hospital: { id },
				cascadeHosId: id
      },
      idx: 0,
      sum: 20,
    };
    let groupData = {
      group2: {
        hospitals: this.coopBtns.crossHospital ? undefined : id,
        typeIds: '1,3',
        crossHospital: this.coopBtns.crossHospital ? id : undefined,
      },
      idx: 0,
      sum: 9999,
    };
    this.mainService
      .getFetchDataList("data", "department", departmentData)
      .subscribe((data) => {
        this.alldepart1 = data.list;
      });
    this.mainService
      .getFetchDataList("data", "group2", groupData)
      .subscribe((data) => {
        this.allUserGroup1 = data.list;
      });
  }

  // 获取性别
  genders: Array<any> = [];
  getGender() {
    var that = this;
    that.mainService.getDictionary("list", "user_gender").subscribe((data) => {
      that.genders = data;
    });
  }
	
	// 获取优先级
	priority_c_List: any = [];
	getPrioritys() {
	  let postData = {
	    priority: {},
	    idx: 0,
	    sum: 9999,
	  };
	  this.mainService
	    .getFetchDataList("simple/data", "priority", postData)
	    .subscribe((data) => {
	      this.isLoading = false;
	      this.priority_c_List = data.list || [];
	    });
	}
	
  // 新增弹框
  showModal() {
    this.add = true;
    this.initForm();
    this.requiredConfigChange('companyId', false);
    this.changeHosp();
  }
  hideModal() {
    this.modal = false;
  }

  // 初始化新增form表单
  initForm() {
    if (this.add) {
      this.alldepart = [];
      this.allcompany = [];
      this.allUserGroup = [];
    }
    this.validateForm = this.fb.group({
      name: [null, [Validators.required]],
      account: [null, [Validators.required]],
      gradeId: [null],
      usertype: [null, [Validators.required]],
      companyId: [null],
      dept: [null, [Validators.required]],
      deptPhone: [null, [Validators.required]],
      gender: [null, [Validators.required]],
      userGroup: [null],
      role: [null, [Validators.required]],
      weixin: [null],
			priority: [null], //优先级
			mngmtDept: [null], //管理科室
    });
  }
  // 选择用户类型
  usertypeChange(value) {
    // if (this.validateForm.value.usertype == 106) {
    //   //配送人员
    //   this.wxRequired = true;
    //   this.validateForm.get("weixin")!.setValidators(Validators.required);
    //   this.validateForm.get("weixin")!.markAsDirty();
    // } else {
    //   this.wxRequired = false;
    //   this.validateForm.get("weixin")!.clearValidators();
    //   this.validateForm.get("weixin")!.markAsPristine();
    // }
    this.wxRequired = false;
    this.validateForm.get("weixin")!.clearValidators();
    this.validateForm.get("weixin")!.markAsPristine();

    this.validateForm.get("weixin")!.updateValueAndValidity();

    this.validateForm.controls.companyId.setValue(null);
    if(value == 4){
      // 三方人员
      this.requiredConfigChange('companyId', true);
    }else{
      this.requiredConfigChange('companyId', false);
    }
  }
  // 表单提交
	recoverContent:any;
	userData:any;
  submitForm(): void {
    var that = this;
    for (const i in that.validateForm.controls) {
      that.validateForm.controls[i].markAsDirty({ onlySelf: true });
      that.validateForm.controls[i].updateValueAndValidity();
    }
    if (that.validateForm.invalid) return;
    that.btnLoading = true;
    let groups = [],
      roles = [];
    if (that.validateForm.value.userGroup) {
      that.validateForm.value.userGroup.forEach((element) => {
        groups.push({ id: element });
      });
    }
    that.validateForm.value.role.forEach((element) => {
      roles.push({ id: element });
    });
    let data = {
      user: {
        name: that.validateForm.value.name,
        account: that.validateForm.value.account,
        gradeId: that.validateForm.value.gradeId,
        gender: { id: that.validateForm.value.gender, key: "user_gender" },
        usertype: this.userTypes.find(v => v.value == that.validateForm.value.usertype),
        dept: { id: that.validateForm.value.dept },
        group: groups,
        role: roles,
				priority: this.validateForm.value.priority,
				mngmtDept: this.validateForm.value.mngmtDept?this.validateForm.value.mngmtDept.join(','):null,
        phone: that.validateForm.value.deptPhone,
        hospital: { id: that.hosId },
        weixin: that.validateForm.value.weixin,
        companyId: that.validateForm.value.companyId || undefined,
        engineer: that.validateForm.value.usertype == 4 ? 1 : 0,
      },
    };
    if (!that.validateForm.value.userGroup) {
      delete data.user.group;
    } else if (that.validateForm.value.userGroup.length === 0) {
      delete data.user.group;
    }
    if (!that.add) {
      data.user["id"] = that.coopId;
    }
    that.mainService
      .coopData(that.add ? "addData" : "updData", "user", data)
      .subscribe((data) => {
        that.btnLoading = false;
        that.hideModal();
        that.initForm();
        if (data.status == 200) {
          that.showPromptModal(that.add ? "新增" : "编辑", true, "");
        } else if(data.status == 2002 || data.status == 2004){
					this.userData = data
					this.recoverContent = data.msg
					this.recoverModal = true;
        }else{
					that.showPromptModal(that.add ? "新增" : "编辑", false, data.msg);
				}
      });
  }

  requiredConfigChange(name: string, required: boolean): void {
    if (!required) {
      this.validateForm.get(name)!.clearValidators();
      this.validateForm.get(name)!.markAsPristine();
    } else {
      this.validateForm.get(name)!.setValidators(Validators.required);
      this.validateForm.get(name)!.markAsDirty();
    }
    this.validateForm.get(name)!.updateValueAndValidity();
  }

  // 编辑
  maskFlag: any = false;
  edit(data) {
    this.initForm();
    // ----------------
    var hid = data.hospital.id;
    let departmentData = {
      department: {
        // hospital: { id: hid },
				cascadeHosId: hid
      },
      idx: 0,
      sum: 20,
    };
    let groupData = {
      group2: {
        hospitals: this.coopBtns.crossHospital ? undefined : hid,
        typeIds: '1,3',
        crossHospital: this.coopBtns.crossHospital ? hid : undefined,
      },
      idx: 0,
      sum: 9999,
    };
    let companyData = {
      company: {
        busiType: {key: "company_busi_type", value: "2"},
        statisticalHosId: hid,
      },
      idx: 0,
      sum: 20,
    };
    this.maskFlag = this.message.loading("正在加载中..", {
      nzDuration: 0,
    }).messageId;
    this.mainService
      .getFetchDataList("data", "group2", groupData)
      .subscribe((item1) => {
        this.allUserGroup = item1.list;
        this.mainService
          .getFetchDataList("data", "department", departmentData)
          .subscribe((item2) => {
            this.alldepart = item2.list;
            if (data.dept) {
              let has = item2.list.some((d) => d.id == data.dept.id);
              if (!has) {
                this.alldepart = [data.dept, ...item2.list];
              }
            }
            this.mainService
            .getFetchDataList("simple/data", "company", companyData)
            .subscribe((item3) => {
              this.message.remove(this.maskFlag);
              this.maskFlag = false;
              this.modal = true;
              this.allcompany = item3.list;
              if (data.companyDTO) {
                let has = item3.list.some((d) => d.id == data.companyDTO.id);
                if (!has) {
                  this.allcompany = [data.companyDTO, ...item3.list];
                }
              }
              this.isLoading = false;
              // ------------------------
              this.add = false;
              this.coopId = data.id;
              let groups = [],
                roles = [];
              if (data.group) {
                data.group.forEach((element) => {
                  groups.push(element["id"] + "");
                });
              }
              if (data.role) {
                data.role.forEach((element) => {
                  roles.push(element["id"] + "");
                });
              }
              this.validateForm.controls.name.setValue(data.name);
              this.validateForm.controls.account.setValue(data.account);
              this.validateForm.controls.gradeId.setValue(data.gradeId);
              this.validateForm.controls.usertype.setValue(data.usertype.value);
              if (data.dept) {
                this.validateForm.controls.dept.setValue(data.dept.id);
              }
              this.validateForm.controls.deptPhone.setValue(data.phone);
              this.validateForm.controls.gender.setValue(data.gender.id + "");
              this.validateForm.controls.userGroup.setValue(
                groups.length ? groups : null
              );
              this.validateForm.controls.role.setValue(
                roles.length ? roles : null
              );
              this.validateForm.controls.gender.setValue(data.gender.id + "");
              this.validateForm.controls.weixin.setValue(data.weixin);
							if(data.priorityDTO){
								this.validateForm.controls.priority.setValue(data.priorityDTO.id);
							}
							if(data.mngmtDept){
								let arr = data.mngmtDept.split(',')
								arr = arr.map(i=>i = parseInt(i))
								this.validateForm.controls.mngmtDept.setValue(arr);
							}else{
								this.validateForm.controls.mngmtDept.setValue(null);
							}
              this.usertypeChange(data.usertype.value);
              if (data.companyDTO) {
                this.validateForm.controls.companyId.setValue(data.companyDTO.id);
              }
            });
          });
      });
    // ----------------
  }

  // 删除
  delModal: boolean = false; //删除模态框
  del(data) {
    let that = this;
    that.coopId = data.id;
    that.delModal = true;
  }
  // 确认删除(删除企业微信用户)
  confirmDel() {
    let that = this;
    that.btnLoading = true;
    that.mainService
      .rmvDataAndWeChatNum([that.coopId], true)
      .subscribe((data) => {
        that.btnLoading = false;
        that.hideDelModal();
        if (data["status"] == 200) {
          if (
            that.listOfData.length == 1 &&
            that.pageIndex == Math.ceil(that.listLength / that.pageSize)
          ) {
            that.listLength--;
            that.pageIndex = Math.ceil(that.listLength / that.pageSize) || 1;
          }
          that.showPromptModal("删除", true, "");
        } else {
          that.showPromptModal("删除", false, data["msg"]);
        }
      });
  }
  // 确认删除(不删除企业用户)
  cancenlLoading = false;
  cancelDel() {
    let that = this;
    that.cancenlLoading = true;
    that.mainService
      .rmvDataAndWeChatNum([that.coopId], false)
      .subscribe((data) => {
        that.cancenlLoading = false;
        that.hideDelModal();
        if (data["status"] == 200) {
          if (
            that.listOfData.length == 1 &&
            that.pageIndex == Math.ceil(that.listLength / that.pageSize)
          ) {
            that.listLength--;
            that.pageIndex = Math.ceil(that.listLength / that.pageSize) || 1;
          }
          that.showPromptModal("删除", true, "");
        } else {
          that.showPromptModal("删除", false, data["msg"]);
        }
      });
  }
	
	// 解锁/锁定
	lockModal:boolean = false;
	lockLoading:boolean = false;
	lockContent:any;
	lockType:any;
	unlock(data, type){
		this.coopId = data.id;
		this.lockType = type
		if(type ==1){
			this.lockContent = '您确定要解锁账号吗？'
		}else{
			this.lockContent = '您确定要锁定账号吗？锁定后用户将不能登录系统，包括PC登录、微信、单点登录！'
		}
		this.lockModal = true
	}
	
	// 确定解锁/锁定
	confirmLock(){
		let that = this;
		let query = {
			user:{
				id: this.coopId,
				upType: this.lockType == 1 ? 'unlock' : 'lock'
			}
		}
		that.lockLoading = true;
		that.mainService.coopData("updData", "user", query).subscribe((data) => {
		    that.lockLoading = false;
		    that.hideLockModal();
		    if (data["status"] == 200) {
		      that.showPromptModal(this.lockType == 1?"解锁":"锁定", true, "");
		    } else {
		      that.showPromptModal(this.lockType == 1?"解锁":"锁定", false, data["msg"]);
		    }
		  });
	}
	
	// 关闭锁定modal
	hideLockModal(){
		this.lockModal = false;
	}
	
	// 确认恢复
	confirmRecover() {
	  let that = this;
		let query = {
			user:{
				...this.itemData,
				deleted: 0
			}
		}
	  that.recoverLoading = true;
	  that.mainService.coopData("updData", "user", query).subscribe((data) => {
	      that.recoverLoading = false;
	      that.hideRecoverModal();
	      if (data["status"] == 200) {
	        that.showPromptModal("恢复", true, "");
	      } else {
	        that.showPromptModal("恢复", false, data["msg"]);
	      }
	    });
	}

	// 关闭恢复模态框
	hideRecoverModal() {
	  this.recoverModal = false;
	}

  // 关闭删除模态框
  hideDelModal() {
    this.delModal = false;
  }

  // ==================重置密码start====================
  // 重置密码
  resetModal: boolean = false; //删除模态框
  resetPwd(data) {
    
		this.coopId = data.id;
    this.resetModal = true;
  }
  // 确认重置密码
  confirmReset() {
    this.btnLoading = true;
    this.mainService
      .resetpwd(this.coopId)
      .subscribe((data) => {
        this.btnLoading = false;
        this.hideResetModal();
        if (data["status"] == 200) {
          this.showPromptModal("重置密码", true, "");
        } else {
          this.showPromptModal("重置密码", false, data["msg"]);
        }
      });
  }
  // 取消
  cancelReset() {
    this.resetModal = false;
  }
  // 关闭删除模态框
  hideResetModal() {
    this.resetModal = false;
  }
  // ==================重置密码end====================

  // 展示信息提示框（con:提示信息，success:操作是否成功，promptInfo:操作结果提示信息）
  showPromptModal(con, success, promptInfo?) {
    this.promptModalShow = false;
    this.promptContent = con;
    this.ifSuccess = success;
    this.promptInfo = promptInfo;
    setTimeout(() => {
      this.promptModalShow = true;
    }, 100);
    this.getList();
  }

  // 查看
  detail(id) {
    this.router.navigateByUrl("/main/usersManagement/userDetail/" + id);
  }
  // 边输边搜节流阀
  isLoading = false;
  changeInp(hosId, type, e) {
    if (!hosId) {
      if (type == "search") {
        this.alldepart1 = [];
      } else if (type == "add") {
        this.alldepart = [];
      }
      return;
    }
    this.isLoading = true;
    this.changeInpSubject.next([hosId, type, e]);
  }

  changeCompanyInp(hosId, type, e) {
    if (!hosId) {
      if (type == "search") {

      } else if (type == "add") {
        this.allcompany = [];
      }
      return;
    }
    this.isLoading = true;
    this.changeInpCompanySubject.next([hosId, type, e]);
  }
  // 获取所有科室
  snum = 0;
  getDeparts(hosId, type, dept) {
    var that = this;
    let data = {
      department: {
        dept,
        // hospital: {
        //   id: hosId,
        // },
				cascadeHosId: hosId
      },
      idx: 0,
      sum: 20,
    };
    this.snum++;
    that.mainService
      .getFetchDataList("data", "department", data)
      .subscribe((data) => {
        this.snum--;
        if (type == "search") {
          that.alldepart1 = data.list;
        } else if (type == "add") {
          that.alldepart = data.list;
        }
        if (this.snum === 0) {
          that.isLoading = false;
        }
      });
  }

  // 获取所有科室
  cnum = 0;
  getCompany(hosId, type, keyword) {
    var that = this;
    let data = {
      company: {
        name: keyword,
        busiType: {key: "company_busi_type", value: "2"},
        statisticalHosId: hosId,
      },
      idx: 0,
      sum: 20,
    };
    this.cnum++;
    that.mainService
      .getFetchDataList("simple/data", "company", data)
      .subscribe((data) => {
        this.cnum--;
        if (type == "search") {

        } else if (type == "add") {
          that.allcompany = data.list;
        }
        if (this.cnum === 0) {
          that.isLoading = false;
        }
      });
  }
}
