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

import { MainService } from "../../services/main.service";
import { OverlayScrollbarsComponent } from "overlayscrollbars-ngx";
import { ToolService } from "../../services/tool.service";
import { format, startOfDay, endOfDay } from "date-fns";
import { NzMessageService } from "ng-zorro-antd";
import { Subject } from "rxjs";
import { debounceTime, filter } from "rxjs/operators";
import host from "../../../assets/js/http";
import { HttpRequest, HttpResponse, HttpClient } from '@angular/common/http';
import { NzContextMenuService, NzDropdownMenuComponent } from 'ng-zorro-antd/dropdown';
import { NzFormatEmitEvent, NzTreeNode } from 'ng-zorro-antd/core';

@Component({
  selector: "app-common-document",
  templateUrl: "./common-document.component.html",
  styleUrls: ["./common-document.component.less"],
})
export class CommonDocumentComponent 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,
    private http: HttpClient,
  ) {}

  ngOnInit() {
		this.hosId = this.tool.getCurrentHospital().id;
		this.userId = this.tool.getCurrentUserId();
    this.coopBtns = this.tool.initCoopBtns(this.route);
		this.getTreeData();
  }
	userId:any;
  listOfData: any[] = []; //表格数据
  promptContent: string; //操作提示框提示信息
  ifSuccess: boolean; //操作成功/失败
  promptInfo: string; //操作结果提示信息
  promptModalShow: boolean; //操作提示框是否展示
  modal: boolean = false; //新增/编辑模态框
  add: boolean; //true:新增；false:编辑
  validateForm: FormGroup; //新增/编辑表单
	validateTreeForm: FormGroup; //新增/编辑表单
  coopId: number; //表格中执行操作的id
  department: ""; //所属科室
	hosId: number;
	dateRange;//时间
  batchNumber; //批次号
  num; //编码
  deptalias; //别名
  type; //类型
  deptHandoverType; //类型
  pageIndex: number = 1; //页码
  listLength: number = 10; //总条数
  pageSize: number = 10; //每页条数
  btnLoading: boolean = false; //确认按钮loading状态
  printLoading: boolean = false; //批量打印按钮loading状态
  deptPhones: any = []; //新添加的科室电话列表
  isAddDeptsPhone = true; //添加新的科室电话是否禁用
  deptsPhoneId = 1; //科室电话自增id
  allParentdepart: any = []; //所有的父级科室列表
  hospitals1: any = []; //科室列表(搜索)
	rowData: object = {}; //打印选择列表
  searchParentDeptSubject = new Subject();
  // 初始化增删改按钮
  coopBtns: any = {};
	viewData: any = []; //科室单查看数据
	nodes: any = [];
	
	// 新增一级目录
	addModal:boolean = false;
	treeType:any;
	addTree(type){
		if(type==2){
			if(!this.treeItem){
				this.message.error('请先选择目录！')
				return
			}
		}else if(type==1){
			this.treeItem = null
			this.parentNode = null
		}
		this.treeType = type
		this.add = true
		this.initAddForm();
	}	
	
	// 编辑目录
	editTree(type){
		if(!this.treeItem){
			this.message.error('请先选择目录！')
			return
		}
		this.treeType = type
		this.add = false
		this.initAddForm('edit');
	}
	
	hideAddModal(){
		this.addModal = false
	}
	
	// 点击数节点
	treeItem:any; //当前节点
	parentNode:any; //父级节点
	activedNode:any;
	nodeClick(data: NzFormatEmitEvent): void{
		this.treeItem = data.node.origin
		this.parentNode = data.node.parentNode ? data.node.parentNode.origin : null
		// console.log(123,this.treeItem)
		// console.log(456,this.parentNode)
		this.getList();
	}
	
	openFolder(data: NzTreeNode | Required<NzFormatEmitEvent>): void {
		console.log(9998, data)
	}
		
	// 删除目录
	treeDel(){
		if(!this.treeItem){
			this.message.error('请先选择目录！')
			return
		}
		this.delTreeModal = true;
	}
	// 取消删除目录
	delTreeModal:boolean = false;
	hideTreeModal() {
	  this.delTreeModal = false;
	}
	// 确认删除目录
	confirmTree() {
	  var that = this;
	  that.btnLoading = true;
	  that.mainService
	    .coopData(
	      "rmvData",
	      "documentFolder",
	      [that.treeItem.id]
	    )
	    .subscribe((data) => {
	      that.btnLoading = false;
	      that.delTreeModal = false;
				if (data.status==200) {
					that.showPromptModal("删除", true, "");
					this.treeItem = null
					this.parentNode = null
					this.getTreeData();
				} else {
					that.showPromptModal("删除", false, data.msg);
				}

	    });
	}
	// 获取目录数据
	defaultExpandedKeys:any = [];	
	getTreeData(){
		let query = {
			idx: 0,
			sum: 9999,
			documentFolder:{
				personal: 0,
				// createUser: this.userId,
				hosId: this.hosId
			}
		}
		this.mainService
		  .getFetchDataList("data", "documentFolder", query)
		  .subscribe((res) => {
		    let data = res.list;
				data = data.map(v => ({...v, parentId: v.parent ? v.parent.id : undefined, title: v.folderName, key: v.id}));
				this.nodes = this.tool.tranListToTreeDataLeaf(data, undefined, "parentId");
				this.defaultExpandedKeys = [this.nodes.length>0?this.nodes[0].key:null]
				// if(this.nodes[0].children && this.nodes[0].children.length>0){
				// 	this.defaultExpandedKeys.push(this.nodes[0].key)
				// 	this.setSelectKey(this.nodes[0].children);
				// 	console.log(4444,this.defaultExpandedKeys)
				// }
			});
	}
	
	setSelectKey(data){
		for(let i of data){
			this.defaultExpandedKeys.push(i.key)
			if(i.children && i.children.length>0){
				this.setSelectKey(i.children);
			}
		}
	}
	
	// 初始化新增form表单
	initAddForm(type:any = 'add') {
		this.validateTreeForm = this.fb.group({
			folderName: [type=='edit' ? this.treeItem.folderName : null, [Validators.required]],
			parent: [null, []],
		});
		if(this.treeType==2){
			this.validateTreeForm.addControl(
			  "parent",
			  new FormControl(null)
			);
			this.validateTreeForm.controls.parent.setValue(this.treeItem.folderName);
		}else{
			this.validateTreeForm.removeControl("parent");
		}
		setTimeout(_=>{
			this.addModal = true
		},50)
	}
	
	// 新增/编辑树
	submitAddForm(): void {
	  for (const i in this.validateTreeForm.controls) {
	    this.validateTreeForm.controls[i].markAsDirty();
	    this.validateTreeForm.controls[i].updateValueAndValidity();
	  }
	  if (this.validateTreeForm.invalid) return;
	  this.btnLoading = true;
		let postData = {
			documentFolder:{
				personal: 0,
				hosId: this.hosId,
				folderName: this.validateTreeForm.value.folderName,
				parent:{
					id:''
				},
				id:null,
			}
		};
	  if (this.treeType==1) {
	    delete postData.documentFolder.parent
			delete postData.documentFolder.id
	  } else if(this.treeType==2) {
			postData.documentFolder.parent.id = this.treeItem.id
		} else if(this.treeType==3) {
			postData.documentFolder.id = this.treeItem.id
			delete postData.documentFolder.parent
		}
	  this.mainService
	    .coopData(this.add ? "addData" : "updData", "documentFolder", postData)
	    .subscribe((result) => {
	      this.hideAddModal();
	      this.btnLoading = false;
	      if (result["status"] == 200) {
					this.treeItem = null
					this.parentNode = null
					this.getTreeData();
	        this.showPromptModal(this.add ? "新增" : "编辑", true, "");
	      } else {
	        this.showPromptModal(
	          this.add ? "新增" : "编辑",
	          false,
	          result["msg"]
	        );
	      }
	    });
	}
	
  // 模板导出
  excelExport(e, item){
    this.maskFlag = this.message.loading("下载中..", {
      nzDuration: 0,
    }).messageId;
    this.mainService.documentExport(item.fileToken).subscribe(
      (data) => {
        this.message.remove(this.maskFlag);
        this.maskFlag = false;
        this.message.success('下载成功');
				let type = null
				if(item.fileType=='xls'){
					console.log(1)
					type = 'application/vnd.ms-excel'
				}else if(item.fileType=='xlsx'){
					type = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
				}else if(item.fileType=='doc'){
					type = 'application/msword'
				}else if(item.fileType=='docx'){
					type = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
				}else if(item.fileType=='pdf'){
					type = 'application/pdf'
				}else if(item.fileType=='ppt'){
					type = 'application/vnd.ms-powerpoint'
				}else if(item.fileType=='pptx'){
					type = 'application/vnd.openxmlformats-officedocument.presentationml.presentation'
				}else if(item.fileType=='png'){
					type = 'image/png'
				}else if(item.fileType=='gif'){
					type = 'image/gif'
				}else if(item.fileType=='jpeg' || item.fileType=='jpg'){
					type = 'image/jpeg'
				}
        var file = new Blob([data], {
          type: type,
        });
        var fileURL = URL.createObjectURL(file);
        var a = document.createElement("a");
        a.href = fileURL;
        a.target = "_blank";
        a.download = item.fileName;
        document.body.appendChild(a);
        a.click();
      },
      (err) => {
        this.message.remove(this.maskFlag);
        this.maskFlag = false;
        this.message.error('下载失败');
      }
    );
  }

  // 导入---start
  // model-取消
  isShow = false;
  hideExcelImport() {
    this.isShow = false;
  }
  // 触发
	uploadType:any;
	itemId:any;
  excelImport(id, type) {
		if(!this.treeItem && type==1){
			this.message.error('请先选择目录！')
			return
		}
		this.uploadType = type
		this.itemId = id
    this.isShow = true;
  }
	maskFlag:any;
  submitExcelImport({fileList}){
    this.isShow = false;
    const formData = new FormData();
    fileList.forEach((file: any) => {
      formData.append('file', file);
			formData.append('filename', file.name);
    });
		let url = null
		let title = null
		if(this.uploadType==1){
			url = this.mainService.documentImport(this.treeItem.id, 0);
			title = '上传'
		}else{
			url = this.mainService.documentUpdateFile(this.itemId);
			title = '更新'
		}
    this.maskFlag = this.message.loading(`正在${title}中..`, {
      nzDuration: 0,
    }).messageId;

    const req = new HttpRequest('Post', url, formData, {
      reportProgress: true
    });
    this.http
      .request(req)
      .pipe(filter(e => e instanceof HttpResponse))
      .subscribe(
        (res:any) => {
          if(res.body.status == 200){
            this.message.remove(this.maskFlag);
            this.maskFlag = false;
            this.message.success(`${title}成功`);
            this.getList();
          }else{
            this.message.remove(this.maskFlag);
            this.maskFlag = false;
            this.showPromptModal(`${title}`, false, res.body.msg);
          }
        },
        () => {
          this.message.remove(this.maskFlag);
          this.maskFlag = false;
          this.message.error(`${title}失败`);
        },
      );
  }
  // 导入---end
  //搜索父级科室
	isDeptLoading = false;
  changeInp(e) {
    this.searchParentDeptSubject.next(e);
  }
  // 打开父级科室下拉框baba
  isLoading = false;
  // 配送建单
  coopData:any = {};
  delList(e,data) {
    this.coopData = data;
    this.showDelModal(e,data);
  }
  delModal1: boolean = false; //删除模态框

  // 搜索
  search() {
    this.pageIndex = 1;
    this.getList();
  }
  // 重置
  reset() {
    this.pageIndex = 1;
    this.getList();
  }
  // 表格数据
  loading1 = false;
	fileName:any;
  getList() {
    var that = this;
    let data = {
      idx: that.pageIndex - 1,
      sum: that.pageSize,
      documentFile: {
				hosId: this.hosId,
				fileName: this.fileName,
				personal: 0,
				folderId: this.treeItem && this.treeItem.id || undefined
      },
    };
    this.loading1 = true;
    that.mainService
      .getFetchDataList("data", "documentFile", data)
      .subscribe((data) => {
        this.loading1 = false;
        that.listOfData = data.list;
        that.listLength = data.totalNum;
      });
  }

	// 日期选择
	startDate: string; //发起时间开始
	endDate: string; //发起时间结束
	changeDate(result?): void {
	  if (!result) {
	    this.startDate = this.endDate = "";
	    return;
	  }
	  this.startDate = format(startOfDay(result[0]), 'yyyy-MM-dd HH:mm:ss');
	  this.endDate = format(endOfDay(result[1]), 'yyyy-MM-dd HH:mm:ss');
	}

  // 新增弹框
  showModal() {
    this.initForm();
    // this.changeHosp();
    this.add = true;
    this.isAddDeptsPhone = true;
    this.deptPhones = [];
  }
  hideModal() {
    this.coopItem = null;
    this.modal = false;
    this.initForm();
  }
  // 初始化新增form表单
  initForm() {
    this.endTime1Hourdis = () => [];
    this.endTime1Mindis = () => [];
    this.endTime2Hourdis = () => [];
    this.endTime2Mindis = () => [];
    this.startTime1Hourdis = () => [];
    this.startTime1Mindis = () => [];
    this.startTime2Hourdis = () => [];
    this.startTime2Mindis = () => [];
    this.validateForm = this.fb.group({
      parentOfficeName: [null],
      officeName: [null, [Validators.required]],
      deptalias: [null],
      officeNo: [null, [Validators.required]],
      officeNum: [null, [Validators.required]],
      building: [null, [Validators.required]],
      floor: [null, [Validators.required]],
      officeAddress: [null, [Validators.required]],
      officeType: [null, [Validators.required]],
      deptHandoverType: [null],
      startTime1: [null],
      endTime1: [null],
      dynamicCode1: [null],
      startTime2: [null],
      endTime2: [null],
      dynamicCode2: [null],
    });
  }
  // 科室位置必填
  buildValidator = (control: FormControl): { [s: string]: boolean } => {
    if (
      this.validateForm &&
      this.validateForm.value &&
      (!this.validateForm.value.building ||
        !this.validateForm.value.floor ||
        !this.validateForm.value.officeAddress)
    ) {
      return { required: true };
    }
  };
  /**
   * 生成一个从 start 到 end 的连续数组
   * @param start
   * @param end
   */
  generateArray(start, end) {
    return Array.from(new Array(end).keys()).slice(start);
  }

  //服务时间选择
  // 禁用的小时
  startTime1Hourdis() {
    return [];
  }
  endTime1Hourdis() {
    return [];
  }
  startTime2Hourdis() {
    return [];
  }
  endTime2Hourdis() {
    return [];
  }
  // 禁用的分钟
  startTime1Mindis() {
    return [];
  }
  endTime1Mindis() {
    return [];
  }
  startTime2Mindis() {
    return [];
  }
  endTime2Mindis() {
    return [];
  }
  timeChange(e: boolean, type: string, num: number) {
    if (!e && this.validateForm.value[type + num]) {
      let hour = new Date(this.validateForm.value[type + num]).getHours();
      let minute = new Date(this.validateForm.value[type + num]).getMinutes();
      if (type == "startTime" && num === 1) {
        this.endTime1Hourdis = () => this.generateArray(0, hour);
        this.endTime1Mindis = () => this.generateArray(0, minute + 1);
      } else if (type == "startTime" && num === 2) {
        this.endTime2Hourdis = () => this.generateArray(0, hour);
        this.endTime2Mindis = () => this.generateArray(0, minute + 1);
      } else if (type == "endTime" && num === 1) {
        this.startTime1Hourdis = () => this.generateArray(hour + 1, 24);
        this.startTime1Mindis = () => this.generateArray(minute, 60);
      } else if (type == "endTime" && num === 2) {
        this.startTime2Hourdis = () => this.generateArray(hour + 1, 24);
        this.startTime2Mindis = () => this.generateArray(minute, 60);
      }
    }
  }
  // 表单提交
  submitForm(): void {
    var that = this;
    for (const i in that.validateForm.controls) {
      that.validateForm.controls[i].markAsDirty();
      that.validateForm.controls[i].updateValueAndValidity();
    }
    console.log(that.validateForm);
    if (that.validateForm.invalid) return;
    let deptsPhone = this.deptPhones.map((item) => item.phone).join();
    let data: any = {
      department: {
        dept: that.validateForm.value.officeName,
        deptalias: that.validateForm.value.deptalias,
        // hospital: { id: that.add ? that.tool.getCurrentHospital().id : that.hospital },
        pcode: that.validateForm.value.officeNo,
        manyPhone: deptsPhone
          ? that.validateForm.value.officeNum + "," + deptsPhone
          : that.validateForm.value.officeNum,
        building: { id: that.validateForm.value.building - 0 },
        floor: { id: that.validateForm.value.floor - 0 },
        address: that.validateForm.value.officeAddress,
        type: { id: that.validateForm.value.officeType },
        deptHandoverType: { id: that.validateForm.value.deptHandoverType },
      },
    };
    if (this.validateForm.value.parentOfficeName) {
      data.department.parent = { id: this.validateForm.value.parentOfficeName };
    }
    if (
      this.validateForm.value.startTime1 ||
      this.validateForm.value.endTime1
    ) {
      if (
        this.validateForm.value.startTime1 &&
        this.validateForm.value.endTime1
      ) {
        data.department["startTime1"] = format(
          this.validateForm.value.startTime1,
          "yyyy-MM-dd HH:mm:ss"
        );
        data.department["endTime1"] = format(
          this.validateForm.value.endTime1,
          "yyyy-MM-dd HH:mm:ss"
        );
        data.department["dynamicCode1"] = this.validateForm.value.dynamicCode1 ? 1 : 0;
      } else {
        return;
      }
    }
    if (
      this.validateForm.value.startTime2 ||
      this.validateForm.value.endTime2
    ) {
      if (
        this.validateForm.value.startTime2 &&
        this.validateForm.value.endTime2
      ) {
        data.department["startTime2"] = format(
          this.validateForm.value.startTime2,
          "yyyy-MM-dd HH:mm:ss"
        );
        data.department["endTime2"] = format(
          this.validateForm.value.endTime2,
          "yyyy-MM-dd HH:mm:ss"
        );
        data.department["dynamicCode2"] = this.validateForm.value.dynamicCode2 ? 1 : 0;
      } else {
        return;
      }
    }
    if (!that.add) {
      data.department["id"] = that.coopId;
    }
    that.btnLoading = true;
    that.mainService
      .coopData(that.add ? "addData" : "updData", "department", data)
      .subscribe((data) => {
        that.btnLoading = false;
        that.hideModal();
        that.initForm();
        if (data.status == 200) {
          that.showPromptModal(that.add ? "新增" : "编辑", true, "");
        } else {
          that.showPromptModal(that.add ? "新增" : "编辑", false, data.msg);
        }
      });
  }

  // 编辑
  coopItem: any = null;
  // 展示信息提示框（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();
		this.getTreeData();
  }

  delModal: boolean = false; //删除模态框
  coopIds: any;
  coopFlag: any = false;
  /**
   *
   * @param e 事件对象
   * @param flag true是批量删除，false是单个删除
   * @param id
   */
  showDelModal(e, id) {
    e.stopPropagation();
    this.delModal = true;
    this.coopId = id;
  }
  hideDelModal() {
    this.delModal = false;
  }
  // 确认删除
  confirmDel() {
    var that = this;
    that.btnLoading = true;
    that.mainService
      .coopData(
        "rmvData",
        "documentFile",
        [that.coopId]
      )
      .subscribe((data) => {
        that.btnLoading = false;
        that.delModal = false;
        if (data.status==200) {
          that.showPromptModal("删除", true, "");
        } else {
          that.showPromptModal("删除", false, data.msg);
        }
      });
  }

  // 查看
  detail(item) {
		this.coopData = item;
		var that = this;
		let data = {
			idx: 0,
			sum: 9999,
			documentFile: {
			  hosId: this.hosId,
			  fileCode: item.fileCode
			}
		};
		this.loading1 = true;
		that.mainService
		  .getFetchDataList("data", "documentFile", data)
		  .subscribe((data) => {
		    this.loading1 = false;
				this.modal = true
		    that.viewData = data.list;
		  });
  }
	
	// 删除历史
	delHistory(e,data){
		this.coopData = data;
		this.showHistoryModal(e,data);
	}
	
	HistoryId:any;
	showHistoryModal(e, id) {
	  e.stopPropagation();
	  this.delModal = true;
	  this.HistoryId = id;
	}
	hideHistoryModal() {
	  this.delModal = false;
	}
	// 确认删除
	confirmHistory() {
	  var that = this;
	  that.btnLoading = true;
	  that.mainService
	    .coopData(
	      "rmvData",
	      "documentFile",
	      [that.HistoryId]
	    )
	    .subscribe((data) => {
	      that.btnLoading = false;
	      that.delModal = false;
	      if (data.status==200) {
	        that.showPromptModal("删除", true, "");
					this.detail(this.coopData)
	      } else {
	        that.showPromptModal("删除", false, data.msg);
	      }
	    });
	}
	
	// 下载历史
	excelHistory(item){
		this.maskFlag = this.message.loading("下载中..", {
		  nzDuration: 0,
		}).messageId;
		this.mainService.documentExport(item.fileToken).subscribe(
		  (data) => {
		    this.message.remove(this.maskFlag);
		    this.maskFlag = false;
		    this.message.success('下载成功');
				let type = null
				if(item.fileType=='xls'){
					type = 'application/vnd.ms-excel'
				}else if(item.fileType=='xlsx'){
					type = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
				}else if(item.fileType=='doc'){
					type = 'application/msword'
				}else if(item.fileType=='docx'){
					type = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
				}else if(item.fileType=='pdf'){
					type = 'application/pdf'
				}else if(item.fileType=='ppt'){
					type = 'application/vnd.ms-powerpoint'
				}else if(item.fileType=='pptx'){
					type = 'application/vnd.openxmlformats-officedocument.presentationml.presentation'
				}else if(item.fileType=='png'){
					type = 'image/png'
				}else if(item.fileType=='gif'){
					type = 'image/gif'
				}else if(item.fileType=='jpeg' || item.fileType=='.jpg'){
					type = 'image/jpeg'
				}
		    var file = new Blob([data], {
		      type: type,
		    });
		    var fileURL = URL.createObjectURL(file);
		    var a = document.createElement("a");
		    a.href = fileURL;
		    a.target = "_blank";
		    a.download = item.fileName + item.fileType;
		    document.body.appendChild(a);
		    a.click();
		  },
		  (err) => {
		    this.message.remove(this.maskFlag);
		    this.maskFlag = false;
		    this.message.error('下载失败');
		  }
		);
	}

}
