import { Component, EventEmitter, Input, OnInit, Output } from "@angular/core";
import { FormBuilder, FormGroup, Validators } from "@angular/forms";
import { NzMessageService } from "ng-zorro-antd";
import { MainService } from "src/app/services/main.service";
import { ToolService } from "src/app/services/tool.service";

@Component({
  selector: "app-batch-orders",
  templateUrl: "./batch-orders.component.html",
  styleUrls: ["./batch-orders.component.less"],
})
export class BatchOrdersComponent implements OnInit {
  @Input() selectedBatchOrder = null;
  @Output() close = new EventEmitter();
  hosId; //当前院区id
  // 起点科室是默认发起科室，终点科室是固定科室
  // 起点科室是固定科室，终点科室是默认发起科室
  // 起点科室是默认发起科室，终点科室是默认发起科室
  // 其他
  type = 0;
  modal = false; //新增的弹窗
  validateForm: FormGroup; //新增
  initiatingDepartments = []; //发起科室列表
  startDepartments = []; //起点科室列表
  startDepartmentsDisabled = false; //是否禁用起点科室
  endDepartments = []; //终点科室列表
  endDepartmentsDisabled = false; //是否禁用终点科室
  isLoading = false; //科室下拉框搜索
  keyword = ""; //当前输入的关键词
  taskType = null; //当前任务类型
  startCarryingCourses = null; //当前起点科室运输过程
  endCarryingCourses = null; //当前终点科室运输过程
  saveLoading = false; //保存的loading
  constructor(
    private fb: FormBuilder,
    private mainService: MainService,
    private tool: ToolService,
    private message: NzMessageService
  ) {}
  // 初始化表单
  initForm() {
    this.validateForm = this.fb.group({
      initiatingDepartment: [null, [Validators.required]],
      startDepartment: [null, [Validators.required]],
      endDepartment: [null, [Validators.required]],
    });
  }
  //表格整行选中
  selectedListData(id) {
    this.mapOfCheckedId[id] = !this.mapOfCheckedId[id];
    this.refreshStatus();
  }
  // 关闭批量建单设置弹窗
  closeHandler() {
    this.close.emit("false");
  }
  //新增-打开
  addModal() {
    this.modal = true;
    this.initForm();
  }
  // 新增-关闭
  hideModal() {
    this.modal = false;
  }
  //获取科室列表
  /**
   *
   * @param type 科室类型id
   * @returns
   */
  getDeptList(obj: { e?: string; typeId?: string } = {}) {
    let postData: any = {
      department: { hospital: { id: this.hosId } },
      idx: 0,
      sum: 10,
    };
    if (obj.e) {
      postData.department.dept = obj.e;
    }
    if (obj.typeId) {
      postData.department.type = { id: obj.typeId };
    }
    this.isLoading = true;
    return this.mainService.getFetchDataList("data", "department", postData);
  }
  //打开发起科室下拉框
  changeFormDept(flag) {
    if (flag) {
      // 发起科室列表
      this.getDeptList().subscribe((result) => {
        this.isLoading = false;
        if (result.status == 200) {
          result.list.forEach((item) => {
            item._uid = item.id + "__" + item.dept;
          });
          this.initiatingDepartments = result.list;
        }
      });
    }
  }
  /**
   * 选择科室
   * @param e 选中的科室uid
   * @param type 科室类型(initiating,start,end)
   */
  selectedDeptHandler(e, type) {
    let arr = e.split("__");
    let o = { id: arr[0], dept: arr[1], _uid: arr[0] + "__" + arr[1] };
    if (this.type === 1 && type === "initiating") {
      this.startDepartments = [o];
      this.validateForm.controls.startDepartment.setValue(e);
      this.endDepartments = this.endCarryingCourses.departmentDTOS;
      this.validateForm.controls.endDepartment.setValue(
        this.endDepartments[0]._uid
      );
    } else if (this.type === 2 && type === "initiating") {
      this.endDepartments = [o];
      this.validateForm.controls.endDepartment.setValue(e);
      this.startDepartments = this.startCarryingCourses.departmentDTOS;
      this.validateForm.controls.startDepartment.setValue(
        this.startDepartments[0]._uid
      );
    } else if (this.type === 3 && type === "initiating") {
      this.endDepartments = [o];
      this.validateForm.controls.endDepartment.setValue(e);
      this.startDepartments = [o];
      this.validateForm.controls.startDepartment.setValue(e);
    }
  }
  //搜索科室
  changeInp(e, type) {
    this.keyword = e;
    if (
      (this.type === 1 ||
        this.type === 2 ||
        this.type === 3 ||
        this.type === 4) &&
      type === "initiating"
    ) {
      // 发起科室列表
      this.getDeptList({ e }).subscribe((result) => {
        if (result.status == 200 && this.keyword == e) {
          this.isLoading = false;
          result.list.forEach((item) => {
            item._uid = item.id + "__" + item.dept;
          });
          this.initiatingDepartments = result.list;
        } else if (result.status != 200) {
          this.isLoading = false;
        }
      });
    }
    if (this.type === 4 && type === "start") {
      // 起点科室列表
      this.getDeptList({ e }).subscribe((result) => {
        if (result.status == 200 && this.keyword == e) {
          this.isLoading = false;
          result.list.forEach((item) => {
            item._uid = item.id + "__" + item.dept;
          });
          this.startDepartments = result.list;
        } else if (result.status != 200) {
          this.isLoading = false;
        }
      });
    }
    if (this.type === 4 && type === "end") {
      // 终点科室列表
      this.getDeptList({ e }).subscribe((result) => {
        if (result.status == 200 && this.keyword == e) {
          this.isLoading = false;
          result.list.forEach((item) => {
            item._uid = item.id + "__" + item.dept;
          });
          this.endDepartments = result.list;
        } else if (result.status != 200) {
          this.isLoading = false;
        }
      });
    }
  }
  //保存
  submitForm() {
    console.log(this.validateForm.get("initiatingDepartment").value);
    console.log(this.validateForm.get("startDepartment").value);
    console.log(this.validateForm.get("endDepartment").value);
    for (const i in this.validateForm.controls) {
      this.validateForm.controls[i].markAsDirty();
      this.validateForm.controls[i].updateValueAndValidity();
    }
    if (this.validateForm.invalid) {
      return;
    }
    let postData = {
      hosId: this.hosId,
      orderPlanId: this.selectedBatchOrder.id,
      createDept: {
        id: this.validateForm.get("initiatingDepartment").value.split("__")[0],
      },
      startDept: {
        id: this.validateForm.get("startDepartment").value.split("__")[0],
      },
      endDept: {
        id: this.validateForm.get("endDepartment").value.split("__")[0],
      },
    };
    this.saveLoading = true;
    this.mainService
      .simplePost("addData", "orderPlanRule", postData)
      .subscribe((result) => {
        this.hideModal();
        this.saveLoading = false;
        if (result.status == 200) {
          this.getList(1);
        }
      });
  }
  //获取列表数据
  loading1 = false;
  listOfData: any[] = []; //表格数据
  pageIndex: number = 1; //表格当前页码
  pageSize: number = 10; //表格每页展示条数
  listLength: number = 10; //表格总数据量
  getList(type) {
    if (type == 1) {
      this.pageIndex = 1;
    }
    let data = {
      idx: this.pageIndex - 1,
      sum: this.pageSize,
      orderPlanRule: {
        hosId: this.hosId,
        orderPlanId: this.selectedBatchOrder.id,
      },
    };
    this.mapOfCheckedId = {};
    this.checkedDepIds = [];
    this.isAllDisplayDataChecked = false;
    this.loading1 = true;
    this.mainService
      .getFetchDataList("simple/data", "orderPlanRule", data)
      .subscribe((data) => {
        this.loading1 = false;
        if (data.status == 200) {
          this.listOfData = data.list;
          this.listLength = data.totalNum;
        }
      });
  }
  // 选中表格单列
  mapOfCheckedId: { [key: string]: boolean } = {};
  checkedDepIds = []; //已选中单列id
  refreshStatus(): void {
    this.isAllDisplayDataChecked = this.listOfData.every(
      (item) => this.mapOfCheckedId[item.id]
    );
    let arr = [];
    for (var k in this.mapOfCheckedId) {
      if (this.mapOfCheckedId[k]) {
        arr.push(Number(k));
      }
    }
    this.checkedDepIds = arr;
  }
  // 全选
  isAllDisplayDataChecked = false; //当前页是否全选
  checkAll(value: boolean): void {
    this.listOfData.forEach((item) => {
      this.mapOfCheckedId[item.id] = value;
    });
    this.refreshStatus();
  }
  // 批量删除
  showDelModals(e) {
    let ids = this.checkedDepIds.join(",");
    this.showDelModal(e, ids);
  }
  //删除
  delModal: boolean = false; //删除模态框
  loading3 = false;
  coopId: string; //表格中执行操作的id
  showDelModal(e, id) {
    e.stopPropagation();
    this.delModal = true;
    this.coopId = id + "";
  }
  hideDelModal() {
    this.delModal = false;
  }
  confirmDel() {
    this.loading3 = true;
    this.mainService
      .simplePost("rmvData", "orderPlanRule", this.coopId.split(","))
      .subscribe((data) => {
        this.loading3 = false;
        this.delModal = false;
        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.message.success("删除成功");
          this.getList(1);
        } else {
          this.message.error("删除失败");
        }
      });
  }
  ngOnInit() {
    console.log(this.selectedBatchOrder);
    this.hosId = this.tool.getCurrentHospital().id;
    this.getList(1);
    // 发起科室列表
    this.getDeptList().subscribe((result) => {
      if (result.status == 200) {
        result.list.forEach((item) => {
          item._uid = item.id + "__" + item.dept;
        });
        this.initiatingDepartments = result.list;
      }
    });
    this.taskType = JSON.parse(
      JSON.stringify(this.selectedBatchOrder.taskType)
    );
    this.startCarryingCourses = this.taskType.carryingCourses[0];
    this.endCarryingCourses = this.taskType.carryingCourses[1];
    if (this.startCarryingCourses.departmentDTOS) {
      this.startCarryingCourses.departmentDTOS.forEach((item) => {
        item._uid = item.id + "__" + item.dept;
      });
    }
    if (this.endCarryingCourses.departmentDTOS) {
      this.endCarryingCourses.departmentDTOS.forEach((item) => {
        item._uid = item.id + "__" + item.dept;
      });
    }
    if (
      // 起点科室是默认发起科室，终点科室是固定科室
      this.startCarryingCourses.departmentStrategy.value === "1" &&
      this.endCarryingCourses.departmentStrategy.value === "2"
    ) {
      this.type = 1;
      this.startDepartmentsDisabled = true;
      this.endDepartmentsDisabled = true;
    } else if (
      // 起点科室是固定科室，终点科室是默认发起科室
      this.startCarryingCourses.departmentStrategy.value === "2" &&
      this.endCarryingCourses.departmentStrategy.value === "1"
    ) {
      this.type = 2;
      this.startDepartmentsDisabled = true;
      this.endDepartmentsDisabled = true;
    } else if (
      // 起点科室是默认发起科室，终点科室是默认发起科室
      this.startCarryingCourses.departmentStrategy.value === "1" &&
      this.endCarryingCourses.departmentStrategy.value === "1"
    ) {
      this.type = 3;
      this.startDepartmentsDisabled = true;
      this.endDepartmentsDisabled = true;
    } else {
      //其他情况
      this.type = 4;
      // 发起科室列表,起点科室列表，终点科室列表
      this.getDeptList().subscribe((result) => {
        if (result.status == 200) {
          result.list.forEach((item) => {
            item._uid = item.id + "__" + item.dept;
          });
          this.initiatingDepartments = JSON.parse(JSON.stringify(result.list));
          this.startDepartments = JSON.parse(JSON.stringify(result.list));
          this.endDepartments = JSON.parse(JSON.stringify(result.list));
        }
      });
    }
  }
}
