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 { forkJoin, Subject } from "rxjs";
import { debounceTime } from "rxjs/operators";
import { NzMessageService } from "ng-zorro-antd";
@Component({
  selector: "app-shortcut-build-orders",
  templateUrl: "./shortcut-build-orders.component.html",
  styleUrls: ["./shortcut-build-orders.component.less"],
})
export class ShortcutBuildOrdersComponent implements OnInit {
  constructor(
    private message: NzMessageService,
    private fb: FormBuilder,
    private mainService: MainService,
    private route: ActivatedRoute,
    private router: Router,
    private tool: ToolService
  ) {}

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

  searchCriteria = {
    //搜索条件
    name: "",
    hospital: null,
    startDepartment: null,
  };
  // roundRobinTypes = [
  //   { id: '163', hosName: '标本轮巡' }
  // ];//快捷建单类型
  roundRobinTypes = []; //快捷建单类型
  createUser = "";
  department = []; // 院区下的科室列表(分类型)
  department1 = []; // 院区下的科室列表
  departmentSearch = []; // 院区下的科室列表(搜索框)
  allHospital: any = []; //院区下拉框
  hosId: any; //当前选中院区
  listOfData: any[] = []; //表格数据
  pageIndex: number = 1; //表格当前页码
  pageSize: number = 10; //表格每页展示条数
  listLength: number = 10; //表格总数据量
  tableHeight: number; //表格动态高
  modal: boolean = false; //新增/编辑模态框
  add: boolean; //true:新增；false:编辑
  validateForm: FormGroup; //新增/编辑表单
  coopId: number; //当前操作列id

  hospitalList: Array<object> = []; //院区列表
  btnLoading: boolean = false; //提交按钮loading状态
  printLoading: boolean = false; //批量打印按钮loading状态

