import { Component, OnInit } from "@angular/core";
import { ActivatedRoute } from "@angular/router";
import { Subject } from 'rxjs';
import { debounceTime } from 'rxjs/operators';
import { MainService } from "../../../services/main.service";
import { Validators, FormGroup, FormBuilder } from '@angular/forms';
import { ToolService } from 'src/app/services/tool.service';
import { NzMessageService } from 'ng-zorro-antd';

@Component({
  selector: "app-configuration-wechat",
  templateUrl: "./configuration-wechat.component.html",
  styleUrls: ["./configuration-wechat.component.less"],
})
export class ConfigurationWechatComponent implements OnInit {
  constructor(
    private route: ActivatedRoute,
    private mainService: MainService,
    private fb: FormBuilder,
    private tool: ToolService,
    private message: NzMessageService,
  ) {}

  coopData: any = {}; //当前操作列
  currentHospital; //当前院区

  formatterMinute = (value: number) => `${value} 分钟`;
  parserMinute = (value: string) => value.replace(' 分钟', '');

  ngOnInit() {
    this.currentHospital = this.tool.getCurrentHospital();
    setTimeout(() => {
      this.tableWechatHeight = document.querySelector('#wechatTable').clientHeight - document.querySelector('#wechatTable .list-template__top').clientHeight - 8 - document.querySelector('#wechatTable .thead').clientHeight;
    }, 0)
    this.getWechatList();
    this.getTypes();
    this.getRoles();
  }

  // 新增弹框
  modelName = ""; //模态框名称
  modalWechat: boolean = false; //新增/编辑模态框
  add: boolean; //true:新增；false:编辑
  addWechatModal() {
    this.modelName = "新增";
    this.add = true; //新增
    this.modalWechat = true;
    this.initWechatForm();
    this.requiredConfigChange('createUser', false);
    this.requiredConfigChange('defaultRole', false);
  }
  //关闭新增/编辑弹框
  hideWechatModal() {
    this.modalWechat = false;
  }

  // 编辑
  editWechat(data) {
    console.log(data);
    this.modelName = "编辑";
    this.add = false;
    this.modalWechat = true;
    this.initWechatForm();
    if(data.bindAccount){
      this.requiredConfigChange('createUser', false);
    }else{
      this.requiredConfigChange('createUser', true);
    }

    if(data.createUser){
      this.requiredConfigChange('defaultRole', true);
    }else{
      this.requiredConfigChange('defaultRole', false);
    }
    this.coopData = data;
    this.validateWechatForm.controls.name.setValue(data.name);
    this.validateWechatForm.controls.appId.setValue(data.appId);
    this.validateWechatForm.controls.appSecret.setValue(data.appSecret);
    this.validateWechatForm.controls.agentId.setValue(data.agentId);
    this.validateWechatForm.controls.url.setValue(data.url);
    this.validateWechatForm.controls.domain.setValue(data.domain);
    this.validateWechatForm.controls.active.setValue(data.active);
    this.validateWechatForm.controls.qy.setValue(data.qy);
    this.validateWechatForm.controls.type.setValue(data.type ? data.type.id : null);
    this.validateWechatForm.controls.bindAccount.setValue(data.bindAccount);
    this.validateWechatForm.controls.createUser.setValue(data.createUser);
    this.validateWechatForm.controls.defaultRole.setValue(data.defaultRole);
  }

  // 新增/编辑表单提交
  btnLoading: boolean = false; //提交按钮loading状态
  submitWechatForm(): void {
    for (const i in this.validateWechatForm.controls) {
      this.validateWechatForm.controls[i].markAsDirty();
      this.validateWechatForm.controls[i].updateValueAndValidity();
    }
    if (this.validateWechatForm.invalid) {
      return;
    }
    console.log(this.validateWechatForm.value);
    this.btnLoading = true;
    let postData:any = {};

    if (this.add) {
      //增加
      postData = {
        // wechatConfig: {
          hospital: this.currentHospital.id,
          name: this.validateWechatForm.value.name,
          appId: this.validateWechatForm.value.appId,
          appSecret: this.validateWechatForm.value.appSecret,
          agentId: this.validateWechatForm.value.agentId,
          url: this.validateWechatForm.value.url,
          domain: this.validateWechatForm.value.domain,
          active: this.validateWechatForm.value.active,
          qy: this.validateWechatForm.value.qy,
          type: { id: this.validateWechatForm.value.type },
          bindAccount: this.validateWechatForm.value.bindAccount,
          createUser: this.validateWechatForm.value.createUser,
          defaultRole: this.validateWechatForm.value.defaultRole,
        // }
      };
    } else {
      //编辑
      postData = {
        // wechatConfig: {
          ...this.coopData,
          ...{
            hospital: this.currentHospital.id,
            name: this.validateWechatForm.value.name,
            appId: this.validateWechatForm.value.appId,
            appSecret: this.validateWechatForm.value.appSecret,
            agentId: this.validateWechatForm.value.agentId,
            url: this.validateWechatForm.value.url,
            domain: this.validateWechatForm.value.domain,
            active: this.validateWechatForm.value.active,
            qy: this.validateWechatForm.value.qy,
            type: { id: this.validateWechatForm.value.type },
            bindAccount: this.validateWechatForm.value.bindAccount,
            createUser: this.validateWechatForm.value.createUser,
            defaultRole: this.validateWechatForm.value.defaultRole,
          }
        // }
      };
    }
    this.mainService
      .simplePost("addData", "wechatConfig", postData)
      .subscribe((result) => {
        this.btnLoading = false;
        this.hideWechatModal();
        let msg = "";
        if (this.add) {
          msg = "新增";
        } else {
          msg = "修改";
        }
        if (result.status == 200) {
          this.showPromptModal(msg, true, '');
        } else {
          this.showPromptModal(msg, false, result.msg);
        }
      });
  }

