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

import { MainService } from "../../services/main.service";
import { OverlayScrollbarsComponent } from "overlayscrollbars-ngx";
import { ToolService } from "../../services/tool.service";

@Component({
  selector: "app-data-dictionary",
  templateUrl: "./data-dictionary.component.html",
  styleUrls: ["./data-dictionary.component.less"],
})
export class DataDictionaryComponent implements OnInit {
  tableHeight;
  validateForm: FormGroup;
  allDataList: any[] = []; //数据字典下的数据列表
  mapOfCheckedId: { [key: string]: boolean } = {};
  checkedDictionary: any = {}; //选中
  dictionaryList: Array<any> = []; //数据字典信息
  parentList: Array<any> = []; //父级数据字典信息
  hosId: any; //当前选择的院区id
  promptContent: string; //操作提示框提示信息
  ifSuccess: boolean; //操作成功/失败
  promptInfo: string; //操作结果提示信息
  promptModalShow: boolean; //是否展示提示框
  btnLoading: boolean = false; //确认按钮loading状态
  coopBtns: any = {}; // 初始化增删改按钮
  dictionaryLoading = false; //loading
  positionY = 0; //记录Y轴滚动距离
  selectedDictionary = []; //选中的
  add: boolean = true; //新增的标识,true:新增;false:编辑
  dictionaryModal: boolean = false; //模态框是否展示
  dataEdit; //正在编辑的
  delModal: boolean = false; //删除,模态框是否显示
  delDictionaryModal: boolean = false; //删除,模态框是否显示
  isDelSingle: boolean = false; //是否单个删除
  isAllDisplayDataChecked = false; //当前页是否全选

  constructor(
    private fb: FormBuilder,
    private route: ActivatedRoute,
    private mainService: MainService,
    private tool: ToolService
  ) {}

  @ViewChild("osComponentRef1", {
    read: OverlayScrollbarsComponent,
    static: true,
  })
  osComponentRef1: OverlayScrollbarsComponent;

  ngOnInit() {
    this.coopBtns = this.tool.initCoopBtns(this.route);
    this.hosId = this.tool.getCurrentHospital().id;
    this.getDictionaryList();
    this.tableHeight = document.body.clientHeight - 312;
  }

  // 数据字典列表
  getDictionaryList() {
    this.dictionaryList = [
      {
        id: -1,
        dictionaryName: '被服种类',
        key: 'clothes_type',
        type: 'dictionaryTree',
      },
      {
        id: -2,
        dictionaryName: '统计分类',
        key: 'statistics_date_type',
        type: 'dictionary',
      },
      {
        id: -3,
        dictionaryName: '大扫描提示',
        key: 'bigScan_special_msg',
        type: 'dictionary',
      },
    ];
    if (Object.keys(this.checkedDictionary).length) {
      this.dictionaryList.forEach((item) => {
        if (item.id == this.checkedDictionary.id) {
          this.checkDictionary(item);
        }
      });
    } else {
      this.checkDictionary(this.dictionaryList[0]);
    }
  }

  searchDto:any = {
    parent: null,
  }

  // 获取父级分类
  getParentList() {
    let postData = {
      idx: 0,
      sum: 9999,
      dictionaryTree: {
        hosId: this.hosId,
        level: 1,
        key: 'clothes_type',
        deleted: 0,
      },
    };
    this.mainService
      .getFetchDataList("simple/data", "dictionaryTree", postData)
      .subscribe((result) => {
        if(result.status == 200){
          this.parentList = result.list || [];
        }
      });
  }

  // 获取选中数据字典列表
  getAll() {
    this.dictionaryLoading = true;
    let postData = {};
    if(this.checkedDictionary.type === 'dictionary'){
      postData = {
        idx: 0,
        sum: 9999,
        dictionary: {
          key: this.checkedDictionary.key,
          deleted: 0,
        },
      }
    }else if(this.checkedDictionary.type === 'dictionaryTree'){
      postData = {
        idx: 0,
        sum: 9999,
        dictionaryTree: {
          hosId: this.hosId,
          level: 2,
          parent: this.searchDto.parent || undefined,
          key: this.checkedDictionary.key,
          deleted: 0,
        },
      }
    }
    this.mainService
      .getFetchDataList("simple/data", this.checkedDictionary.type, postData)
      .subscribe((result) => {
        this.dictionaryLoading = false;
        if (result.status == 200) {
          this.allDataList = result.list;
          this.refreshStatus();
        }
      });
  }

