import { Component, OnInit, ViewChild } from "@angular/core";
import { ActivatedRoute } from "@angular/router";
import { FormBuilder, Validators, FormGroup } from "@angular/forms";
import { NzMessageService } from "ng-zorro-antd/message";

import { MainService } from "../../services/main.service";
import { OverlayScrollbarsComponent } from "overlayscrollbars-ngx";
import { ToolService } from "../../services/tool.service";
import { Subject } from "rxjs";
import { debounceTime } from "rxjs/operators";

@Component({
  selector: "app-group-management",
  templateUrl: "./group-management.component.html",
  styleUrls: ["./group-management.component.less"],
})
export class GroupManagementComponent implements OnInit {
  tableHeight;

  constructor(
    private fb: FormBuilder,
    private route: ActivatedRoute,
    private mainService: MainService,
    private msg: NzMessageService,
    private tool: ToolService
  ) {}
  @ViewChild("osComponentRef1", {
    read: OverlayScrollbarsComponent,
    static: false,
  })
  osComponentRef1: OverlayScrollbarsComponent;
  ngOnInit() {
    this.changeInpSubject
      .pipe(debounceTime(500))
      .subscribe((keyword: string) => {
        this.getUserList(keyword);
      });
    this.coopBtns = this.tool.initCoopBtns(this.route);
    this.initForm();
    this.getHospitalList();
    this.getGroupList();
    this.getScheduleList();
    this.tableHeight = document.body.clientHeight - 267;
  }
  isAllDisplayDataChecked = false;
  isIndeterminate = false;
  listOfDisplayData: any[] = [];
  allUserList: any[] = []; //所有用户
  groupUserList: any[] = []; //所选组内用户
  mapOfCheckedId: { [key: string]: boolean } = {};
  checkedGroup: any = {}; //选中分组
  groupList: Array<any> = []; //分组信息
  hospitalList: Array<any> = []; //院区列表
  hosId: any; //当前选择的院区id
  scheduleList: Array<any> = []; //班次列表
  userList: Array<any> = []; //用户列表
  searchName: string = ""; //用户信息搜索输入框

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

  btnLoading: boolean = false; //确认按钮loading状态
  saveLoading: boolean = false; //批量打印按钮loading状态
  changeInpSubject = new Subject();

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

  // 边输边搜节流阀
  isLoading = false;
  changeInp(keyword: string = "") {
    this.isLoading = true;
    this.changeInpSubject.next(keyword);
  }
  // 打开搜索框
  changeSearch(flag) {
    if (flag && !this.editLoading) {
      this.changeInp();
    }
  }

  // 分组列表
  loading1 = false;
  getGroupList() {
    let that = this;
    let arr = [];
    this.hospitalList.forEach((item) => {
      arr.push(item["id"]);
    });
    let data = {
      idx: 0,
      sum: 999,
      group2: {
        hospitals: arr.join(),
      },
    };
    this.loading1 = true;
    that.mainService
      .getFetchDataList("data", "group2", data)
      .subscribe((data1) => {
        this.loading1 = false;
        that.groupList = data1.list;
        console.log(this.checkedGroup);
        if (Object.keys(this.checkedGroup).length) {
          console.log(this.checkedGroup);
          data1.list.forEach((item) => {
            if (item.id == this.checkedGroup.id) {
              this.checkGroup(item);
            }
          });
        } else {
          this.checkGroup(data1.list[0]);
        }
      });
  }

