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 { NzMessageService, UploadFile, UploadXHRArgs } from "ng-zorro-antd";
import { Observable, Observer, Subject } from "rxjs";
import { debounceTime, filter } from "rxjs/operators";
import { HttpEventType, HttpEvent, HttpRequest, HttpResponse, HttpClient } from '@angular/common/http';
@Component({
  selector: "app-repository-manage-add",
  templateUrl: "./repository-manage-add.component.html",
  styleUrls: ["./repository-manage-add.component.less"],
})
export class RepositoryManageAddComponent implements OnInit {
	currentHospital; //当前院区
  @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.searchParentDeptSubject.pipe(debounceTime(500)).subscribe((e) => {
			this.isDeptLoading = true;
			this.getProduct(e[0]);
    });
		this.detailId = this.route.snapshot.params.id;
		this.optType = this.route.snapshot.queryParams.type  //upgrade:升级
		if(this.detailId==0){
			this.add = true //新增
		}else{
			this.add = false //编辑
		}
		this.getDicData()
		this.hosId = this.tool.getCurrentHospital().id;
    this.coopBtns = this.tool.initCoopBtns(this.route);
		this.currentHospital = this.tool.getCurrentHospital();
		this.initForm();
    this.getAllHospital();
  }
	detailData:any;
	solutionNumber;
	versionNumber;
	optType:null;
	classItem:null;
	detailId:null; //列表数据
	deptId:null; //选中的科室id
  listOfData: any[] = []; //表格数据
  promptContent: string; //操作提示框提示信息
  ifSuccess: boolean; //操作成功/失败
  promptInfo: string; //操作结果提示信息
  promptModalShow: boolean; //操作提示框是否展示
  modal: boolean = false; //新增/编辑模态框
	isContentShow: boolean = false; //显示富文本
  add: boolean; //true:新增；false:编辑
  validateForm: FormGroup; //新增/编辑表单
  coopId: number; //表格中执行操作的id
  department: number; //所属科室
	drug: number; //药品名称
	hosId: number;
	rowId:number; //清单id
	dateRange;//时间
  batchNumber; //批次号
  num; //编码
  deptalias; //别名
  type; //类型
  deptHandoverType; //类型
  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状态
	isSpinning: boolean = false; //页面loading状态
  deptPhones: any = []; //新添加的科室电话列表
  isAddDeptsPhone = true; //添加新的科室电话是否禁用
  deptsPhoneId = 1; //科室电话自增id
  allParentdepart: any = []; //所有的父级科室列表
  hospitals1: any = []; //科室列表
	buildingList: any = []; //楼栋列表
	deptList: any = []; //楼栋科室
	malfunctionData: any = []; //故障现象数据
	productData: any = []; //产品数据
	typeDic:any = []; //知识库状态字典
	fileData: UploadFile[] = [];//附件数据
	fileAllData:any[] = []; //附件数据
	building:''; //楼栋
	deptIndex:number; //选中index
  searchParentDeptSubject = new Subject();
  // 初始化增删改按钮
  coopBtns: any = {};
	deptName:null;
	detailContent:null;
  //搜索父级科室
	isDeptLoading = false;
	delGrantModal = false;
	showInsp = false;
  changeInp(e) {
    this.searchParentDeptSubject.next([e]);
  }

	// 获取详情
	getDetail(){
		this.isSpinning = true
		var that = this;
		let query = {
			idx: that.pageIndex - 1,
			sum: that.pageSize,
			solution: {
				hosId: this.hosId,
				id:this.detailId,
				operationType:'lookOver',
			}
		};

		that.mainService
			.getFetchDataList("data", "solution", query)
			.subscribe((res) => {
				this.getFile()
				let data = res.list[0]
				this.detailData = data
				this.solutionNumber = data.solutionNumber
				this.versionNumber = data.versionNumber
				this.detailContent = data.content || ''
				this.editOrData = data.content || ''
				let item = this.dicData.find(i=>i.id == this.detailData.type.id)
				if(item){
					this.classItem = item.value
				}
				this.validateForm.controls.title.setValue(data.title || '');
				this.validateForm.controls.content.setValue(data.content || '');
				this.validateForm.controls.repairVisible.setValue(data.repairVisible+'' || '');
				this.validateForm.controls.knowledgeClass.setValue(data.type.id || '');
				if(data.inspectionForm){
					this.validateForm.controls.polling.setValue(data.inspectionForm.id || '');
				}
				this.validateForm.controls.assetProductId.setValue(data.assetProductId || '');
				this.isSpinning = false
				this.isContentShow = true
			});
	}
	getFile(){
		this.mainService
			.getPreviewImage('solution', this.detailId)
			.subscribe((res:any)=> {
				if(res.data.length>0){
					this.fileAllData = res.data
					this.fileData = res.data.map(i=>{
						return{
							uid:i.id,
							name:i.name,
							token:i.token
						}
					})
				}else{
					this.fileAllData = []
					this.fileData = []
				}
			});
	}

	hideDelModal() {
	  this.delModal = false;
	}

	// 获取产品
	getProduct(name){
		let postData = {
		  assetProduct: {
		    hosId: this.hosId,
				name:name
		  },
		  idx: 0,
		  sum: 20,
		};
		this.mainService
		  .getFetchDataList("data", "assetProduct", postData)
		  .subscribe((result) => {
				setTimeout(_=>{
					this.isDeptLoading = false
					this.productData = result.list;
				},500)
		  });
	}

  // 获取所有院区
  getAllHospital() {
		this.getPolling()
		this.getProduct('')
		this.getMalfunction()
  }

	// 获取故障现象数据
	getMalfunction(){
    let { hospital, type } = this.tool.getHospitalOrDuty();
		if(type === 'hospital' || type === 'department'){
		  this.malfunctionData = [];
		  return;
		};
		let postData = {
			hasThird: 'true',
		  category: {
		    dutyIds: type === 'duty' ? hospital.id.toString()  : undefined,
		  },
		};
		this.mainService.incidentPost("listIncidentCategory", postData).subscribe(res => {
		  let incidentCategoryList = res.data || [];
		  incidentCategoryList = incidentCategoryList.map(v => ({...v, parentId: v.parent ? v.parent.id : undefined, label: v.category, value: v.id}));
		  let arr = this.tool.tranListToTreeDataLeaf(incidentCategoryList, undefined, "parentId");

			for(let i of arr){
				for(let t of i.children){
					for(let x of t.children){
						this.malfunctionData.push({
							name:x.mutiCategory,
							id:x.id
						})
					}
				}
			}

			if(this.detailData && this.detailData.categoryId){
				// let malfunctionId = this.tool.tranListToTreeDataFindIdsLeaf(this.malfunctionData,this.detailData.categoryId);
				this.validateForm.controls.malfunction.setValue(this.detailData.categoryId);
			}
		})
	}

	// 获取巡检列表
	pollingData = [];
	getPolling(){
		let data = {
		  idx: 0,
		  sum: 9999,
		  inspectionForm: {
		    hosId: this.hosId
		  },
		};
		this.mainService
		  .getFetchDataList("simple/data", "inspectionForm", data)
		  .subscribe((data) => {
		    if (data.status == 200) {
		      this.pollingData = data.list.filter(i=>i.status.name=='已发布');
		    }
		  });
	}

	// 获取知识分类字典
	dicData = [];
	getDicData(){
		this.mainService.getDictionary("list", "solution_type").subscribe((res) => {
			this.dicData = res
			if(!this.add){
				this.getDetail()
			}else{
				this.isContentShow = true
			}
			if(this.optType=='upgrade'){
				this.getDetail()
			}
		});
		this.mainService.getDictionary("list", "solution_status").subscribe((res) => {
			this.typeDic = res
		});
	}

	// 选择知识库分类
	radioChnage(e){
		let item = this.dicData.find(i=>i.id == this.validateForm.value.knowledgeClass)
		if(item){
			this.classItem = item.value
		}
	}

	hideGrantModal(){
		this.delGrantModal = false;
	}


	// 富文本内容
	editOrData=null;
	changeContent(data){
		this.editOrData = data
	}

	// 表单提交
	submitForm(type): void {
	  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;

		if(this.classItem==1){
			if(!this.validateForm.value.malfunction){
				this.message.error(`请选择关联故障现象`)
				return
			}
		}else if(this.classItem==2){
			if(!this.validateForm.value.polling){
				this.message.error(`请选择关联巡检表`)
				return
			}
		}
		let operationType = null
		if(this.optType=='edit'){
			operationType = 'edit'
		}else if(this.optType=='upgrade'){
			operationType = 'upgrade'
		}
	  let data = {
			title:this.validateForm.value.title,
			repairVisible:this.validateForm.value.repairVisible,
			content:this.editOrData?this.editOrData:null,
			id:'',
			hosId:this.hosId,
			inspectionForm:{
				id:'' //巡检
			},
			type:{
				id:this.validateForm.value.knowledgeClass
			},
			assetProductId:this.validateForm.value.assetProductId,
			categoryId:'', //故障
			buttonType:type==1?'confirm':'ts',
			operationType: operationType
	  };
		if(this.classItem==1){
			data.categoryId = this.validateForm.value.malfunction
			delete data.inspectionForm
		}else if(this.classItem==2){
			data.inspectionForm.id = this.validateForm.value.polling
			delete data.categoryId
		}else{
			delete data.inspectionForm
			delete data.categoryId
		}
		if(this.add){
			delete data.id
		}else{
			data.id = this.detailId
		}
		if(type==1){
			that.btnLoading1 = true;
		}else if(type==2){
			that.btnLoading2 = true;
		}else{
			that.btnLoading2 = true;
		}

	  that.mainService
	    .simplePost(this.add?"addData":"updData", "solution", data)
	    .subscribe((res) => {
				if(type==1){
					that.btnLoading1 = false;
				}else if(type==2){
					that.btnLoading2 = false;
				}else{
					that.btnLoading2 = false;
				}
				if(this.fileData.length>0){
					if (res.status == 200) {
						this.uploadFile(res.data.id)
					  that.showPromptModal("操作", true, "");
					} else {
					  that.showPromptModal("操作", false, res.msg);
					}
					that.hideModal();
				}else{
					if (res.status == 200) {
					  that.showPromptModal("操作", true, "");
					} else {
					  that.showPromptModal("操作", false, res.msg);
					}
					that.hideModal();
				}
	    });
	}

	// 上传图片
	uploadFile(id){
		let url = this.mainService.returnUploadUrl('solution', id);
		for(let i of this.fileData){//新上传的附件
			const formData = new FormData()
			let item = this.fileAllData.find(t=>t.id == i.uid) //之前的附件
			if(!item){
				formData.append('file', i as any);
				formData.append('filename', i.name);

				const req = new HttpRequest('POST', url, formData, {
					reportProgress: false,
					withCredentials: false
				});
				this.http.request(req).subscribe((res) => {

				});
			}
		}
	}

  // 新增弹框
  showModal() {
    this.add = true;
    this.isAddDeptsPhone = true;
    this.deptPhones = [];
  }
	// 返回
	back(){
		this.router.navigateByUrl(`/main/repositoryManage`);
	}

  hideModal() {
    this.modal = false;
  }
  // 初始化新增form表单
  initForm() {
		this.validateForm = this.fb.group({
		  title: [null, [Validators.required]],
			code: [null, []],
			version: [null, []],
			content: [null, []],
			assetProductId: [null,[]],
			repairVisible: ['1', [Validators.required]],
			knowledgeClass: [null, [Validators.required]],
			polling: [null,],
			malfunction:[null,],
		});
  }

	beforeUpload = (file: UploadFile) => {
		let index = file.name.lastIndexOf('.')
		let type = file.name.slice(index + 1)
		const isSize = file.size / 1024 / 1024 < 10;
		const isPic = (type === 'xlsx' || type === 'pdf' ||
		type === 'xls' || type === 'ppt' || type === 'pptx' ||
		type === 'txt' || type === 'doc' || type === 'docx');
		if (!isPic) {
			this.message.error('只能上传PDF、word、ppt、excel、txt等文件类型格式!');
			return false;
		}
		if (!isSize) {
		  this.message.error('文件大小不能大于10MB!');
		  return false;
		}
		this.fileData = this.fileData.concat(file);
		return false;
	};

	// 删除附件
	removeFile = (file:any) =>  {
		let item = this.fileAllData.find(i=>i.id == file.uid)
		let index = this.fileData.findIndex(i=>i.uid == file.uid)
		if(item){ //附件在数据库
			this.mainService
				.removeAttachment(file.token)
				.subscribe((res:any=[]) => {
					if (res.status == 200) {
						this.getFile()
					}
				});
		}else{//附件不在数据库
			if(index!=-1){
				this.fileData.splice(index, 1)
			}
		}

	}

	closeModel(){
		this.initForm();
		this.back()
	}

  // 展示信息提示框（con:提示信息，success:操作是否成功，promptInfo:操作结果提示信息）
  showPromptModal(con, success, promptInfo?) {
    this.promptModalShow = false;
    this.promptContent = con;
    this.ifSuccess = success;
    this.promptInfo = promptInfo;
    setTimeout(() => {
      this.promptModalShow = true;
    }, 100);
  }

  delModal: boolean = false; //删除模态框
  coopIds: any;
  coopFlag: any = false;

}
