import { Component, OnInit, ViewChild } from "@angular/core";
import { ActivatedRoute, Router } 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";
import { forkJoin, Subject } from "rxjs";
import { debounceTime } from "rxjs/operators";
import { NzMessageService } from "ng-zorro-antd";
import { isThisISOWeek } from 'date-fns';

@Component({
  selector: "app-tab-custom",
  templateUrl: "./tab-custom.component.html",
  styleUrls: ["./tab-custom.component.less"],
})
export class TabCustomComponent implements OnInit {
  @ViewChild("osComponentRef1", {
    read: OverlayScrollbarsComponent,
    static: false,
  })
  osComponentRef1: OverlayScrollbarsComponent;
  constructor(
    private message: NzMessageService,
    private fb: FormBuilder,
    private route: ActivatedRoute,
    private router: Router,
    private mainService: MainService,
    private tool: ToolService
  ) {}

  listOfData: any[] = []; //表格数据

  modal: boolean = false; //新增/编辑模态框
  add: boolean; //true:新增；false:编辑
  validateForm: FormGroup; //新增/编辑表单
  coopId: number; //表格中执行操作的id
  department: any; //所属科室
  num; //工号
  name; //姓名
  userType: any; //用户类型
  hosId: any; //院区（搜索）
  userGroup; //所属组
  userGroup1; //所属组(搜索)
  userTypes: Array<any>; //所有用户类型
  alldepart: any = []; //所有所属科室
  alldepart1: any = []; //所有所属科室(搜索)
  hospitals1: any = []; //院区列表(搜索)
  otherTasktypeList: Array<any>; //所有其他临床服务任务类型
  allUserRole: Array<any>; //所有角色
  pageIndex: number = 1; //页码
  listLength: number = 10; //总条数
  pageSize: number = 10; //每页条数

  promptContent: string; //操作提示框提示信息
  ifSuccess: boolean; //操作成功/失败
  promptInfo: string; //操作结果提示信息
  promptModalShow: boolean; //操作提示框是否展示

  btnLoading: boolean = false; //提交按钮loading状态
  wxRequired = false; //新增或编辑用户的时候，微信号是否必填
  changeInpSubject = new Subject(); //防抖

  ngOnInit() {
    //防抖
    this.changeInpSubject.pipe(debounceTime(500)).subscribe((v) => {
      this.getOtherTasktype(v[0]);
    });
    this.coopBtns = this.tool.initCoopBtns(this.route);
    this.initForm();
    this.hosId = this.tool.getCurrentHospital().id;
    this.getList(true);
  }

  // 初始化增删改按钮
  coopBtns: any = {};
  // 搜索
  search() {
    this.getList(true);
  }
  // 表格数据
  loading1 = false;
  getList(isResetPageIndex = false) {
    isResetPageIndex && (this.pageIndex = 1);
    let data = {
      idx: this.pageIndex - 1,
      sum: this.pageSize,
      tabPermission: {
        hosId: this.hosId,
      },
    };
    this.loading1 = true;
    this.mainService
      .getFetchDataList("simple/data", "tabPermission", data)
      .subscribe((data) => {
        this.loading1 = false;
        data.list = data.list || [];
        data.list.forEach(v => {
          v.taskNames = v.tabTypeList.map(v=>v.taskTypeDTO.taskName).toString()
        })
        this.listOfData = data.list;
        this.listLength = data.totalNum;
      });
  }

  // 获取任务类型列表-其他临床服务
  getOtherTasktype(keywords = '') {
    let hid = this.tool.getCurrentHospital().id;
    let postData = {
      taskType: {
        cascadeHosId: hid,
        taskName: keywords,
        simpleQuery: true,
        associationType: {
          key: 'association_types',
          value: 'other',
        }
      },
      idx: 0,
      sum: 9999,
    };
    this.isLoading = true;
    this.mainService.getFetchDataList("configuration", "taskType", postData).subscribe((res) => {
      this.isLoading = false;
      this.otherTasktypeList = res.list || [];
    });
  }

  // 新增弹框
  showModal() {
    this.add = true;
    this.modal = true;
    this.tabTypeListDisabled = false;
    this.initForm();
  }
  hideModal() {
    this.modal = false;
    this.initForm();
  }

  // 初始化新增form表单
  initForm() {
    if (this.add) {
      this.otherTasktypeList = [];
    }
    this.validateForm = this.fb.group({
      title: ['', [Validators.required]],
      orders: [0, [Validators.required]],
      tabTypeList: [[]],
    });
  }
  // 表单提交
  submitForm(): void {
    for (const i in this.validateForm.controls) {
      this.validateForm.controls[i].markAsDirty({ onlySelf: true });
      this.validateForm.controls[i].updateValueAndValidity();
    }
    if (this.validateForm.invalid) return;
    this.btnLoading = true;
    let tabTypeList = [];
    this.validateForm.value.tabTypeList.forEach(v => {
      this.otherTasktypeList.forEach(vv => {
        if(v == vv.id){
          tabTypeList.push({
            taskTypeId: vv.id,
            hosId: vv.hosId ? vv.hosId.id : undefined,
            typeParentHosId: vv.hosId.parent ? vv.hosId.parent.id : undefined,
          })
        }
      })
    })
    let data = {
      title: this.validateForm.value.title,
      orders: this.validateForm.value.orders,
      hosId: this.hosId,
      deleteFlag: 0,
      tabTypeList
    };
    if (!this.add) {
      data = {...this.coopData, ...data};
    }
    console.log(data);
    this.mainService
      .simplePost("addData", "tabPermission", data)
      .subscribe((data) => {
        this.btnLoading = false;
        this.hideModal();
        this.initForm();
        if (data.status == 200) {
          this.showPromptModal(this.add ? "新增" : "编辑", true, "");
        } else {
          this.showPromptModal(this.add ? "新增" : "编辑", false, data.msg);
        }
      });
  }

  // 编辑
  maskFlag: any = false;
  coopData = {};
  tabTypeListDisabled:boolean = false;
  edit(data) {
    this.tabTypeListDisabled = Boolean(data.system);
    this.validateForm.controls.title.setValue(data.title);
    this.validateForm.controls.orders.setValue(data.orders);
    this.validateForm.controls.tabTypeList.setValue(Array.isArray(data.tabTypeList) ? data.tabTypeList.map(v => +v.taskTypeId) : []);
    this.modal = true;
    this.add = false;
    this.coopId = data.id;
    this.coopData = data;
    this.getOtherTasktype();
  }

  // 删除
  delModal: boolean = false; //删除模态框
  del(data) {
    this.coopId = data.id;
    this.delModal = true;
  }
  // 确认删除
  confirmDel() {
    this.btnLoading = true;
    this.mainService
      .simplePost(
        "rmvData",
        "tabPermission",
        [this.coopId]
      )
      .subscribe((data) => {
        this.btnLoading = false;
        this.hideDelModal();
        if (data["status"] == 200) {
          if (
            this.listOfData.length == 1 &&
            this.pageIndex == Math.ceil(this.listLength / this.pageSize)
          ) {
            this.listLength--;
            this.pageIndex = Math.ceil(this.listLength / this.pageSize);
          }
          this.showPromptModal("删除", true, "");
        } else {
          this.showPromptModal("删除", false, data["msg"]);
        }
      });
  }

  // 关闭删除模态框
  hideDelModal() {
    this.delModal = false;
  }

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

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

  // 打开任务类型
  openOtherTasktype(e){
    if(e){
      this.getOtherTasktype();
    }
  }
}


