import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';
import { MainService } from '../../services/main.service';
import { ToolService } from 'src/app/services/tool.service';
import { NzMessageService } from 'ng-zorro-antd';
import { FormGroup, Validators, FormBuilder } from '@angular/forms';

@Component({
  selector: 'app-assets-product-management-prompt-modal',
  templateUrl: './assets-product-management-prompt-modal.component.html',
  styleUrls: ['./assets-product-management-prompt-modal.component.less']
})
export class AssetsProductManagementPromptModalComponent implements OnInit {
  // 切换科室，切换弹窗
  hsLoading = false;
  historySpecimenList: any = [];

  currentHospital; //当前院区
  @Input() show: Boolean;
  @Input() id: Number;

  @Output() closeModelHs = new EventEmitter<any>();//1.组件暴露一个 EventEmitter 属性，当事件发生时，子组件利用该属性 emits(向上弹射)事件

  constructor(
    private mainService: MainService,
    private tool: ToolService,
    private message: NzMessageService,
    private fb: FormBuilder,
  ) { }

  ngOnInit() {
    this.currentHospital = this.tool.getCurrentHospital();
    this.getList();
    this.getIncidentCategoryList();
  }

  // 获取故障现象
  incidentCategoryList:any[] = [];
  getIncidentCategoryList(){
    let { hospital, type } = this.tool.getHospitalOrDuty();
    if(type === 'hospital' || type === 'department'){
      this.incidentCategoryList = [];
      return;
    };
    let postData = {
      hasThird: 'true',//只差有三级的故障现象列表
      category: {
        dutyIds: type === 'duty' ? hospital.id.toString()  : undefined,
      },
    };
    this.mainService.incidentPost("listIncidentCategory", postData).subscribe(res => {
      let incidentCategoryList = res.data || [];
      incidentCategoryList = incidentCategoryList.map(v => ({...v, parentId: v.parent ? v.parent.id : undefined, label: v.category, value: v.id}));
      this.incidentCategoryList = this.tool.tranListToTreeDataLeaf(incidentCategoryList, undefined, "parentId");
      console.log(this.incidentCategoryList);
    })
  }

  // 编辑
  edit(e, data) {
    e.stopPropagation();
    console.log(data);
    this.initForm();
    this.modelName = "编辑";
    this.add = false;
    this.modal = true;
    this.coopData = data;
    this.validateForm.controls.alias.setValue(data.alias);
    this.validateForm.controls.incidentCategoryId.setValue(this.tool.tranListToTreeDataFindIdsLeaf(this.incidentCategoryList, data.incidentCategoryId));
  }

  // 新增弹框
  modelName = ""; //模态框名称
  modal: boolean = false; //新增/编辑模态框
  add: boolean; //true:新增；false:编辑
  validateForm: FormGroup; //新增/编辑表单
  coopData: any; //当前操作列
  addModal() {
    this.modelName = "新增";
    this.add = true; //新增
    this.modal = true;
    this.initForm();
  }
  //关闭新增/编辑弹框
  hideAddModal() {
    this.modal = false;
    this.initForm();
  }

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

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

    console.log(this.validateForm.value)

    this.btnLoading = true;
    let postData:any = {};

    if (this.add) {
      //增加
      postData = {
        // assetProductIncidentCategory: {
          hosId: this.currentHospital.id,
          alias: this.validateForm.value.alias,
          productId: this.id,
          incidentCategoryId: this.validateForm.value.incidentCategoryId.length ? this.validateForm.value.incidentCategoryId.slice(-1)[0] : undefined,
        // }
      };
    } else {
      //编辑
      postData = {
        // assetProductIncidentCategory:{
          ...this.coopData,
          ...{
            hosId: this.currentHospital.id,
            alias: this.validateForm.value.alias,
            productId: this.id,
            incidentCategoryId: this.validateForm.value.incidentCategoryId.length ? this.validateForm.value.incidentCategoryId.slice(-1)[0] : undefined,
          }
        // }
      };
    }
    console.log(postData);
    this.mainService
      .simplePost("addData", "assetProductIncidentCategory", postData)
      .subscribe((result) => {
        this.btnLoading = false;
        this.hideAddModal();
        let msg = "";
        if (this.add) {
          msg = "新增";
        } else {
          msg = "修改";
        }
        if (result.status == 200) {
          this.showPromptModal(msg, true, "");
        } else {
          this.showPromptModal(msg, false, result.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.getList();
  }

  delModal: boolean = false; //删除模态框
  tipsMsg1: string; //提示框信息
  tipsMsg2: string; //操作后信息
  confirmDelType: string; //确认的类型（启用/停用，删除）
  confirmDelIsSwitch: boolean; //启用/停用
  showDelModal(
    e,
    data,
    tipsMsg1: string,
    tipsMsg2: string,
    type: string,
    isSwitch?: boolean
  ) {
    e.stopPropagation();
    this.confirmDelIsSwitch = isSwitch;
    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", "assetProductIncidentCategory", [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 === "switch") {
      //启用/停用
      let postData = {
        // assetProductIncidentCategory:{
          ...this.coopData,
          ...{
            status: { key: 'product_category_status', value: this.confirmDelIsSwitch ? '0' : '1' },
          }
        // }
      };
      console.log(postData);
      this.mainService
        .simplePost("addData", "assetProductIncidentCategory", postData)
        .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);
          }
        });
    }
  }

  // 关闭弹窗
  hideModal() {
    this.closeModelHs.emit(JSON.stringify({ show: false }));//emits(向上弹射)事件
  }
  // 获取列表数据
  getList() {
    let postData = {
      idx: 0,
      sum: 9999,
      assetProductIncidentCategory: {
        productId: this.id,
        hosId: this.currentHospital.id,
      }
    }
    this.hsLoading = true;
    this.mainService.getFetchDataList("data", "assetProductIncidentCategory", postData).subscribe(data => {
      this.hsLoading = false;
      this.historySpecimenList = data.list || [];
    })
  }
}