  // 获取选中院区下用户列表
  loading2 = false;
  onlyFlag = true;
  allUsers = [];
  getAllUser() {
    // 初始化的时候搜索一次，然后前端过滤
    if (this.onlyFlag) {
      let data = {
        idx: 0,
        sum: 999,
        user: {
          name: this.searchName,
          usertype: { id: 106 },
          hospital: { id: this.hosId },
        },
      };
      this.timeNum++;
      this.loading2 = true;
      this.mainService
        .getFetchDataList("data", "user", data)
        .subscribe((result) => {
          this.timeNum--;
          if (this.timeNum === 0) {
            this.loading2 = false;
            this.onlyFlag = false;
          }
          this.allUserList = result.list;
          this.allUsers = JSON.parse(JSON.stringify(result.list));
          this.refreshStatus(true);
        });
    } else {
      this.allUserList = this.allUsers.filter((item) => {
        return (
          item.pinYin.includes(this.searchName) ||
          item.name.includes(this.searchName) ||
          item.inputCode.includes(this.searchName)
        );
      });
      this.refreshStatus(true);
    }
  }

  // 输入用户信息搜索节流阀
  time: any;
  timeNum = 0;
  searchInp(e) {
    let that = this;
    that.getAllUser();
  }

  // 院区列表
  getHospitalList() {
    this.hosId = this.tool.getCurrentHospital().id;
    this.hospitalList = [this.tool.getCurrentHospital()];
  }
  // 班次列表
  getScheduleList() {
    const data = {
      idx: 0,
      scheduleClass: { hospital: { id: this.hosId } },
      sum: 999,
    };
    this.mainService
      .getFetchDataList("configuration", "scheduleClass", data)
      .subscribe((data) => {
        this.scheduleList = data.list;
      });
  }
  // 用户列表
  getUserList(keyword: string = "") {
    const data = {
      idx: 0,
      user: {
        hospital: { id: this.hosId },
        name: keyword,
        simpleQuery: true,
      },
      sum: 5,
    };
    this.mainService
      .getFetchDataList("data", "user", data)
      .subscribe((result) => {
        this.isLoading = false;
        if (result.status == 200) {
          this.userList = result.list;
        }
      });
  }

  // 选中分组
  positionY = 0; //记录其他建单Y轴滚动距离
  checkGroup(data) {
    this.positionY = this.osComponentRef1.osInstance().scroll().position.y; //内容滚动的距离
    this.searchName = "";
    this.checkedGroup = data ? data : {};
    this.mapOfCheckedId = {};
    this.groupUserList = this.checkedGroup["users"]
      ? this.checkedGroup["users"]
      : [];
    this.getAllUser();
  }
  selectedUser(data) {
    console.log(data)
    if(this.checkedGroup.type == 2){
      return;
    }
    this.mapOfCheckedId[data.id] = !this.mapOfCheckedId[data.id];
    this.refreshStatus();
  }
  // 选中列表中当前分组用户
  usersArr = [];
  refreshStatus(first?): void {
    let i, j;
    // 切换分组信息时初始化表格內checkbox选中情况
    if (first) {
      for (j = 0; j < this.groupUserList.length; j++) {
        for (i = 0; i < this.allUserList.length; i++) {
          if (this.allUserList[i]["id"] == this.groupUserList[j]["id"]) {
            this.mapOfCheckedId[this.allUserList[i]["id"]] = true;
            break;
          }
        }
      }
    }
    let arr = [];
    for (var m in this.mapOfCheckedId) {
      if (this.mapOfCheckedId[m]) {
        arr.push({ id: m });
      }
    }
    this.usersArr = arr;
  }

  // 保存
  save() {
    let that = this;
    that.saveLoading = true;
    let postData = {
      group2: {
        id: that.checkedGroup["id"],
        users: that.usersArr,
      },
    };
    that.mainService
      .coopData("updData", "group2", postData)
      .subscribe((data) => {
        that.saveLoading = false;
        if (data.status == 200) {
          that.showPromptModal("保存", true, "");
        } else {
          that.showPromptModal("保存", false, data.msg);
        }
      });
  }

