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

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

  coopData: any = {}; //当前操作列
  hosId: any = this.tool.getCurrentHospital().id;


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

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

  // 编辑
  editWechat(data) {
    console.log(data);
    this.modelName = "编辑";
    this.add = false;
    this.modalWechat = true;
    this.initWechatForm();
    this.coopData = data;
    this.validateForm.controls.orders.setValue(data.orders);
    this.validateForm.controls.name.setValue(data.name);
    this.validateForm.controls.extra4.setValue(data.extra4 ? +data.extra4 : undefined);
    this.validateForm.controls.extra5.setValue(data.extra5 || '0');
    this.validateForm.controls.extra6.setValue(data.extra6 || '0');
    this.validateForm.controls.extra7.setValue(data.extra7);
  }

  // 新增/编辑表单提交
  btnLoading: boolean = false; //提交按钮loading状态
  submitWechatForm(): 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 = {};

    let arr = this.dataList.filter(
      (item) => item.name == this.validateForm.value.name && item.id != this.coopData.id
    );

    //有重复名称
    if (arr.length > 0) {
      this.btnLoading = false;
      this.showPromptModal(
        this.add ? "新增" : "编辑",
        false,
        `存在重复的退回原因【${this.validateForm.value.name}】请修改后再保存！`
      );
      return;
    }

    if (this.add) {
      //增加
      let n = 0;
      if (this.dataList.length > 0) {
        let sortArr = this.dataList.map((item) => Number(item.value));
        n = Math.max.apply(null, sortArr);
      } else {
        n = 0;
      }
      postData = {
        // dictionary: {
          key: "reason_for_return",
          value: n + 1,
          desc: "标本退回",
          orders: this.validateForm.value.orders,
          name: this.validateForm.value.name,
          extra6: this.validateForm.value.extra6,
          extra4: this.validateForm.value.extra4,
          extra5: this.validateForm.value.extra5,
          extra7: this.validateForm.value.extra7,
        // }
      };
    } else {
      //编辑
      postData = {
        // dictionary: {
          ...this.coopData,
          orders: this.validateForm.value.orders,
          name: this.validateForm.value.name,
          extra6: this.validateForm.value.extra6,
          extra4: this.validateForm.value.extra4,
          extra5: this.validateForm.value.extra5,
          extra7: this.validateForm.value.extra7,
        // }
      };
    }
    this.mainService
      .simplePost("addData", "dictionary", 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表单
  validateForm: FormGroup; //新增/编辑表单
  initWechatForm() {
    this.validateForm = this.fb.group({
      orders: [null, [Validators.required]],
      name: [null, [Validators.required]],
      extra4: [null, [Validators.required]],
      extra5: [null, [Validators.required]],
      extra6: [null, [Validators.required]],
      extra7: [null, [Validators.required]],
    });
  }

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

  isLoading = false;
  extra7List: any = [
    { name: '无', id: '0' },
    { name: '科室码', id: '1' },
    { name: '动态码', id: '2' },
    { name: '填写工号', id: '3' },
  ];

  // 获取退回标本状态
  typeList: any = [];
  getTypes() {
    this.mainService.getDictionary('list', 'speState').subscribe((data) => {
      this.isLoading = false;
      this.typeList = data || [];
    });
  }

  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", "dictionary", [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.getList();
  }
}