  promptContent: string; //操作提示框提示信息
  ifSuccess: boolean; //操作成功/失败
  promptInfo: string; //操作结果提示信息
  promptModalShow: boolean; //操作提示框是否展示
  demoValue: number = 0;
  changeInpSubject = new Subject();
  ngOnInit() {
    this.changeInpSubject.pipe(debounceTime(500)).subscribe((v) => {
      this.searchDepartment(v[0], v[1]);
    });
    this.coopBtns = this.tool.initCoopBtns(this.route);
    this.getAllHospital();
    this.initForm();
    this.getHospitalList();
  }
  // 重置
  reset() {
    this.searchCriteria = {
      //搜索条件
      name: "",
      hospital: this.allHospital[0] ? this.allHospital[0]["id"] + "" : null,
      startDepartment: null,
    };
    this.getList(1);
  }
  // 获取轮巡类型
  getRoundRobinTypes(id) {
    this.mainService
      .getFetchDataList("configuration", "taskType", {
        taskType: { hosId: { id }, associationTypeIds: '380,259' },
        idx: 0,
        sum: 100,
      })
      .subscribe((data) => {
        if (data.status == 200) {
          this.roundRobinTypes = data.list
          // this.validateForm.controls.roundRobinType.setValue(
          //   this.roundRobinTypes[0] && this.roundRobinTypes[0].id
          // );
        }
      });
  }
  // 打印
  codes = []; //二维码
  print(e, batch, id?) {
    e.stopPropagation();
    this.printLoading = true;
    this.mainService
      .printShortcutBuildOrders(batch ? this.checkedDepIds : [id])
      .subscribe((data) => {
        if (data.status == 200) {
          this.codes = data.data;
          this.printLoading = false;
          setTimeout(() => {
            const printContent = document.getElementById("report");
            const WindowPrt = window.open("", "", "width=700,height=900");
            WindowPrt.document.write(printContent.innerHTML);
            WindowPrt.document.close();
            WindowPrt.focus();
            WindowPrt.print();
            WindowPrt.close();
          }, 100);
        }
      });
  }
  // 选中表格中快捷建单
  mapOfCheckedId = {};
  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;
    console.log(this.checkedDepIds);
  }
  // 整行操作
  selectedListData(id) {
    this.mapOfCheckedId[id] = !this.mapOfCheckedId[id];
    this.refreshStatus();
  }

  // 全选
  isAllDisplayDataChecked = false; //当前页是否全选
  checkAll(value: boolean): void {
    this.listOfData.forEach((item) => (this.mapOfCheckedId[item.id] = value));
    this.refreshStatus();
  }
  // 选择院区
  changeHospital(id, type) {
    if (type === "search") {
      this.searchCriteria.startDepartment = null;
    } else {
      if (
        this.validateForm &&
        this.validateForm.value &&
        this.validateForm.value.endDepartment
      ) {
        this.validateForm.controls.startDepartment.setValue(null);
        this.validateForm.controls.endDepartment.setValue(null);
        this.validateForm.controls.roundRobinType.setValue(null);
      }
    }
    // 1,请求指定科室类型的科室列表
    let data = {
      department: {
        hospital: { id },
        type: { id: 383 },
      },
      idx: 0,
      sum: 20,
    };
    this.mainService
      .getFetchDataList("data", "department", data)
      .subscribe((data) => {
        if (data.status == 200) {
          if (type === "search") {
            this.departmentSearch = data.list;
          } else {
            this.department = data.list;
          }
        }
      });
    if (type === "search") {
      return;
    }
    // 2,请求科室类型为检验科的科室列表
    let data2 = {
      department: {
        hospital: { id },
        type: { id: 282 },
      },
      idx: 0,
      sum: 20,
    };
		if(this.deptDicId){
			delete data2.department.type
		}else{
			data2.department.type.id = 282
		}
    this.mainService
      .getFetchDataList("data", "department", data2)
      .subscribe((data) => {
        if (data.status == 200) {
          this.department1 = data.list;
        }
      });
  }
  // 打开搜索框
  changeSearch(flag) {
    if (flag) {
      this.changeInp("no", "search");
    }
  }
  changeForm(flag) {
    if (flag) {
      this.changeInp("no", "form");
    }
  }
  changeFormEnd(flag) {
    if (flag) {
      this.changeInp("no", "formEnd");
    }
  }
  // 边输边搜节流阀
  isLoading = false;
  changeInp(dept, type) {
    if (dept === "no") {
      dept = "";
    }
    if (type === "form" || type === "formEnd") {
      if (!this.hosId) {
        this.department = [];
        return;
      }
    }
    this.isLoading = true;
    this.changeInpSubject.next([dept, type]);
  }
  // 修改起点科室院区
  changeStartHospital(e){
    console.log(e);
    this.validateForm.controls.startDepartment.setValue(null);
  }
  // 修改终点科室院区
  changeEndHospital(e){
    console.log(e);
    this.validateForm.controls.endDepartment.setValue(null);
  }
  // 搜索科室
  snum = 0;
  searchDepartment(dept, type) {
    let data = {
      department: {
        dept,
				deptHandoverType:{
					id: null
				},
        type: { id: 383 },
        hospital: {
          id: this.hosId,
        },
      },
      idx: 0,
      sum: 20,
    };
    if (type === "form") {
			if(this.deptDicId){
				data.department.deptHandoverType.id = this.deptDicId;
				delete data.department.type
			}else{
				data.department.type.id = 383
				delete data.department.deptHandoverType
			}
      if(this.validateForm.value.startDepartmentHospital){
				data.department.hospital.id = this.validateForm.value.startDepartmentHospital;
      }else{
        this.department = [];
        this.isLoading = false;
        return;
      }
    }
    // 终点科室的科室类型为检验科
    if (type === "formEnd") {
			if(this.deptDicId){
				delete data.department.deptHandoverType
				delete data.department.type
			}else{
				data.department.type.id = 282
				delete data.department.deptHandoverType
			}
      if(this.validateForm.value.endDepartmentHospital){
        data.department.hospital.id = this.validateForm.value.endDepartmentHospital;
      }else{
        this.department1 = [];
        this.isLoading = false;
        return;
      }
    }
    this.snum++;
    this.mainService
      .getFetchDataList("data", "department", data)
      .subscribe((data) => {
        this.snum--;
        if (data.status == 200) {
          if (type === "search") {
            if (this.snum === 0) {
              this.isLoading = false;
            }
            this.departmentSearch = data.list;
          } else if (type === "form") {
            if (this.snum === 0) {
              this.isLoading = false;
            }
            this.department = data.list;
          } else if (type === "formEnd") {
            if (this.snum === 0) {
              this.isLoading = false;
            }
            this.department1 = data.list;
          }
        }
      });
  }

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

  // 获取所有院区
  /**
   *
   *
   * @memberof RoundRobinComponent
   */
  getAllHospital() {
    this.allHospital = [this.tool.getCurrentHospital()];
    this.hosId = this.tool.getCurrentHospital().id;
    this.searchCriteria.hospital = this.tool.getCurrentHospital().id + "";
    this.getList(1);
    this.changeHospital(this.searchCriteria.hospital, "search");
    this.getRoundRobinTypes(this.hosId);
  }

  // 表格数据
  loading1 = false;
  getList(type) {
    if (type == 1) {
      this.pageIndex = 1;
    }
    let data = {
      idx: this.pageIndex - 1,
      sum: this.pageSize,
      quickOrder: {
        hospital: this.searchCriteria.hospital,
        startDept:
          this.searchCriteria.startDepartment === null
            ? ""
            : this.searchCriteria.startDepartment,
        title:
          this.searchCriteria.name === null ? "" : this.searchCriteria.name,
      },
    };
    this.mapOfCheckedId = {};
    this.checkedDepIds = [];
    this.isAllDisplayDataChecked = false;
    this.loading1 = true;
    this.mainService
      .getFetchDataList("api", "quickOrder", data)
      .subscribe((data) => {
        this.loading1 = false;
        if (data.status == 200) {
          this.listOfData = data.list;
          this.listLength = data.totalNum;
        }
      });
  }
	
	// 选择任务类型
	isOrther:any = 'multiple';
	changeType(e){
		this.validateForm.controls.startDepartmentHospital.setValue(null);
		this.validateForm.controls.startDepartment.setValue(null);
		this.validateForm.controls.endDepartmentHospital.setValue(null);
		this.department1 = [];
		this.validateForm.controls.endDepartment.setValue(null);
		let item = this.roundRobinTypes.find(i=>i.id == e)
		if(item){
			if(item.associationType.value == 'other'){
				this.mainService.getDictionary("list", "dept_handover_type").subscribe((data) => {
				  let item = data.find(i=>i.value == 'comprehensive')
					if(item){
						this.isOrther = 'default'
						this.deptDicId = item.id
					}else{
						this.isOrther = 'multiple'
						this.deptDicId = null
					}
				});
			}else{
				this.isOrther = 'multiple'
				this.deptDicId = null
			}
		}else{
			this.isOrther = 'multiple'
			this.deptDicId = null
		}
		
		setTimeout(_=>{
			this.validateForm.controls.startDepartmentHospital.setValue(null);
			this.validateForm.controls.startDepartment.setValue(null);
			this.validateForm.controls.endDepartmentHospital.setValue(null);
			this.department1 = [];
			this.validateForm.controls.endDepartment.setValue(null);
		},100)
	}
	
	deptDicId:any;
  // 新增/编辑弹框
  addModal() {
    this.add = true; //新增
    this.modal = true;
    this.initForm();
  }
  //关闭新增/编辑弹框
  hideAddModal() {
    this.modal = false;
    this.initForm();
  }
  // 初始化新增form表单
  initForm() {
    this.createUser = this.userInfo.user.name ? this.userInfo.user.name : "";
    this.validateForm = this.fb.group({
      roundRobinName: [null, [Validators.required]],
      roundRobinType: [null, [Validators.required]],
      startDepartmentHospital: [null, [Validators.required]],
      startDepartment: [null, [Validators.required]],
      endDepartmentHospital: [null, [Validators.required]],
      endDepartment: [null, [Validators.required]],
    });
    // this.validateForm.controls.roundRobinType.setValue(
    //   this.roundRobinTypes[0] && this.roundRobinTypes[0].id
    // );
    this.timeSelectedValue = [];
  }

  // 新增/编辑表单提交
  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 data = {};

    if (this.add) {
      //新增
      data = {
        quickOrder: {
          title: this.validateForm.value.roundRobinName,
          hospital: this.hosId,
          startDept: this.validateForm.value.startDepartment,
          taskType: this.validateForm.value.roundRobinType,
          targetDept: this.deptDicId ? this.validateForm.value.endDepartment : this.validateForm.value.endDepartment.join(),
        },
      };
    } else {
      //编辑
      data = {
        quickOrder: {
          id: this.coopId,
          title: this.validateForm.value.roundRobinName,
          hospital: this.hosId,
          startDept: this.validateForm.value.startDepartment,
          taskType: this.validateForm.value.roundRobinType,
          targetDept: this.deptDicId ? this.validateForm.value.endDepartment : this.validateForm.value.endDepartment.join(),
        },
      };
    }
    this.mainService
      .addShortcutBuildOrders(this.add ? "addData" : "updData", data)
      .subscribe((data) => {
        this.btnLoading = false;
        this.hideAddModal();
        this.initForm();
        if (data.status == 200) {
          this.listLength++;
          this.showPromptModal(this.add ? "新增" : "修改", true, "");
        } else {
          this.showPromptModal(this.add ? "新增" : "修改", false, data.msg);
        }
      });
  }

  // 编辑
  maskFlag: any = false;
  edit(e, data) {
    e.stopPropagation();
    this.add = false;
    this.coopId = data.id;
    this.createUser = data.createUserName; //创建人
    this.validateForm.controls.roundRobinName.setValue(data.title); //名称
    this.validateForm.controls.startDepartmentHospital.setValue(data.startDeptHosId.toString());//起点科室院区
    this.validateForm.controls.endDepartmentHospital.setValue(data.targetDeptHosId.toString());//终点科室院区
    let taskType$ = this.mainService.getFetchDataList(
      "configuration",
      "taskType",
      {
        taskType: {
          hosId: { id: data.hospital },
          associationTypeIds: '380,259',
        },
        idx: 0,
        sum: 100,
      }
    );

    // --------起点科室---
    let startDeptArr = []; //临时起点科室数组
    let startDept = data.startDept; //科室id
    let startDeptShow = data.startDeptShow; //科室名称
    startDeptArr.push({ id: startDept, dept: startDeptShow });
    let startDept$ = this.mainService.getFetchDataList("data", "department", {
      department: {
        hospital: { id: data.startDeptHosId },
        type: { id: 383 }, //科室类型为中转科室
      },
      idx: 0,
      sum: 20,
    });
    // --------/起点科室---
    // --------终点科室---
    let targetDeptArr = []; //临时终点科室数组
		let item = this.roundRobinTypes.find(i=>i.id == data.taskType)
		if(item){
			if(item.associationType.value == 'other'){
				this.mainService.getDictionary("list", "dept_handover_type").subscribe((data) => {
				  let item = data.find(i=>i.value == 'comprehensive')
					if(item){
						this.isOrther = 'default'
						this.deptDicId = item.id
					}else{
						this.isOrther = 'multiple'
						this.deptDicId = null
					}
				});
			}else{
				this.isOrther = 'multiple'
				this.deptDicId = null
			}
		}else{
			this.isOrther = 'multiple'
			this.deptDicId = null
		}
		let targetDept = null;
		let targetDeptShow = null;
		if(!this.deptDicId){
			targetDept = data.targetDept.split(","); //科室id
			targetDeptShow = data.targetDeptShow.split(","); //科室名称
			targetDept.forEach((item, index) => {
			  targetDeptArr.push({ id: item, dept: targetDeptShow[index] });
			});
		}else{
			targetDept = data.targetDept;
			targetDeptShow = data.targetDeptShow; //科室名称
			targetDeptArr.push({ id: targetDept, dept: targetDeptShow });
		}

    let targetDept$ = this.mainService.getFetchDataList("data", "department", {
      department: {
        hospital: { id: data.targetDeptHosId },
        type: { id: 282 },
      },
      idx: 0,
      sum: 20,
    });
    // --------/终点科室---
    this.maskFlag = this.message.loading("正在加载中..", {
      nzDuration: 0,
    }).messageId;
    forkJoin(taskType$, startDept$, targetDept$).subscribe((res) => {
      this.message.remove(this.maskFlag);
      this.maskFlag = false;
      this.modal = true;
      // 任务类型
      if (res[0]["status"] == 200) {
        this.roundRobinTypes = res[0]["list"]
        this.validateForm.controls.roundRobinType.setValue(
          data.taskType + ""
        ); //快捷建单类型
      }
      //起点科室
      if (res[1]["status"] == 200) {
        let add = startDeptArr.filter(
          (item) => !res[1]["list"].some((ele) => ele.id == item.id)
        ); //过滤掉已有的选项
        this.department = add.concat(res[1]["list"]); //拼接数组
        this.validateForm.controls.startDepartment.setValue(
          data.startDept + ""
        ); //起点科室
      }
      //终点科室
      if (res[2]["status"] == 200) {
				if(!this.deptDicId){
					let add = targetDeptArr.filter(
					  (item) => !res[2]["list"].some((ele) => ele.id == item.id)
					); //过滤掉已有的选项
					this.department1 = add.concat(res[2]["list"]); //拼接数组
					this.validateForm.controls.endDepartment.setValue(targetDept); //终点科室
				}else{
					let add = targetDeptArr.filter(
					  (item) => !res[2]["list"].some((ele) => ele.id == item.id)
					); //过滤掉已有的选项
					this.department1 = add.concat(res[2]["list"]); //拼接数组
					this.validateForm.controls.endDepartment.setValue(targetDept.toString());
				}
      }
    });
  }

  // 展示信息提示框（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(
    e,
    id: number,
    tipsMsg1: string,
    tipsMsg2: string,
    type: string,
    isSwitch?: boolean
  ) {
    e.stopPropagation();
    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.delShortcutBuildOrders(this.coopId).subscribe((data) => {
        this.btnLoading = false;
        this.delModal = false;
        if (data.status == 200) {
          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);
        }
      });
    } else if (this.confirmDelType === "switch") {
      //启用/停用
      this.mainService
        .switchRoundRobin(
          this.confirmDelIsSwitch ? "stop" : "active",
          this.coopId
        )
        .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);
          }
        });
    }
  }

  // 院区列表
  getHospitalList() {
    this.hospitalList = [this.tool.getCurrentHospital()];
  }
  // 查看
  detail(e, id) {
    e.stopPropagation();
    this.router.navigateByUrl(
      "/main/shortcutBuildOrders/shortcutBuildOrdersDetail/" + id
    );
  }
  //时间选择框相关
  timeSelectedValue = [];
  defaultSelectTimesOption = [];

  time: Date | null = null;
  defaultTimePickerOpenValue = new Date();
  timePickerOpen = false;
  timeSelectFocus() {
    this.timePickerOpen = true;
  }
  timePickerClick() {
    this.timePickerOpen = false;
    this.time = this.time || new Date();
    let hour = (this.time.getHours() + "").padStart(2, "0");
    let minute = (this.time.getMinutes() + "").padStart(2, "0");
    let str = `${hour}:${minute}`;
    if (!this.timeSelectedValue.includes(str)) {
      this.defaultSelectTimesOption.push(str);
      this.timeSelectedValue.push(str);
    }
  }
  timePickerChange() {
    if (this.timePickerOpen) {
      this.timePickerOpen = false;
    }
  }
}
