import { Component, OnInit, ViewChild } from "@angular/core";
import { ActivatedRoute, Router } from "@angular/router";
import { DomSanitizer } from '@angular/platform-browser';
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, subDays} 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';

@Component({
  selector: "app-repository-manage",
  templateUrl: "./repository-manage.component.html",
  styleUrls: ["./repository-manage.component.less"],
})
export class RepositoryManageComponent 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,
		private sanitizer: DomSanitizer
  ) {}
  searchTimerSubject = new Subject();
  ngOnInit() {
    this.searchParentDeptSubject.pipe(debounceTime(500)).subscribe((e) => {

    });
    this.searchTimerSubject.pipe(debounceTime(500)).subscribe((v) => {
      let fun = v[0];
      fun.call(this, v[1], v[2]);
    });
		this.hosId = this.tool.getCurrentHospital().id;
    this.coopBtns = this.tool.initCoopBtns(this.route);
		this.maintainDept = this.tool.getUserInfoPermission().dutyList
		if(this.coopBtns.strideLook){
			this.defaDept()
		}
		this.getList();
    this.getUsers();
  }
  createUserList: any = []; //创建人列表
	maintainDept:any = []; //维修科室
	maintainDepartment:any;
	hosIds:any; //当前院区
	richText:any;
  listOfData: any[] = []; //表格数据
  promptContent: string; //操作提示框提示信息
  ifSuccess: boolean; //操作成功/失败
  promptInfo: string; //操作结果提示信息
  promptModalShow: boolean; //操作提示框是否展示
  modal: boolean = false; //新增/编辑模态框
  add: boolean; //true:新增；false:编辑
  validateForm: FormGroup; //新增/编辑表单
  coopId: number; //表格中执行操作的id
  department: number; //所属科室
	hosId: number;
	loadAllConsumeDept: boolean = true;//是否加载所有消耗科室
  solutionNumber; //编号
  createUserId; //创建人
	title; //标题
  num; //编码
  deptalias; //别名
  type; //类型
  deptHandoverType; //类型
	vIndex:number = 0;//版本号下标
	stepLength: number = 0; //步骤条
  pageIndex: number = 1; //页码
  listLength: number = 10; //总条数
  pageSize: number = 10; //每页条数
  btnLoading: boolean = false; //确认按钮loading状态
	btnLoading1: boolean = false; //审核通过按钮loading状态
	btnLoading2: boolean = false; //审核驳回按钮loading状态
  printLoading: boolean = false; //批量打印按钮loading状态
  deptPhones: any = []; //新添加的科室电话列表
  isAddDeptsPhone = true; //添加新的科室电话是否禁用
  deptsPhoneId = 1; //科室电话自增id
  allParentdepart: any = []; //所有的父级科室列表
  hospitals1: any = []; //科室列表(搜索)
	rowData: object = {}; //打印选择列表
	editModal:boolean = false; //编辑时弹框
	isSpinning: boolean = false; //页面loading状态
	detailData:any;
	solutionLogs:any;
	lookData:any;
	versionsData: any = []; //审核版本数据
	fileData: any = []; //上传的附件数据
  searchParentDeptSubject = new Subject();
  // 初始化增删改按钮
  coopBtns: any = {};
	saveLoading:boolean = false;
	taskTypeData:{id:''};
	rejectModal:boolean = false;
	rejectData:null;
	optType:string = '';
  // 导入---end
  //搜索父级科室
	isDeptLoading = false;
  changeInp(e) {
    this.searchParentDeptSubject.next(e);
  }
  // 配送建单
  coopData:any = {};
  addDateModal(data) {
    this.coopData = data;
    this.showDelModal1();
  }

	// 默认科室
	defaDept(){
		let itemDept = this.maintainDept.find(i=>i.id == this.hosId)
		if(itemDept){
			this.maintainDepartment = itemDept.id
		}
	}

  showDelModal1() {
    this.editModal = true;
  }
  hideDelModal1() {
    this.editModal = false;
  }

  // 编辑保存
  confirmDel1() {
    var that = this;
		for (const i in that.validateForm.controls) {
		  that.validateForm.controls[i].markAsDirty();
		  that.validateForm.controls[i].updateValueAndValidity();
		}
		if (that.validateForm.invalid) return;
    let data: any = {
			hosId:this.hosId,
			pharmacy:this.validateForm.value.department,
			id:that.coopId,
			loadAllConsumeDept:this.validateForm.value.loadAllConsumeDept?1:0
    };
		that.saveLoading = true;
		that.mainService
		  .simplePost("addData", "drugsBatch", data)
		  .subscribe((data) => {
		    that.saveLoading = false;
		    that.hideModal();
		    if (data.status == 200) {
					this.editModal = false;
		      that.showPromptModal("编辑", true, "");
		    } else {
		      that.showPromptModal("编辑", false, data.msg);
		    }
		  });
  }

  // 搜索
  search() {
    this.pageIndex = 1;
    this.getList();
  }
  // 重置
  reset() {
    this.pageIndex = 1;
		this.solutionNumber = null;
		this.title = null;
    this.createUserId = undefined;
		if(this.coopBtns.strideLook){
			this.defaDept()
		}
    this.getList();
  }
  // 表格数据
  loading1 = false;
  getList() {
    var that = this;
    let data = {
      idx: that.pageIndex - 1,
      sum: that.pageSize,
      solution: {
    		title:this.title,
				solutionNumber:this.solutionNumber,
        createUserId: this.createUserId || undefined,
    		hosId: this.hosId,
      },
    };
		if(this.maintainDepartment){
			data.solution.hosId = this.maintainDepartment;
		}
    this.loading1 = true;
    that.mainService
      .getFetchDataList("data", "solution", data)
      .subscribe((data) => {
        this.loading1 = false;
        that.listOfData = data.list;
        that.listLength = data.totalNum;
      });
  }

	// 版本号点击
	versionsClick(data, index){
		this.vIndex = index
		this.lookData = data
		let content = data.content
		if(content){
			this.richText = this.sanitizer.bypassSecurityTrustHtml(content);
		}else{
			this.richText = ''
		}
	}

	// 点击附件
	fileClick(data){
		console.log(222,data)
		let a: any = document.createElement('a') // 创建一个元素
		a.style = 'display: none' // 不能在页面中被看到，把他隐藏起来
		a.style.height = '0px' // 给个0高度，避免影响页面布局
		a.download = data.name;
		a.href = data.url // 文件url地址
		document.body.appendChild(a)  //  将其绑定在body上才能发挥作用
		a.click() // 触发a标签的click事件
		document.body.removeChild(a) // 删除该元素
	}

  hideModal() {
    this.modal = false;
  }

	// 审核通过
	confirmDel4() {
		let data: any = {
			id:this.rowId,
			operationType: 'approve'
		};
		this.btnLoading1 = true;
		this.mainService
			.simplePost("updData", "solution", data)
			.subscribe((data) => {
				this.btnLoading1 = false;
				this.hideDelModal4()
				if (data.status == 200) {
					this.showPromptModal("审核", true, "");
				} else {
					this.showPromptModal("审核", false, data.msg);
				}
			});
	}

	hideDelModal4() {
	  this.auditModal = false;
	}

	// 审核驳回
	rejectCancel(){
		this.rejectModal = false
	}

	// 审核驳回
	rejectOk(){
		if(this.rejectData==null){
			this.message.error('请输入整改意见')
			return
		}
		let data: any = {
			id:this.rowId,
			operationType: 'approve',
			rejectReason:this.rejectData
		};
		this.btnLoading2 = true;
		this.mainService
			.simplePost("updData", "solution", data)
			.subscribe((data) => {
				this.btnLoading2 = false;
				this.rejectCancel()
				if (data.status == 200) {
					this.showPromptModal("驳回", true, "");
				} else {
					this.showPromptModal("驳回", false, data.msg);
				}
			});
	}

	closeModel(){
		this.hideModal()
	}

  // 表单提交
	auditModal = false;
  submitForm(type): void {
    var that = this;
		if(type==1){
			this.auditModal = true
		}else{
			this.rejectData = null
			this.rejectModal = true
		}
  }

	// 升级
	upgrade(e, data){
		e.stopPropagation();
		this.router.navigateByUrl(`/repositoryManageAdd/${data.id}?type=upgrade`);
	}

	// 新增
	addForm(){
		this.router.navigateByUrl(`/repositoryManageAdd/0`);
	}

	// 查看
	look(e, data){
		e.stopPropagation();
		this.optType = 'look'
		this.rowId = data.id
		this.vIndex = 0
		this.modal = true
		var that = this;
		let query = {
			idx: 0,
			sum: 9999,
			solution: {
				hosId: this.hosId,
				operationType:'lookOver',
				solutionNumber:data.solutionNumber
			}
		};
		this.isSpinning = true
		that.mainService
			.getFetchDataList("data", "solution", query)
			.subscribe((res) => {
				this.getFile()
				let data = res.list
				this.detailData = data
				let content = data[0].content
				if(content){
					this.richText = this.sanitizer.bypassSecurityTrustHtml(content);
				}else{
					this.richText = ''
				}
				for(let i of data){
					if(i.solutionLogs.length>0){
						for(let t of i.solutionLogs){
							t.time = format(t.operationTime, 'yyyy-MM-dd HH:mm')
						}
					}
				}
				this.lookData = data[0]
				this.solutionLogs = data[0].solutionLogs
				this.stepLength = this.solutionLogs.length
				this.isSpinning = false
			});
	}

	getFile(){
		this.mainService
			.getPreviewImage('solution', this.rowId)
			.subscribe((res:any)=> {
				this.fileData = res.data.map((v) =>{
					return{
						name: v.name,
						url: location.origin + '/file' + v.relativeFilePath
					}
				});
			});
	}

	// 审核
	rowId=null;
	audit(e, data){
		e.stopPropagation();
		this.rowId = data.id
		this.vIndex = 0
		this.optType = 'audit'
		this.modal = true
		var that = this;
		let query = {
			idx: 0,
			sum: 9999,
			solution: {
				hosId: this.hosId,
				operationType:'lookOver',
				solutionNumber:data.solutionNumber
			}
		};
		this.isSpinning = true
		that.mainService
			.getFetchDataList("data", "solution", query)
			.subscribe((res) => {
				this.getFile()
				let data = res.list
				this.detailData = data
				this.richText = this.sanitizer.bypassSecurityTrustHtml(data[0].content);
				for(let i of data[0].solutionLogs){
					i.time = format(i.operationTime, 'yyyy-MM-dd HH:mm')
				}
				this.lookData = data[0]
				this.solutionLogs = data[0].solutionLogs
				this.stepLength = this.solutionLogs.length
				this.isSpinning = false
			});

	}

	// 编辑
	edit(e, data) {
	  e.stopPropagation();
	  this.router.navigateByUrl(`/repositoryManageAdd/${data.id}?type=edit`);
	}

	// 停用
	pauseModal = false;
	pause(e, data){
		e.stopPropagation();
		this.pauseModal = true;
		this.coopId = data.id;
	}

	// 确认停用
	confirmDel2() {
	  var that = this;
	  that.btnLoading = true;
		let data: any = {
			id:this.coopId,
			operationType: 'deactivate'
		};
		this.mainService
			.simplePost("updData", "solution", data)
			.subscribe((data) => {
				that.btnLoading = false;
				that.pauseModal = false;
				if (data.status == 200) {
					this.showPromptModal("停用", true, "");
				} else {
					this.showPromptModal("停用", false, data.msg);
				}
			});
	}

	hideDelModal2() {
	  this.pauseModal = false;
	}


	// 恢复
	renewModal = false;
	renew(e, data){
		e.stopPropagation();
		this.renewModal = true;
		this.coopId = data.id;
	}

	// 确认恢复
	confirmDel3() {
	  var that = this;
		that.btnLoading = true;
		let data: any = {
			id:this.coopId,
			operationType: 'recover'
		};
		this.mainService
			.simplePost("updData", "solution", data)
			.subscribe((data) => {
				that.btnLoading = false;
				that.renewModal = false;
				if (data.status == 200) {
					this.showPromptModal("恢复", true, "");
				} else {
					this.showPromptModal("恢复", false, data.msg);
				}
			});
	}

	hideDelModal3() {
	  this.renewModal = 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();
  }

  delModal: boolean = false; //删除模态框
  coopIds: any;
  coopFlag: any = false;
  /**
   *
   * @param e 事件对象
   * @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
      .coopTypeConfig(
        "rmvData",
        "solution",
         [that.coopId]
      )
      .subscribe((data) => {
        that.btnLoading = false;
        that.delModal = false;
        if (data.status==200) {
          that.showPromptModal("删除", true, "");
        } else {
          that.showPromptModal("删除", false, data.data[0].msg);
        }
      });
  }

  detail(e, data) {
    e.stopPropagation();
		this.router.navigateByUrl(`/dispensingDetail/${data.id}`);
  }

  // 人员边输边搜节流阀
  changeUser(e) {
    this.searchTimer(this.getUsers, e);
  }

  // 边输入边搜索节流阀
  searchTimer(fun, e) {
    this.isLoading = true;
    this.searchTimerSubject.next([fun, e]);
  }

  // 获取创建人
  isLoading:boolean = false;
  getUsers(e?) {
    let postData = {
      user: {
        name: e,
        hospital: { id: this.hosId },
        simpleQuery: true,
      },
      idx: 0,
      sum: 20,
    };
    this.isLoading = true;
    this.mainService
      .getFetchDataList("data", "user", postData)
      .subscribe((data) => {
        this.isLoading = false;
        this.createUserList = data.list;
      });
  }

}
