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

import { ToolService } from "../../services/tool.service";
import { QuiltDepartmentBindService } from './quilt-department-bind.service';
import { Subject } from 'rxjs';
import { debounceTime } from 'rxjs/operators';
import { NzMessageService } from 'ng-zorro-antd/message';
@Component({
  selector: "app-quilt-department-bind",
  templateUrl: "./quilt-department-bind.component.html",
  styleUrls: ["./quilt-department-bind.component.less"],
})
export class QuiltDepartmentBindComponent implements OnInit {
  constructor(
    private fb: FormBuilder,
    private quiltDepartmentBindService: QuiltDepartmentBindService,
    private route: ActivatedRoute,
    private tool: ToolService,
    private message: NzMessageService,
  ) {}

  userInfo: any = JSON.parse(localStorage.getItem("user")) || {}; //登录用户信息
  listOfData: any[] = []; //表格数据
  pageIndex: number = 1; //表格当前页码
  pageSize: number = 10; //表格每页展示条数
  listLength: number = 10; //表格总数据量
  tableHeight: number; //表格动态高
  modal: boolean = false; //新增/编辑模态框
  add: boolean; //true:新增；false:编辑
  validateForm: FormGroup; //新增/编辑表单
  coopId: any; //当前操作列
  currentHospital; //当前院区

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

  promptContent: string; //操作提示框提示信息
  ifSuccess: boolean; //操作成功/失败
  promptInfo: string; //操作结果提示信息
  promptModalShow: boolean; //操作提示框是否展示
  modelName = ""; //模态框名称

  changeInpSubject = new Subject(); //防抖

  ngOnInit() {
    //防抖
    this.changeInpSubject.pipe(debounceTime(500)).subscribe((v) => {
      if(v[1] === 'clothesTypeIds'){
        this.getClothesTypeIdsList(true, v[0]);
      }else if(v[1] === 'deptIds'){
        this.getDeptList(true, v[0]);
      }
    });
    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,
      clothesDept: {
        hosId: this.currentHospital.id,
      },
    };
    this.loading1 = true;
    this.quiltDepartmentBindService
      .getFetchDataList(data)
      .subscribe((data) => {
        this.loading1 = false;
        if (data.status == 200) {
          data.list.forEach(v => {
            v.deptIds = v.depts.map(v => v.id);
            v.deptNames = v.depts.map(v => v.dept).toString();
            v.clothesTypeIds = v.clothesTypes.map(v => v.id);
            v.clothesTypeNames = v.clothesTypes.map(v => v.name).toString();
          });
          this.listOfData = data.list;
          this.listLength = data.totalNum;
        }
      });
  }

  //打开查询被服种类下拉框
  isLoading:boolean = false;
  clothesTypeIdsList:any[] = [];
  getClothesTypeIdsList(flag, keyWord = '') {
    if (flag) {
      let postData = {
        idx: 0,
        sum: 9999,
        dictionaryTree: {
          hosId: this.currentHospital.id,
          level: 2,
          key: 'clothes_type',
          deleted: 0,
        },
      };
      this.isLoading = true;
      this.quiltDepartmentBindService
      .getClothesTypes(postData)
      .subscribe((data) => {
        this.isLoading = false;
        if (data.status == 200) {
          this.clothesTypeIdsList = data.list;
        }
      });
    }
  }

  //打开查询科室下拉框
  deptList:any[] = [];
  getDeptList(flag, keyWord = '') {
    if (flag) {
      let postData = {
        idx: 0,
        sum: 9999,
        department: {
          searchType: 1,// 简单查询
          dept: keyWord,
          cascadeHosId: this.currentHospital.id,
        }
      };
      this.isLoading = true;
      this.quiltDepartmentBindService
      .getDepts(postData)
      .subscribe((data) => {
        this.isLoading = false;
        if (data.status == 200) {
          this.deptList = data.list;
        }
      });
    }
  }

  //搜索
  changeInp(e, type) {
    this.isLoading = true;
    this.changeInpSubject.next([e, type]);
  }

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

  // 初始化新增form表单
  initForm() {
    this.validateForm = this.fb.group({
      typeName: ['', [Validators.required]],
      clothesTypeIds: [[], [Validators.required]],
      deptIds: [[], [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;
    }
    if((/^\s+/.test(this.validateForm.value.typeName) || /\s+$/.test(this.validateForm.value.typeName)) && !this.validateForm.value.typeName.trim()){
      this.message.info('请设置业务名称！');
      return;
    }

    this.btnLoading = true;
    let data = {};

    if (this.add) {
      //增加
      data = {
        typeName: this.validateForm.value.typeName.trim(),
        clothesTypeIds: this.validateForm.value.clothesTypeIds.toString(),
        deptIds: this.validateForm.value.deptIds.toString(),
        hosId: this.currentHospital.id,
      };
    } else {
      //编辑
      data = {
        ...this.coopId,
        typeName: this.validateForm.value.typeName.trim(),
        clothesTypeIds: this.validateForm.value.clothesTypeIds.toString(),
        deptIds: this.validateForm.value.deptIds.toString(),
        hosId: this.currentHospital.id,
      };
    }
    this.quiltDepartmentBindService
      .simplePost("addData", "clothesDept", data)
      .subscribe((result) => {
        this.btnLoading = false;
        this.hideAddModal();
        this.initForm();
        if (result.status == 200) {
          if (this.add) {
            this.showPromptModal("新增", true, "");
            this.listLength++;
          }else{
            this.showPromptModal("编辑", true, "");
          }
        } else {
          this.showPromptModal(this.add ? '新增' : '修改', false, result.msg);
        }
      });
  }

  // 编辑
  edit(data) {
    console.log(data);
    this.modelName = "编辑";
    this.add = false;
    this.modal = true;
    this.coopId = data;

    this.deptList = data.depts ? data.depts : [];
    this.clothesTypeIdsList = data.clothesTypes ? data.clothesTypes : [];
    this.validateForm.controls.typeName.setValue(data.typeName);
    this.validateForm.controls.clothesTypeIds.setValue(data.clothesTypeIds);
    this.validateForm.controls.deptIds.setValue(data.deptIds);
  }

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

  delModal: boolean = false; //删除模态框
  tipsMsg1: string; //提示框信息
  tipsMsg2: string; //操作后信息
  confirmDelType: string; //确认的类型（启用/停用，删除）
  showDelModal(
    data,
    tipsMsg1: string,
    tipsMsg2: string,
    type: string,
  ) {
    this.confirmDelType = type;
    this.delModal = true;
    this.coopId = data;
    this.tipsMsg1 = tipsMsg1;
    this.tipsMsg2 = tipsMsg2;
  }
  // 隐藏删除框
  hideDelModal() {
    this.delModal = false;
  }
  // 确认删除
  confirmDel() {
    this.btnLoading = true;
    if (this.confirmDelType === "del") {
      //删除
      this.quiltDepartmentBindService
        .simplePost("rmvData", "clothesDept", [this.coopId.id])
        .subscribe((data) => {
          this.btnLoading = false;
          this.delModal = false;
          if (data.status == 200) {
            if (
              this.listOfData.length == 1 &&
              this.pageIndex == Math.ceil(this.listLength / this.pageSize)
            ) {
              this.listLength--;
              if (this.listLength === 0) {
                this.pageIndex = 1;
              } else {
                this.pageIndex = Math.ceil(this.listLength / this.pageSize);
              }
            }
            this.showPromptModal(this.tipsMsg2, true, "");
          } else {
            this.showPromptModal(this.tipsMsg2, false, data.msg);
          }
        });
    }
  }
}


