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";
import { Subject } from "rxjs";
import { debounceTime } from "rxjs/operators";
import { NzMessageService } from "ng-zorro-antd";
@Component({
  selector: "app-keep-order-config",
  templateUrl: "./keep-order-config.component.html",
  styleUrls: ["./keep-order-config.component.less"],
})
export class KeepOrderConfigComponent implements OnInit {
  @ViewChild("osComponentRef1", {
    read: OverlayScrollbarsComponent,
    static: false,
  })
  osComponentRef1: OverlayScrollbarsComponent;
  constructor(
    private message: NzMessageService,
    private fb: FormBuilder,
    private mainService: MainService,
    private route: ActivatedRoute,
    private tool: ToolService
  ) {}

  userInfo: any = JSON.parse(localStorage.getItem("user")) || {}; //登录用户信息

  searchCriteria = {};
  taskTypeList = []; //轮巡类型
  orderRangeList:any[] =  [
    { id: 4, name: '待到达' },
    { id: 5, name: '待送达' },
  ];
  hosId; //当前院区id
  listOfData: any[] = []; //表格数据
  pageIndex: number = 1; //表格当前页码
  pageSize: number = 10; //表格每页展示条数
  listLength: number = 10; //表格总数据量
  modal: boolean = false; //新增/编辑模态框
  add: boolean; //true:新增；false:编辑
  validateForm: FormGroup; //新增/编辑表单
  coopId: number; //当前操作列id

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

  promptContent: string; //操作提示框提示信息
  ifSuccess: boolean; //操作成功/失败
  promptInfo: string; //操作结果提示信息
  promptModalShow: boolean; //操作提示框是否展示
  changeInpTasktypeSubject = new Subject();
  ngOnInit() {
    this.hosId = this.tool.getCurrentHospital().id;
    this.changeInpTasktypeSubject.pipe(debounceTime(500)).subscribe((v: any) => {
      this.getTasktypeByValues(v);
    });
    this.coopBtns = this.tool.initCoopBtns(this.route);
    this.getList(1);
    this.getKeepOrderDeptTypeList();
    this.getKeepOrderGetorderTypeList();
  }
  // 重置
  reset() {
    this.searchCriteria = {};
    this.getList(1);
  }

  changeFormTasktype(flag) {
    if (flag) {
      this.changeInpTasktype();
    }
  }
  // 任务类型防抖搜索
  changeInpTasktype(taskName = "") {
    this.isLoading = true;
    this.changeInpTasktypeSubject.next(taskName);
  }
  isLoading = false;

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

  //获取起点科室|终点科室字典
  keepOrderDeptTypeList:any[] = [];
  getKeepOrderDeptTypeList() {
    this.isLoading = true;
    this.mainService.getDictionary('list', 'keep_order_dept_type').subscribe((data) => {
      this.isLoading = false;
      this.keepOrderDeptTypeList = data || [];
    });
  }
  //获取抢接单字典
  keepOrderGetorderTypeList:any[] = [];
  getKeepOrderGetorderTypeList() {
    this.isLoading = true;
    this.mainService.getDictionary('list', 'keep_order_getorder_type').subscribe((data) => {
      this.isLoading = false;
      this.keepOrderGetorderTypeList = data || [];
    });
  }

  // 表格数据
  loading1 = false;
  getList(type) {
    if (type == 1) {
      this.pageIndex = 1;
    }
    let data = {
      idx: this.pageIndex - 1,
      sum: this.pageSize,
      keepOrderConfig: {
        hosId: this.hosId,
      },
    };
    this.loading1 = true;
    this.mainService
      .getFetchDataList("simple/data", "keepOrderConfig", data)
      .subscribe((data) => {
        this.loading1 = false;
        if (data.status == 200) {
          this.listOfData = data.list;
          this.listLength = data.totalNum;
        }
      });
  }
  //获取任务类型
  taskNameing = "";
  getTasktypeByValues(taskName = "") {
    this.taskNameing = taskName;
    let postData = {
      idx: 0,
      sum: 10,
      taskType: {
        hosIds: this.hosId,
        assTypeValues: "other,ordinary",
        taskName,
        simpleQuery: true,
      },
    };
    this.mainService
      .getFetchDataList("configuration", "taskType", postData)
      .subscribe((result) => {
        if (result.status == 200 && this.taskNameing === postData.taskType.taskName) {
          this.isLoading = false;
          this.taskTypeList = result.list;
        }
      });
  }
  // 新增/编辑弹框
  addModal() {
    this.add = true; //新增
    this.modal = true;
    this.initForm();
  }
  //关闭新增/编辑弹框
  hideAddModal() {
    this.modal = false;
  }
  // 是否是必选
  requiredChange(required: boolean, formControlName: string): void {
    if (!required) {
      this.validateForm.get(formControlName)!.clearValidators();
      this.validateForm.get(formControlName)!.markAsPristine();
    } else {
      this.validateForm.get(formControlName)!.setValidators(Validators.required);
      this.validateForm.get(formControlName)!.markAsDirty();
    }
    this.validateForm.get(formControlName)!.updateValueAndValidity();
  }
  // 初始化新增form表单
  initForm() {
    this.validateForm = this.fb.group({
      startTaskTypeId: [null, [Validators.required]],
      createTaskTypeId: [null, [Validators.required]],
      startDept: [null, [Validators.required]],
      endDept: [null, [Validators.required]],
      getOrderType: [null, [Validators.required]],
      getOrderRange: [null, [Validators.required]],
      copyRemark: [0, [Validators.required]],
      active: [0, [Validators.required]],
    });
  }