  // 新增/编辑模态框
  coopModal: boolean = false; //模态框是否展示
  add: boolean = true; //true：新增；false：编辑
  editLoading = false;//分组组长选择框loading
  isDisabledGroupType = false;//分组类型是否禁用
  showCoopModal(type) {
    if (type == "edit" && !this.checkedGroup["groupName"]) {
      this.msg.create("warning", "请选择需要编辑的分组！");
      return;
    }
    this.coopModal = true;
    this.add = type == "add";
    if (type == "edit") {
      this.isDisabledGroupType = true;
      this.validateForm.controls.groupLeader.setValue(null);//先清空组长
      this.validateForm.controls.classes.setValue(
        this.checkedGroup["scheduleClass"].id + ""
      );
      this.validateForm.controls.groupName.setValue(
        this.checkedGroup["groupName"]
      );
      this.validateForm.controls.groupType.setValue(
        this.checkedGroup["type"].toString()
      );
      if (this.checkedGroup["manager"]) {
        this.editLoading = true;
        this.mainService
          .getFetchData("data", "user", this.checkedGroup["manager"])
          .subscribe((result) => {
            this.editLoading = false;
            if (result.status == 200) {
              if (result.data) {
                this.userList.unshift(result.data);
              }
              this.validateForm.controls.groupLeader.setValue(
                this.checkedGroup["manager"].toString()
              );
            }
          });
      } else {
        this.validateForm.controls.groupLeader.setValue(null);
      }
    } else {
      this.isDisabledGroupType = false;
      this.validateForm.controls.classes.setValue(null);
      this.validateForm.controls.groupName.setValue(null);
      this.validateForm.controls.groupLeader.setValue(null);
      this.validateForm.controls.groupType.setValue(null);
    }
  }
  // 隐藏分组信息模态框
  hideCoopModal() {
    this.coopModal = false;
  }

  // 初始化新增form表单
  initForm() {
    this.validateForm = this.fb.group({
      classes: [null, [Validators.required]],
      groupName: [null, [Validators.required]],
      groupType: [null, [Validators.required]],
      groupLeader: [null, [Validators.required]],
    });
  }

  // 新增/编辑提交
  validateForm: FormGroup;
  submitForm(): void {
    let that = this;
    for (const i in that.validateForm.controls) {
      that.validateForm.controls[i].markAsDirty();
      that.validateForm.controls[i].updateValueAndValidity();
    }
    if (that.validateForm.invalid) return;
    that.btnLoading = true;
    let data = {
      group2: {
        groupName: that.validateForm.value.groupName,
        hospital: { id: that.hosId - 0 },
        scheduleClass: { id: that.validateForm.value.classes - 0 },
        manager: that.validateForm.value.groupLeader,
        type: that.validateForm.value.groupType,
      },
    };
    if (!that.add) {
      data.group2["id"] = that.checkedGroup["id"];
    }
    that.mainService
      .coopData(that.add ? "addData" : "updData", "group2", data)
      .subscribe((data) => {
        that.hideCoopModal();
        that.btnLoading = false;
        that.initForm();
        if (data.status == 200) {
          that.showPromptModal(that.add ? "新增" : "编辑", true, "");
        } else {
          that.showPromptModal(that.add ? "新增" : "编辑", false, data.msg);
        }
      });
  }

  //删除modal
  delModal: boolean = false;
  showDelModal() {
    if (!this.checkedGroup["groupName"]) {
      this.msg.create("warning", "请选择需要删除的分组！");
      return;
    }
    this.delModal = true;
  }
  hideDelModal() {
    this.delModal = false;
  }
  // 确认删除
  confirmDel() {
    this.btnLoading = true;
    this.mainService
      .coopData("rmvData", "group2", [this.checkedGroup["id"]])
      .subscribe((data) => {
        this.hideDelModal();
        this.btnLoading = false;
        if (data.data && data.data[0]) {
          if (!data.data[0].msg) {
            this.showPromptModal("删除", true, "");
            this.checkedGroup = {};
          } else {
            this.showPromptModal("删除", false, data.data[0].msg);
          }
        } else {
          this.showPromptModal("删除", false, "");
        }
      });
  }

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