  // 选中数据字典
  checkDictionary(data) {
    this.positionY = this.osComponentRef1.osInstance() ? this.osComponentRef1.osInstance().scroll().position.y : 0; //内容滚动的距离
    this.checkedDictionary = data ? data : {};
    this.mapOfCheckedId = {};
    this.getAll();
    this.checkedDictionary.type === 'dictionaryTree' && this.getParentList();
  }

  selectedUser(data) {
    this.mapOfCheckedId[data.id] = !this.mapOfCheckedId[data.id];
    this.refreshStatus();
  }
  // 选中列表中
  refreshStatus(): void {
    let arr = [];
    if (this.allDataList.length) {
      this.isAllDisplayDataChecked = this.allDataList.every(
        (item) => this.mapOfCheckedId[item.id]
      );
    } else {
      this.isAllDisplayDataChecked = false;
    }

    for (var m in this.mapOfCheckedId) {
      if (this.mapOfCheckedId[m]) {
        arr.push({ id: m });
      }
    }
    this.selectedDictionary = arr;
  }

  // 新增/编辑模态框
  showModal(e, type, data?) {
    e.stopPropagation();
    this.dictionaryModal = true;
    this.add = type == "add";
    if (type == "edit") {
      this.initForm();
      this.dataEdit = data;
      if(this.checkedDictionary.type === 'dictionaryTree'){
        this.validateForm.controls.key.setValue(data.key);
        this.validateForm.controls.parent.setValue(data.parent);
        this.validateForm.controls.name.setValue(data.name);
        this.validateForm.controls.value.setValue(data.value);
        this.validateForm.controls.orders.setValue(data.orders);
        this.validateForm.controls.extra3.setValue(data.extra3);
        this.validateForm.controls.desc.setValue(data.desc);
      } else if(this.checkedDictionary.type === 'dictionary'){
        this.validateForm.controls.key.setValue(data.key);
        this.validateForm.controls.name.setValue(data.name);
        this.validateForm.controls.value.setValue(data.value);
        this.validateForm.controls.orders.setValue(data.orders);
        this.validateForm.controls.desc.setValue(data.desc);
      }

    } else {
      this.initForm();
    }
  }

  // 隐藏模态框
  hideModal() {
    this.dictionaryModal = false;
  }

  // 初始化新增form表单dictionary
  initForm() {
    if(this.checkedDictionary.type === 'dictionaryTree'){
      this.validateForm = this.fb.group({
        key: [this.checkedDictionary.key, [Validators.required]],
        parent: [null, [Validators.required]],
        name: [null, [Validators.required]],
        value: [null, [Validators.required]],
        orders: [0, [Validators.required]],
        extra3: [0, [Validators.required]],
        desc: [null, [Validators.required]],
      });
    } else if(this.checkedDictionary.type === 'dictionary'){
      this.validateForm = this.fb.group({
        key: [this.checkedDictionary.key, [Validators.required]],
        name: [null, [Validators.required]],
        value: [null, [Validators.required]],
        orders: [0, [Validators.required]],
        desc: [null, [Validators.required]],
      });
    }

  }

  // 数据字典修改name,value自动变化,且value禁止修改
  changeValue(e){
    if(this.checkedDictionary.type === 'dictionary'){
      this.validateForm.controls.value.setValue(e.target.value);
    }
  }

  // 新增/编辑提交
  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 postData;