  // 选择抢接单
  changeGetOrderType(e){
    this.validateForm.controls.getOrderRange.setValue(null);
    if(e === '1'){
      this.requiredChange(true, 'getOrderRange');
    }else{
      this.requiredChange(false, 'getOrderRange');
    }
  }

  // 新增/编辑表单提交
  submitForm(): void {
    this.btnLoading = true;
    for (const i in this.validateForm.controls) {
      this.validateForm.controls[i].markAsDirty();
      this.validateForm.controls[i].updateValueAndValidity();
    }
    if (this.validateForm.invalid) {
      this.btnLoading = false;
      return;
    }
    let postData: any = {};

    if (this.add) {
      //增加
      postData = {
        hosId: this.hosId,
        startTaskTypeId: this.validateForm.value.startTaskTypeId || undefined,
        createTaskTypeId: this.validateForm.value.createTaskTypeId || undefined,
        startDept: this.validateForm.value.startDept ? { id: this.validateForm.value.startDept } : undefined,
        endDept: this.validateForm.value.endDept ? { id: this.validateForm.value.endDept } : undefined,
        getOrderType: this.validateForm.value.getOrderType ? this.keepOrderGetorderTypeList.find(v => v.value === this.validateForm.value.getOrderType) : undefined,
        getOrderRange: this.validateForm.value.getOrderRange || undefined,
        copyRemark: this.validateForm.value.copyRemark,
        active: this.validateForm.value.active,
      };
    } else {
      //编辑
      postData = {
        ...this.coopData,
        startTaskTypeId: this.validateForm.value.startTaskTypeId || undefined,
        createTaskTypeId: this.validateForm.value.createTaskTypeId || undefined,
        startDept: this.validateForm.value.startDept ? { id: this.validateForm.value.startDept } : undefined,
        endDept: this.validateForm.value.endDept ? { id: this.validateForm.value.endDept } : undefined,
        getOrderType: this.validateForm.value.getOrderType ? this.keepOrderGetorderTypeList.find(v => v.value === this.validateForm.value.getOrderType) : undefined,
        getOrderRange: this.validateForm.value.getOrderRange || undefined,
        copyRemark: this.validateForm.value.copyRemark,
        active: this.validateForm.value.active,
      };
    }
    console.log(postData);
    this.mainService
      .simplePost("addData", "keepOrderConfig", postData)
      .subscribe((data) => {
        this.btnLoading = false;
        this.hideAddModal();
        if (data.status == 200) {
          this.listLength++;
          this.showPromptModal(this.add ? "新增" : "修改", true, "");
        } else {
          this.showPromptModal(this.add ? "新增" : "修改", false, data.msg);
        }
      });
  }

  // 编辑
  executionTimeTemporaryStorage; //暂存执行时间
  maskFlag: any = false;
  coopData: any = {};
  edit(data) {
    this.modal = true;
    this.add = false;
    this.coopId = data.id;
    this.coopData = data;
    this.initForm();
    data.getOrderType && this.changeGetOrderType(data.getOrderType.value);
    this.taskTypeList = [];
    data.startTaskTypeDTO && (this.taskTypeList.push(data.startTaskTypeDTO));
    data.createTaskTypeDTO && (this.taskTypeList.push(data.createTaskTypeDTO));
    data.startTaskTypeId && this.validateForm.controls.startTaskTypeId.setValue(data.startTaskTypeId);
    data.createTaskTypeId && this.validateForm.controls.createTaskTypeId.setValue(data.createTaskTypeId);
    data.startDept && this.validateForm.controls.startDept.setValue(data.startDept.id);
    data.endDept && this.validateForm.controls.endDept.setValue(data.endDept.id);
    data.getOrderType && this.validateForm.controls.getOrderType.setValue(data.getOrderType.value);
    data.getOrderRange && this.validateForm.controls.getOrderRange.setValue(data.getOrderRange);
    data.copyRemark && this.validateForm.controls.copyRemark.setValue(data.copyRemark);
    data.active && this.validateForm.controls.active.setValue(data.active);
  }

  // 展示信息提示框（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; //确认的类型（启用/停用，删除）
  confirmDelIsSwitch: boolean; //启用/停用
  showDelModal(
    id: number,
    tipsMsg1: string,
    tipsMsg2: string,
    type: string,
    isSwitch?: boolean
  ) {
    this.confirmDelIsSwitch = isSwitch;
    this.confirmDelType = type;
    this.delModal = true;
    this.coopId = id;
    this.tipsMsg1 = tipsMsg1;
    this.tipsMsg2 = tipsMsg2;
  }
  // 隐藏删除框
  hideDelModal() {
    this.delModal = false;
  }
  // 确认删除
  confirmDel() {
    this.btnLoading = true;
    if (this.confirmDelType === "del") {
      //删除
      this.mainService.simplePost('rmvData', 'keepOrderConfig', [this.coopId]).subscribe((data) => {
        this.btnLoading = false;
        this.delModal = false;
        if (data.status == 200) {
          console.log(this.pageIndex, this.listLength, this.pageSize, "lmm");
          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);
        }
      });
    }
  }
}
