import { Component, OnInit } from "@angular/core";
import { ActivatedRoute, Router } from "@angular/router";
import { FormBuilder, Validators, FormGroup } from "@angular/forms";

import { MainService } from "../../services/main.service";
import { ToolService } from "../../services/tool.service";
import { NzMessageService } from 'ng-zorro-antd';
@Component({
  selector: "app-inspection-configuration",
  templateUrl: "./inspection-configuration.component.html",
  styleUrls: ["./inspection-configuration.component.less"],
})
export class InspectionConfigurationComponent implements OnInit {
  constructor(
    private fb: FormBuilder,
    private mainService: MainService,
    private route: ActivatedRoute,
    private router: Router,
    private tool: ToolService,
    private message: NzMessageService,
  ) {}

  listOfData: any[] = []; //表格数据
  pageIndex: number = 1; //表格当前页码
  pageSize: number = 10; //表格每页展示条数
  listLength: number = 10; //表格总数据量
  modal: boolean = false; //新增/编辑模态框
  add: boolean; //true:新增；false:编辑
  validateForm: FormGroup; //新增/编辑表单
  coopData: any; //当前操作列
  currentHospital; //当前院区

  btnLoading: boolean = false; //提交按钮loading状态

  promptContent: string; //操作提示框提示信息
  ifSuccess: boolean; //操作成功/失败
  promptInfo: string; //操作结果提示信息
  promptModalShow: boolean; //操作提示框是否展示
  nextSchemeName = ""; //下一个开启的方案名称
  modelName = ""; //模态框名称

  ngOnInit() {
    this.currentHospital = this.tool.getCurrentHospital();
    this.coopBtns = this.tool.initCoopBtns(this.route);
    this.initForm();
    this.getList(1);
  }

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

  // 表格数据
  loading1 = false;
  getList(type) {
    if (type == 1) {
      this.pageIndex = 1;
    }
    let data = {
      idx: this.pageIndex - 1,
      sum: this.pageSize,
      inspectionForm: {
        hosId: this.currentHospital.id,
      },
    };
    this.loading1 = true;
    this.mainService
      .getFetchDataList("simple/data", "inspectionForm", data)
      .subscribe((data) => {
        this.loading1 = false;
        if (data.status == 200) {
          this.listOfData = data.list;
          this.listLength = data.totalNum;
        }else{
          this.message.error(data.msg || "请求数据失败");
        }
      });
  }

  // 新增弹框
  addModal() {
    this.modelName = "新增";
    this.add = true; //新增
    this.modal = true;
    this.initForm();
  }
  //关闭新增/编辑弹框
  hideAddModal() {
    this.modal = false;
    this.initForm();
  }

  // 初始化新增form表单
  initForm() {
    this.validateForm = this.fb.group({
      name: ['', [Validators.required, Validators.pattern(/\S/)]],
      showOrder: [0, [Validators.required]],
      createOrder: [0, [Validators.required]],
    });
  }

  // 新增/编辑表单提交
  submitForm(): void {
    for (const i in this.validateForm.controls) {
      this.validateForm.controls[i].markAsDirty();
      this.validateForm.controls[i].updateValueAndValidity();
    }
    if (this.validateForm.invalid) {
      return;
    }
    this.btnLoading = true;
    let data:any = {};

    if (this.add) {
      //增加
      data = {
        name: this.validateForm.value.name,
        showOrder: this.validateForm.value.showOrder,
        createOrder: this.validateForm.value.createOrder,
        hosId: this.currentHospital.id,
      };
    } else {
      //编辑
      data = {
        ...this.coopData,
        ...{
          name: this.validateForm.value.name,
          showOrder: this.validateForm.value.showOrder,
          createOrder: this.validateForm.value.createOrder,
        }
      };
    }
    this.mainService
      .simplePost("addData", "inspectionForm", data)
      .subscribe((result) => {
        this.btnLoading = false;
        this.hideAddModal();
        this.initForm();
        if (result.status == 200) {
          if (this.add) {
            this.listLength++;
            this.router.navigateByUrl(`/main/inspectionConfigurationItem/${result.data.id}`);
          } else {
            this.showPromptModal("编辑", true, "");
          }
        } else {
          let msg = "";
          if (this.add) {
            msg = "新增";
          } else {
            msg = "修改";
          }
          this.showPromptModal(msg, false, result.msg);
        }
      });
  }

  // 编辑
  edit(data) {
    console.log(data);
    this.modelName = "编辑";
    this.add = false;
    this.modal = true;
    this.coopData = data;
    this.validateForm.controls.name.setValue(data.name); //名称
    this.validateForm.controls.showOrder.setValue(data.showOrder);
    this.validateForm.controls.createOrder.setValue(data.createOrder);
  }

  // 展示信息提示框（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(0);
  }

  // 跳转到配置项
  toItem(data){
    this.router.navigateByUrl(`/main/inspectionConfigurationItem/${data.id}`);
  }

  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", "inspectionForm", [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 === "publish") {
      //发布
      let data = {
        formId: this.coopData.id,
      };
      this.mainService
        .inspectionPost("formPublish", data)
        .subscribe((result) => {
          this.btnLoading = false;
          this.delModal = false;
          if (result.status == 200) {
            this.showPromptModal(this.tipsMsg2, true, "");
          } else {
            this.showPromptModal(this.tipsMsg2, false, result.msg);
          }
        });
    }
  }
}