    if(this.checkedDictionary.type === 'dictionaryTree'){
      if (this.add) {
        postData = {
          hosId: this.hosId,
          key: this.validateForm.value.key,
          parent: this.validateForm.value.parent,
          name: this.validateForm.value.name,
          value: this.validateForm.value.value,
          orders: this.validateForm.value.orders,
          extra3: this.validateForm.value.extra3,
          desc: this.validateForm.value.desc,
          level: 2,
          system: 0,
        };
      } else {
        postData = {
          hosId: this.hosId,
          key: this.validateForm.value.key,
          parent: this.validateForm.value.parent,
          name: this.validateForm.value.name,
          value: this.validateForm.value.value,
          orders: this.validateForm.value.orders,
          extra3: this.validateForm.value.extra3,
          desc: this.validateForm.value.desc,
          id: this.dataEdit.id,
          level: 2,
          system: 0,
        };
      }
    }else if(this.checkedDictionary.type === 'dictionary'){
      if (this.add) {
        postData = {
          key: this.validateForm.value.key,
          name: this.validateForm.value.name,
          value: this.validateForm.value.value,
          orders: this.validateForm.value.orders,
          desc: this.validateForm.value.desc,
          system: 0,
        };
      } else {
        postData = {
          key: this.validateForm.value.key,
          name: this.validateForm.value.name,
          value: this.validateForm.value.value,
          orders: this.validateForm.value.orders,
          desc: this.validateForm.value.desc,
          system: 0,
          id: this.dataEdit.id,
        };
      }
    }
    this.addHandler(postData);
  }

  //新增/编辑
  addHandler(postData) {
    this.mainService
      .simplePost("addData", this.checkedDictionary.type, postData)
      .subscribe((result) => {
        this.hideModal();
        this.btnLoading = false;
        if (result["status"] == 200) {
          if(this.checkedDictionary.type === 'dictionary'){
            this.mainService.clearDictionary();
          }
          this.showPromptModal(this.add ? "新增" : "编辑", true, "");
        } else {
          this.showPromptModal(
            this.add ? "新增" : "编辑",
            false,
            result["msg"]
          );
        }
      });
  }

  /**
   * 删除
   * @param e 事件对象
   * @param data 有值就是单个删除,无值就是批量删除
   */
  showDelDictionaryModal(e, data?) {
    if (data) {
      this.isDelSingle = true;
      this.dataEdit = data;
    } else {
      this.isDelSingle = false;
    }
    this.delDictionaryModal = true;
    e.stopPropagation();
  }
  hideDelDictionaryModal() {
    this.delDictionaryModal = false;
  }
  // 确认删除
  confirmDictionaryDel() {
    this.btnLoading = true;
    let selectedDictionary = this.selectedDictionary.map((item) => item.id);
    let postData = this.isDelSingle ? [this.dataEdit.id] : selectedDictionary;
    this.mainService.simplePost("rmvData", this.checkedDictionary.type, postData).subscribe((result) => {
      this.hideDelDictionaryModal();
      this.btnLoading = false;
      if (result.status == 200) {
        if(this.checkedDictionary.type === 'dictionary'){
          this.mainService.clearDictionary();
        }
        this.showPromptModal("删除", true, "");
      } else {
        this.showPromptModal("删除", false, result.msg);
      }
    });
  }
  // 全选
  checkAll(value: boolean): void {
    console.log(this.allDataList);
    this.allDataList.forEach((item) => {
      this.mapOfCheckedId[item.id] = value;
    });
    this.refreshStatus();
  }

  // 展示信息提示框(con:提示信息,success:操作是否成功,promptInfo:操作结果提示信息)(con:提示信息,success:操作是否成功,promptInfo:操作结果提示信息)
  showPromptModal(con, success, promptInfo) {
    this.promptModalShow = false;
    this.promptContent = con;
    this.ifSuccess = success;
    this.promptInfo = promptInfo;
    this.osComponentRef1.osInstance().scroll({ x: 0, y: this.positionY });
    if (success) {
      setTimeout(() => {
        this.promptModalShow = true;
        this.getDictionaryList();
      }, 100);
    } else {
      setTimeout(() => {
        this.promptModalShow = true;
      }, 100);
    }
  }
}