import { Component, OnInit, ViewChild } from "@angular/core";
import { FormBuilder, FormGroup, Validators } from "@angular/forms";
import { ActivatedRoute } from "@angular/router";
import { OverlayScrollbarsComponent } from "overlayscrollbars-ngx";
import { MainService } from "../../services/main.service";
import { ToolService } from "../../services/tool.service";
import { Subject } from "rxjs";
import { debounceTime } from "rxjs/operators";

@Component({
  selector: "app-wechat-config",
  templateUrl: "./wechat-config.component.html",
  styleUrls: ["./wechat-config.component.less"],
})
export class WechatConfigComponent implements OnInit {
  validateForm: FormGroup;
  loading1 = false; //查询信息的loading
  loading2 = false; //保存信息的loading
  roleList = []; //角色列表
  groupList = []; //组列表
  deptList = []; //科室列表
  id = -1; //修改配置的id
  promptContent: string; //操作提示框提示信息
  ifSuccess: boolean; //操作成功/失败
  promptInfo: string; //操作结果提示信息
  promptModalShow: boolean; //操作提示框是否展示
  coopBtns = {};
  hosId: ""; //院区ID
  hospitals = []; //所属院区
  loading3 = false; //科室
  constructor(
    private mainService: MainService,
    private fb: FormBuilder,
    private route: ActivatedRoute,
    private tool: ToolService
  ) {}
  @ViewChild("osComponentRef1", {
    read: OverlayScrollbarsComponent,
    static: false,
  })
  osComponentRef1: OverlayScrollbarsComponent;
  onDeptSearchSubject = new Subject();
  ngOnInit() {
    this.onDeptSearchSubject.pipe(debounceTime(500)).subscribe((v) => {
      this.onDeptSearch(v);
    });
    this.hospitals = this.tool.getHospitalList();
    this.validateForm = this.fb.group({
      secret: [null, [Validators.required]],
      appid: [null, [Validators.required]],
      agentid: [null, [Validators.required]],
      autoCreateUser: ["1", [Validators.required]],
      defaultRole: [null, [Validators.required]],
      defaultHospital: [null, [Validators.required]],
      defaultDept: [null, [Validators.required]],
      defaultGroup: [null, [Validators.required]],
      bindAccount: ["0", [Validators.required]]
    });
    this.getRoleList();
    this.coopBtns = this.tool.initCoopBtns(this.route);
  }
  // 保存
  submitForm(): void {
    for (const i in this.validateForm.controls) {
      this.validateForm.controls[i].markAsDirty();
      this.validateForm.controls[i].updateValueAndValidity();
    }
    if (this.validateForm.invalid) {
      return;
    }
    const postData = {
			...this.configData,
			agentId: this.validateForm.controls.agentid.value,
			appId: this.validateForm.controls.appid.value,
      id: this.id,
      appSecret: this.validateForm.controls.secret.value,
      createUser:
        this.validateForm.controls.autoCreateUser.value === "1" ? 1 : 0,
      bindAccount:
        this.validateForm.controls.bindAccount.value === "1" ? 1 : 0,
      defaultRole: this.validateForm.controls.defaultRole.value,
      hospital: this.validateForm.controls.defaultHospital.value,
      defaultDept: this.validateForm.controls.defaultDept.value,
      defaultGroup: this.validateForm.controls.defaultGroup.value,
    };
    this.loading2 = true;
    this.mainService.changeWechatConfig(postData).subscribe(
      (result) => {
        this.loading2 = false;
        if (result["status"] == 200) {
          this.showPromptModal("保存", true, "");
        } else {
          this.showPromptModal("保存", false, "");
        }
      },
      (error) => {
        this.loading2 = false;
        this.showPromptModal("保存", false, "");
      }
    );
  }
  // 获取微信配置
	configData:any;
  getWechatConfig() {
    const postData = { idx: 0, sum: 1 };
    this.mainService
      .getFetchDataList("simple/data", "wechatConfig", postData)
      .subscribe((result) => {
        if (result.status == 200) {
					this.configData = result.list[0];
          const config = result.list[0];
          if (!config) {
            this.loading1 = false;
            return;
          }
          this.hosId = config.hospital;
          this.getGroupList(config.hospital).subscribe((result1) => {
            if (result1.status == 200) {
              this.groupList = result1.list;
              this.getDeptList(config.hospital).subscribe((result2) => {
                if (result2.status == 200) {
                  this.loading1 = false;
                  this.deptList = result2.list;
                  this.id = config.id;
                  this.validateForm.controls.secret.setValue(config.appSecret);
                  this.validateForm.controls.appid.setValue(config.appId);
                  this.validateForm.controls.agentid.setValue(config.agentId);
                  this.validateForm.controls.autoCreateUser.setValue(
                    config.createUser ? "1" : "0"
                  );
                  this.validateForm.controls.bindAccount.setValue(
                    config.bindAccount ? "1" : "0"
                  );
                  this.validateForm.controls.defaultRole.setValue(
                    config.defaultRole
                  );
                  this.validateForm.controls.defaultHospital.setValue(
                    config.hospital
                  );
                  this.mainService.getFetchData("data", "department", config.defaultDept).subscribe((result) => {
                    if (result.status == 200) {
                      if(result.data){
                        this.deptList.unshift(result.data);
                      }
                      this.validateForm.controls.defaultDept.setValue(
                        config.defaultDept
                      );
                    }
                  });
                  this.validateForm.controls.defaultGroup.setValue(
                    config.defaultGroup
                  );
                } else {
                  this.loading1 = false;
                }
              });
            } else {
              this.loading1 = false;
            }
          });
        } else {
          this.loading1 = false;
        }
      });
  }
  // 获取角色列表
  getRoleList() {
    const postData = { idx: 0, sum: 1000 };
    this.loading1 = true;
    this.mainService
      .getFetchDataList("data", "role", postData)
      .subscribe((result) => {
        if (result.status == 200) {
          this.roleList = result.list;
          this.getWechatConfig();
        } else {
          this.loading1 = false;
        }
      });
  }
  // 展示信息提示框（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.loading1 = true;
    this.getWechatConfig();
  }
  //修改默认院区
  hospitalChange(hosId) {
    this.hosId = hosId;
    this.validateForm.controls.defaultDept.setValue(null);
    this.validateForm.controls.defaultGroup.setValue(null);
    this.getGroupList(hosId).subscribe((result) => {
      if (result.status == 200) {
        this.groupList = result.list;
        this.getDeptList(hosId).subscribe((result1) => {
          if (result1.status == 200) {
            this.deptList = result1.list;
          }
        });
      }
    });
  }
  // 获取科室列表
  getDeptList(hosId, value?, num?) {
    let sum = num || 20;
    const postData: any = {
      idx: 0,
      sum,
      department: { hospital: { id: hosId } },
    };
    if (value) {
      postData.department.dept = value;
    }
    return this.mainService.getFetchDataList("data", "department", postData);
  }
  // 获取组列表
  getGroupList(hosId) {
    const postData = { idx: 0, sum: 9999, group2: { hospitals: hosId,type:1 } };
    return this.mainService.getFetchDataList("data", "group2", postData);
  }
  //搜索科室
  onDeptSearchNew(value) {
    this.loading3 = true;
    this.onDeptSearchSubject.next(value);
  }
  //搜索科室
  onDeptSearch(value): void {
    this.getDeptList(this.hosId, value).subscribe((result) => {
      this.loading3 = false;
      if (result.status == 200) {
        this.deptList = result.list;
      }
    });
  }
}
