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';
import { Subject } from 'rxjs';
import { debounceTime } from 'rxjs/operators';
@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 = ""; //模态框名称

  changeInpSubject = new Subject(); //防抖

  ngOnInit() {
    //防抖
    this.changeInpSubject.pipe(debounceTime(500)).subscribe((v) => {
      if(v[0] === 'repairDept'){
        this.getRepairDeptList(v[1]);
      }else if(v[0] === 'category'){
        this.getCategoryList(v[1]);
      }else if(v[0] === 'priority'){
        this.getPriorityList(v[1]);
      }else if(v[0] === 'group'){
        this.getGroupList(v[1]);
      }else if(v[0] === 'user'){
        this.getUserList(v[1]);
      }
    });
    this.currentHospital = this.tool.getCurrentHospital();
    this.coopBtns = this.tool.initCoopBtns(this.route);
    this.initForm();
    this.getList(1);
  }

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

  // 边输边搜节流阀
  isLoading = false;
  changeInp(type, e) {
    this.isLoading = true;
    this.changeInpSubject.next([type, e]);
  }

  // 获取报修科室
  repairDeptList: any = [];
  getRepairDeptList(keyWord) {
    let postData:any = {
      department: {
        searchType: 1,// 简单查询
        flag: 1,
        keyWord,
        cascadeHosId: this.currentHospital.id,
      },
      idx: 0,
      sum: 20,
    };
    this.mainService
      .getFetchDataList("data", "department", postData)
      .subscribe((data) => {
        this.repairDeptList = data.list;
        this.isLoading = false;
      });
  }

  // 获取维修组
  groupList: any = [];
  getGroupList(keyWord) {
    let postData:any = {
      group2: {
        type: 3,
        groupName: keyWord,
        hospitals: this.currentHospital.id,
      },
      idx: 0,
      sum: 20,
    };
    this.mainService
      .getFetchDataList("simple/data", "group2", postData)
      .subscribe((data) => {
        this.groupList = data.list;
        this.isLoading = false;
      });
  }

  // 获取维修人
  userList: any = [];
  getUserList(keyWord) {
    let postData:any = {
      user: {
        simpleQuery: true,// 简单查询
        name: keyWord,
        groupdata: {
          id: this.validateForm.value.groupId,
        },
        roleCodes: "first-line support",
        engineer: 1,
      },
      idx: 0,
      sum: 20,
    };
    this.mainService
      .getFetchDataList("simple/data", "user", postData)
      .subscribe((data) => {
        this.userList = data.list;
        this.isLoading = false;
      });
  }

  // 获取故障现象
  categoryList: any = [];
  getCategoryList(keyWord) {
    let dutyIds;
    let { hospital, type } = this.tool.getHospitalOrDuty();
    if(type === 'duty'){
      // 是责任部门
      dutyIds = hospital.id.toString();
    }else{
      this.categoryList = [];
      this.isLoading = false;
      return;
    }
    let postData:any = {
      category: {
        category: keyWord,
        selectType: 'mutlQuery',
        hierarchy: 3,//只差有三级的故障现象列表
        dutyIds,
      },
    };
    this.mainService
      .incidentPost("listIncidentCategory", postData)
      .subscribe((data) => {
        this.categoryList = data.data;
        this.isLoading = false;
      });
  }

  // 获取优先级
  priorityList: any = [];
  getPriorityList(keyWord) {
    let postData:any = {
      priority: {},
      idx: 0,
      sum: 9999,
    };
    this.mainService
      .getFetchDataList("data", "priority", postData)
      .subscribe((data) => {
        this.priorityList = data.list;
        this.isLoading = false;
      });
  }

  // 表格数据
  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],
      repairDeptId: [null],
      categoryId: [null],
      priorityId: [null],
      userGroup: [null],
      groupId: [null],
      userId: [null],
    });
  }

  // 新增/编辑表单提交
  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,
        repairDeptId: this.validateForm.value.repairDeptId || undefined,
        categoryId: this.validateForm.value.categoryId || undefined,
        priorityId: this.validateForm.value.priorityId || undefined,
        userGroup: this.validateForm.value.userGroup || undefined,
        groupId: this.validateForm.value.groupId || undefined,
        userId: this.validateForm.value.userId || undefined,
        hosId: this.currentHospital.id,
      };
    } else {
      //编辑
      data = {
        ...this.coopData,
        ...{
          name: this.validateForm.value.name,
          showOrder: this.validateForm.value.showOrder,
          createOrder: this.validateForm.value.createOrder,
          repairDeptId: this.validateForm.value.repairDeptId || undefined,
          categoryId: this.validateForm.value.categoryId || undefined,
          priorityId: this.validateForm.value.priorityId || undefined,
          userGroup: this.validateForm.value.userGroup || undefined,
          groupId: this.validateForm.value.groupId || undefined,
          userId: this.validateForm.value.userId || undefined,
        }
      };
    }
    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);
    if(data.showOrder == 1){
      this.validateForm.controls.createOrder.setValue(data.createOrder);

      data.repairDeptDTO && (this.repairDeptList = [data.repairDeptDTO]);
      this.validateForm.controls.repairDeptId.setValue(data.repairDeptId);
      this.requiredChange('repairDeptId', data.createOrder == 1);

      data.categoryDTO && (this.categoryList = [data.categoryDTO]);
      this.validateForm.controls.categoryId.setValue(data.categoryId);
      this.requiredChange('categoryId', data.createOrder == 1);

      data.priorityDTO && (this.priorityList = [data.priorityDTO]);
      this.validateForm.controls.priorityId.setValue(data.priorityId);

      if(data.createOrder == 1){
        this.validateForm.controls.userGroup.setValue(data.userGroup);

        data.groupDTO && (this.groupList = [data.groupDTO]);
        this.validateForm.controls.groupId.setValue(data.groupId);
        this.requiredChange('groupId', (data.userGroup == 1 || data.userGroup == 2 || data.userGroup == 3));

        data.userDTO && (this.userList = [data.userDTO]);
        this.validateForm.controls.userId.setValue(data.userId);
        this.requiredChange('userId', data.userGroup == 3);
      }
    }else{
      this.requiredChange('createOrder', false);
      this.validateForm.controls.createOrder.setValue(0);
    }
  }

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

  requiredChange(field, required: boolean): void {
    if (!required) {
      this.validateForm.get(field)!.clearValidators();
      this.validateForm.get(field)!.markAsPristine();
    } else {
      this.validateForm.get(field)!.setValidators(Validators.required);
      this.validateForm.get(field)!.markAsDirty();
    }
    this.validateForm.get(field)!.updateValueAndValidity();
  }

  changeShowOrder(value){
    this.requiredChange('createOrder', value == 1);
    this.validateForm.controls.createOrder.setValue(0);

    this.validateForm.controls.repairDeptId.setValue(null);
    this.repairDeptList = [];

    this.validateForm.controls.categoryId.setValue(null);
    this.categoryList = [];

    this.validateForm.controls.priorityId.setValue(null);
    this.priorityList = [];

    this.requiredChange('userGroup', false);
    this.validateForm.controls.userGroup.setValue(null);

    this.requiredChange('groupId', false);
    this.validateForm.controls.groupId.setValue(null);
    this.groupList = [];

    this.requiredChange('userId', false);
    this.validateForm.controls.userId.setValue(null);
    this.userList = [];
  }

  changeCreateOrder(value){
    this.requiredChange('repairDeptId', value == 1);

    this.requiredChange('categoryId', value == 1);

    this.requiredChange('userGroup', value == 1);
    this.validateForm.controls.userGroup.setValue(value == 1 ? 1 : null);

    this.requiredChange('groupId', (this.validateForm.value.userGroup == 1 || this.validateForm.value.userGroup == 2 || this.validateForm.value.userGroup == 3));
    this.validateForm.controls.groupId.setValue(null);
    this.groupList = [];

    this.requiredChange('userId', this.validateForm.value.userGroup == 3);
    this.validateForm.controls.userId.setValue(null);
    this.userList = [];
  }

  changeUserGroup(value){
    this.requiredChange('groupId', (value == 1 || value == 2 || value == 3));
    this.validateForm.controls.groupId.setValue(null);
    this.groupList = [];

    this.requiredChange('userId', value == 3);
    this.validateForm.controls.userId.setValue(null);
    this.userList = [];
  }

  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);
          }
        });
    }
  }
}