  // 初始化新增form表单
  validateWechatForm: FormGroup; //新增/编辑表单
  initWechatForm() {
    this.validateWechatForm = this.fb.group({
      name: [null, [Validators.required]],
      appId: [null, [Validators.required]],
      appSecret: [null, [Validators.required]],
      agentId: [null, [Validators.required]],
      url: [null, [Validators.required]],
      domain: [null, [Validators.required]],
      active: [false, [Validators.required]],
      qy: [false, [Validators.required]],
      type: [null, [Validators.required]],
      bindAccount: [true, [Validators.required]],
      createUser: [false,],
      defaultRole: [null,],
    });
    console.log(this.validateWechatForm.controls)
  }

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

  changeBindAccount(e){
    if(e){
      this.requiredConfigChange('createUser', false);
      this.requiredConfigChange('defaultRole', false);
    }else{
      this.requiredConfigChange('createUser', true);
      this.requiredConfigChange('defaultRole', false);
    }

    this.validateWechatForm.controls.createUser.setValue(false);
    this.validateWechatForm.controls.defaultRole.setValue(null);
  }

  changeCreateUser(e){
    if(e){
      this.requiredConfigChange('createUser', true);
      this.requiredConfigChange('defaultRole', true);
    }else{
      this.requiredConfigChange('createUser', true);
      this.requiredConfigChange('defaultRole', false);
    }

    this.validateWechatForm.controls.defaultRole.setValue(null);
  }

  // 获取列表
  loading1:boolean = false;
  wechatList: any[] = []; //表格数据
  tableWechatHeight:number = 0;
  getWechatList() {
    let data = {
      idx: 0,
      sum: 9999,
      wechatConfig: {},
    };
    this.loading1 = true;
    this.mainService
      .getFetchDataList("simple/data", "wechatConfig", data)
      .subscribe((data) => {
        this.loading1 = false;
        if (data.status == 200) {
          this.wechatList = data.list || [];
        }else{
          this.message.error(data.msg || "请求数据失败");
        }
      });
  }

  // 获取角色
  defaultRoleList: any = [];
  getRoles() {
    let postData = {
      role: {},
      idx: 0,
      sum: 9999,
    };
    this.mainService
      .getFetchDataList("simple/data", "role", postData)
      .subscribe((data) => {
        this.isLoading = false;
        this.defaultRoleList = data.list || [];
      });
  }

  // 获取类型
  isLoading:boolean = false;
  typeList: any = [];
  getTypes() {
    let postData = {
      dictionary: {
        key: "wechat_config_type"
      },
      idx: 0,
      sum: 9999,
    };
    this.mainService
      .getFetchDataList("simple/data", "dictionary", postData)
      .subscribe((data) => {
        this.isLoading = false;
        this.typeList = data.list || [];
      });
  }

  delModal: boolean = false; //删除模态框
  tipsMsg1: string; //提示框信息
  tipsMsg2: string; //操作后信息
  confirmDelType: string; //确认的类型（启用/停用，删除）
  showDelModal(
    data,
    tipsMsg1: string,
    tipsMsg2: string,
    type: string,
  ) {
    this.confirmDelType = type;
    this.delModal = true;
    this.coopData = data;
    this.tipsMsg1 = tipsMsg1;
    this.tipsMsg2 = tipsMsg2;
  }
  // 隐藏删除框
  hideDelModal() {
    this.delModal = false;
  }
  // 确认删除
  confirmDel() {
    this.btnLoading = true;
    if (this.confirmDelType === "del") {
      //删除
      this.mainService
        .simplePost("rmvData", "wechatConfig", [this.coopData.id])
        .subscribe((data) => {
          this.btnLoading = false;
          this.delModal = false;
          if (data.status == 200) {
            this.showPromptModal(this.tipsMsg2, true, "");
          } else {
            this.showPromptModal(this.tipsMsg2, false, data.msg);
          }
        });
    }else if(this.confirmDelType === "delToken"){
      //重置token
      this.mainService
        .refreshToken("refreshToken", { wechatConfigId: this.coopData.id })
        .subscribe((data) => {
          this.btnLoading = false;
          this.delModal = false;
          if (data.status == 200) {
            this.showPromptModal(this.tipsMsg2, true, "");
          } else {
            this.showPromptModal(this.tipsMsg2, false, data.msg);
          }
        });
    }
  }

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