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 } from "rxjs/operators";
import { NzMessageService } from "ng-zorro-antd";

@Component({
  selector: "app-clinical-users-management",
  templateUrl: "./clinical-users-management.component.html",
  styleUrls: ["./clinical-users-management.component.less"],
})
export class ClinicalUsersManagementComponent 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
  ) {}

  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 = []; //所有所属科室(搜索)
  hospitals1: 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状态
  wxRequired = false; //新增或编辑用户的时候，微信号是否必填
  changeInpSubject = new Subject(); //防抖
  changeInpHospitalSubject = new Subject(); //防抖

  ngOnInit() {
    //防抖
    this.changeInpSubject.pipe(debounceTime(500)).subscribe((v) => {
      this.getDeparts(v[0], v[1], v[2]);
    });
    //防抖
    this.changeInpHospitalSubject.pipe(debounceTime(500)).subscribe((v) => {
      this.getHospitals(v[0], v[1], v[2]);
    });
    this.coopBtns = this.tool.initCoopBtns(this.route);
    this.initForm();
    this.getUserTypes();
    this.getAllRole();
    this.getGender();
		this.getPrioritys();
  }

  // 初始化增删改按钮
  coopBtns: any = {};
  // 搜索
  search() {
    this.pageIndex = 1;
    this.getList();
  }
  // 重置
  isShowSelectHospital = true;
  reset() {
    this.isShowSelectHospital = false;
    setTimeout(()=>{
      this.isShowSelectHospital = true;
    },0)
    this.pageIndex = 1;
    this.hosId = this.tool.getCurrentHospital().id;
    this.name = "";
    this.num = "";
    let userType = this.userTypes.find(v => v.value == 1);
    this.userType = userType ? userType.id: 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 || "" },
      },
    };
    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 || [];
      let userType = this.userTypes.find(v => v.value == 1);
      this.userType = userType ? userType.id: null;
      this.getAllHospital();
    });
  }

  // 获取相应的院区
  getAllHospital() {
    this.loading1 = true;
    let topLevelParentHosList$ = this.mainService.apiPostAll("topLevelParentHosList", {});
    // let topLevelParentHos$ = this.mainService.apiPostAll("topLevelParentHos", {hosId: this.tool.getCurrentHospital().id});
    forkJoin(topLevelParentHosList$).subscribe((dataArray:any[]) => {
      let [data1] = dataArray;
      this.hospitals1 = data1.topLevelParentHosList || [];
      // this.hosId = data2.topHospital ? data2.topHospital.id : null;
      this.hosId = this.tool.getCurrentHospital().id;
      this.changeHosp1(this.hosId);
      this.getList();
    }, err => {
      this.loading1 = false;
    })
  }

  // 角色列表
  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.tool.getCurrentHospital().id;
    let data = {
      department: {
        hospital: { id: hid },
      },
      idx: 0,
      sum: 20,
    };
    let groupData = {
      group2: {
        hospitals: hid,
        type:1
      },
      idx: 0,
      sum: 9999,
    };
    this.maskFlag = this.message.loading("正在加载中..", {
      nzDuration: 0,
    }).messageId;
    let department$ = this.mainService.getFetchDataList(
      "data",
      "department",
      data
    );
    let group$ = this.mainService.getFetchDataList("data", "group2", groupData);
    forkJoin(department$, group$).subscribe((res) => {
      this.message.remove(this.maskFlag);
      this.maskFlag = false;
      this.modal = true;
      this.alldepart = res[0]["list"];
      this.allUserGroup = res[1]["list"];
    });
  }
  // 切换院区选项获取对应科室列表(搜索)seimin
  changeHosp1(id) {
    this.department = null;
    this.userGroup1 = null;
    let departmentData = {
      department: {
        hospital: { id },
      },
      idx: 0,
      sum: 20,
    };
    let groupData = {
      group2: {
        hospitals: id,
        type:1
      },
      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;
      });
  }
	
	// 获取优先级
	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 || [];
	    });
	}
	
  // 获取性别
  genders: Array<any> = [];
  getGender() {
    var that = this;
    that.mainService.getDictionary("list", "user_gender").subscribe((data) => {
      that.genders = data;
    });
  }

  // 新增弹框
  showModal() {
    this.add = true;
    this.initForm();
    this.changeHosp();
  }
  hideModal() {
    this.modal = false;
    this.initForm();
  }

  // 初始化新增form表单
  initForm() {
    if (this.add) {
      this.alldepart = [];
      this.allUserGroup = [];
    }
    this.validateForm = this.fb.group({
      name: [null, [Validators.required]],
      account: [null, [Validators.required]],
      gradeId: [null],
      usertype: [this.userType + '', [Validators.required]],
      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() {
    // 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();
  }
  // 表单提交
  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: { id: 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.add ? that.tool.getCurrentHospital().id : that.hosId },
        weixin: that.validateForm.value.weixin,
        engineer: this.userTypes.find(v => v.id == that.validateForm.value.usertype).value == 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 {
          that.showPromptModal(that.add ? "新增" : "编辑", false, data.msg);
        }
      });
  }

  // 编辑
  maskFlag: any = false;
  edit(data) {
    // ----------------
    var hid = data.hospital.id;
    let departmentData = {
      department: {
        hospital: { id: hid },
      },
      idx: 0,
      sum: 20,
    };
    let groupData = {
      group2: {
        hospitals: hid,
        type:1
      },
      idx: 0,
      sum: 9999,
    };
    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.message.remove(this.maskFlag);
            this.maskFlag = false;
            this.modal = true;
            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.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.id + "");
            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();
          });
      });
    // ----------------
  }

  // 删除
  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"]);
        }
      });
  }
  // 关闭删除模态框
  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/clinicalUsersManagement/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]);
  }
  // 边输边搜节流阀
  changeInpHospital(hosId, type, e) {
    if (!hosId) {
      if (type == "search") {
        this.hospitals1 = [];
      } else if (type == "add") {}
      return;
    }
    this.isLoading = true;
    this.changeInpHospitalSubject.next([hosId, type, e]);
  }
  // 获取所有科室
  snum = 0;
  getDeparts(hosId, type, dept) {
    var that = this;
    let data = {
      department: {
        dept,
        hospital: {
          id: type == "search" ? hosId : this.tool.getCurrentHospital().id,
        },
      },
      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;
        }
      });
  }
  // 获取院区
  hnum = 0;
  getHospitals(hosId, type, keword) {
    this.hnum++;
    this.mainService
      .apiPostAll("topLevelParentHosList", {})
      .subscribe((data:any) => {
        this.hnum--;
        if (type == "search") {
          this.hospitals1 = data.list;
        } else if (type == "add") {}
        if (this.hnum === 0) {
          this.isLoading = false;
        }
      });
  }
}

