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

@Component({
  selector: "app-serial-number-setting",
  templateUrl: "./serial-number-setting.component.html",
  styleUrls: ["./serial-number-setting.component.less"],
})
export class SerialNumberSettingComponent 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
  hosId: any; //院区（搜索）
  dateTypes: Array<any> = []; //所有日期方案
  pageIndex: number = 1; //页码
  listLength: number = 10; //总条数
  pageSize: number = 10; //每页条数

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

  btnLoading: boolean = false; //提交按钮loading状态
  isShowDateType = false; //是否显示日期方案

  ngOnInit() {
    this.coopBtns = this.tool.initCoopBtns(this.route);
    this.initForm();
    this.getUserTypes();
    this.getGender();
  }

  // 初始化增删改按钮
  coopBtns: any = {};
  // 表格数据
  loading1 = false;
  getList() {
    let data = {
      idx: this.pageIndex - 1,
      sum: this.pageSize,
      serialnumberConfig: {
        hosId: this.hosId,
      },
    };
    this.loading1 = true;
    this.mainService
      .getFetchDataList("simple/data", "serialnumberConfig", data)
      .subscribe((data) => {
        this.loading1 = false;
        this.listOfData = data.list;
        this.listLength = data.totalNum;
      });
  }

  // 获取所有日期类型
  getUserTypes() {
    this.mainService.getDictionary("list", "serialnumber_date_type").subscribe((data) => {
      this.dateTypes = data;
      this.getAllHospital();
    });
  }

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

  // 获取生成方案
  generateTypes: Array<any> = [];
  getGender() {
    var that = this;
    that.mainService.getDictionary("list", "serialnumber_generate_type").subscribe((data) => {
      that.generateTypes = data;
    });
  }

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

  // 初始化新增form表单
  initForm() {
    this.validateForm = this.fb.group({
      title: [null, [Validators.required]],
      prefix: [null, [Validators.required]],
      length: [1, [Validators.required]],
      generateType: [null, [Validators.required]],
      dateType: [null, [Validators.required]],
    });
  }
  // 选择生成方案
  generateTypeChange(dateType) {
    if(dateType){
      this.validateForm.controls.dateType.setValue(dateType.id);
    }else{
      this.validateForm.controls.dateType.setValue(null);
    }
    let value = this.generateTypes.find(v => v.id == this.validateForm.value.generateType).value;
    this.isShowDateType = value == 2;
    if(this.isShowDateType){
      this.validateForm.get("dateType")!.setValidators(Validators.required);
      this.validateForm.get("dateType")!.markAsDirty();
    }else{
      this.validateForm.get("dateType")!.clearValidators();
      this.validateForm.get("dateType")!.markAsPristine();
    }
  }
  // 表单提交
  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 data:any = {
      title: that.validateForm.value.title,
      prefix: that.validateForm.value.prefix,
      length: that.validateForm.value.length,
      generateType: { id: that.validateForm.value.generateType },
      dateType: that.validateForm.value.dateType ? { id: that.validateForm.value.dateType } : undefined,
      hosId: that.hosId,
    };
    if (!that.add) {
      data = {...this.coopData, ...data};
    }
    that.mainService
      .simplePost("addData", "serialnumberConfig", data)
      .subscribe((data) => {
        that.btnLoading = false;
        that.hideModal();
        that.initForm();
        if (data.status == 200) {
          if(data.data && data.data.prefix){
            that.showPromptModal(that.add ? "新增" : "编辑", true, "");
          }else{
            that.showPromptModal(that.add ? "新增" : "编辑", false, '开头字母不能重复！');
          }
        } else {
          that.showPromptModal(that.add ? "新增" : "编辑", false, data.msg);
        }
      });
  }

  // 编辑
  maskFlag: any = false;
  coopData:any = {};
  edit(data) {
    this.modal = true;
    this.add = false;
    this.coopId = data.id;
    this.coopData = data;
    this.validateForm.controls.title.setValue(data.title);
    this.validateForm.controls.prefix.setValue(data.prefix);
    this.validateForm.controls.length.setValue(data.length);
    this.validateForm.controls.generateType.setValue(data.generateType.id);
    this.generateTypeChange(data.dateType);
  }

  // 删除
  delModal: boolean = false; //删除模态框
  del(data) {
    this.coopId = data.id;
    this.delModal = true;
  }
  // 确认删除
  confirmDel() {
    let that = this;
    that.btnLoading = true;
    that.mainService
      .simplePost("rmvData", "serialnumberConfig", [that.coopId])
      .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"]);
        }
      });
  }
  // 关闭删除模态框
  hideDelModal() {
    this.delModal = 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.getList();
  }

  // 查看
  detail(id) {
    this.router.navigateByUrl("/main/serialNumberSetting/serialNumberSettingDetail/" + id);
  }
  isLoading = false;
}
