package yem.wm.cm.htqs.form;

import java.util.ArrayList;
import java.util.EventObject;
import java.util.List;

import com.alibaba.fastjson.JSONObject;

import kd.bos.bill.AbstractBillPlugIn;
import kd.bos.bill.OperationStatus;
import kd.bos.context.RequestContext;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.dataentity.serialization.SerializationUtils;
import kd.bos.entity.datamodel.IDataModel;
import kd.bos.entity.datamodel.ListSelectedRow;
import kd.bos.entity.datamodel.events.PropertyChangedArgs;
import kd.bos.entity.operate.result.OperationResult;
import kd.bos.form.CloseCallBack;
import kd.bos.form.FormShowParameter;
import kd.bos.form.IFormView;
import kd.bos.form.ShowType;
import kd.bos.form.control.EntryGrid;
import kd.bos.form.control.SplitContainer;
import kd.bos.form.control.SplitDirection;
import kd.bos.form.control.events.ItemClickEvent;
import kd.bos.form.events.ClosedCallBackEvent;
import kd.bos.form.field.events.AfterF7SelectEvent;
import kd.bos.form.field.events.AfterF7SelectListener;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.print.api.PrintTask;
import kd.bos.print.api.PrintWork;
import kd.bos.print.core.service.PrtAttach;
import kd.bos.print.core.service.PrtAttach.AttachDetail;
import kd.bos.print.service.BosPrintServiceHelper;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.user.UserConfigServiceHelper;
import kd.bos.url.UrlService;
import org.apache.commons.lang3.StringUtils;
import yem.base.common.utils.YEM;

/**
 * 分屏打印
 * @description 表单插件 
 * @author longh
 * @date 2023年4月5日
 */
public class PrintPreviewFormPlugIn extends AbstractBillPlugIn  {

	@Override
	public void itemClick(ItemClickEvent evt) {
		super.itemClick(evt);
		String itemKey = evt.getItemKey();
		switch (itemKey) {
		case "yem_printpreview":
			this.clickPrintPreview();
			break;

		default:
			break;
		}
	}

	private void clickPrintPreview() {
		IFormView view = this.getView();
		IDataModel model = this.getModel();
		DynamicObject dataEntity = model.getDataEntity();//表单的根数据包
		String billstatus = dataEntity.getString("billstatus");
		if("A".equals(billstatus)) {
			OperationResult opResult = view.invokeOperation("save", YEM.getOptionNoMsg());
			if(!opResult.isSuccess()) {
				view.showTipNotification("保存失败。" + YEM.getOpMsg(opResult));
			}
		}
		String entityId = view.getEntityId();
		Object pkValue = dataEntity.getPkValue();
		//{"printlang":"zh_CN","templateid":"36CTUSI7KXWD","hSavePage":false,"vSavePage":false,"pageNumType":"1","pageSeparation":false}
		String tplId = "";
		String printLang = "";
		//获取打印设置的配置信息
		String setting = UserConfigServiceHelper.getSetting(RequestContext.get().getCurrUserId(), entityId + "_printsetting");
		if(setting != null) {
			JSONObject fromJsonString = SerializationUtils.fromJsonString(setting, JSONObject.class);
			if(fromJsonString != null) {
				tplId = fromJsonString.getString("templateid");//打印模板
				printLang = fromJsonString.getString("printlang");//打印语言：
			}
		}
		if(YEM.isEmpty(tplId)) {
			view.showTipNotification("没有设置打印模板，请在“打印”->“设置”中进行设置。");
		}else {
			ArrayList<Object> pkIds = new ArrayList<>();
			pkIds.add(pkValue);
			// 打印任务
			ArrayList<PrintTask> taskList = new ArrayList<>();
			PrintTask printTask = new PrintTask();
			printTask.setTplId(tplId);// 打印模板的id
			printTask.setPkIds(pkIds);
			printTask.setPrintType("billForm");// 打印对象的类型，是单据（billForm),报表（report)，还是动态表单(dynamic)
			printTask.setFormId(entityId);
			taskList.add(printTask);
			// 打印作业
			PrintWork printWork = new PrintWork();
			//设置打印语言
			printWork.setPrintLang(YEM.isEmpty(printLang) ? "zh_CN" : printLang);
			//生成文件的后缀格式
			printWork.setExpType("pdf");
			//打印作业
			printWork.setTaskList(taskList);
			//生成打印模板生成的pdf文件
			//找到pdf打印指令
			PrtAttach doPrint = BosPrintServiceHelper.doPrint(printWork);
			List<AttachDetail> attachDetails = doPrint.getAttachDetail();
			for (AttachDetail attachDetail : attachDetails) {
				String filePath = attachDetail.getFilePath();
				String previewUrl = UrlService.getAttachmentPreviewUrl(filePath);
				
				FormShowParameter showParameter = new FormShowParameter();
				showParameter.setStatus(OperationStatus.EDIT);
				showParameter.getOpenStyle().setShowType(ShowType.InContainer);
				showParameter.getOpenStyle().setTargetKey("yem_printpreview_right");
				showParameter.setSendToClient(true);
				showParameter.setFormId("bos_printpreview");
				showParameter.setCustomParam("src", previewUrl);
				view.showForm(showParameter);
				break;
			}
			splitSet(false);
		}
	}



	private void splitSet(boolean hide) {
		SplitContainer splitc = this.getControl("yem_splitprintpreview");
		if(splitc != null) {
			if(hide) {
				splitc.hidePanel(SplitDirection.right, hide);
			}else {
				splitc.hidePanel(SplitDirection.right, hide);
				splitc.setCollapse("yem_printpreview_right", hide);
			}
		}
	}
	
	@Override
	public void afterCreateNewData(EventObject e) {
		super.afterCreateNewData(e);
		splitSet(true);
	}
	
	@Override
	public void afterLoadData(EventObject e) {
		super.afterLoadData(e);
		splitSet(true);
	}
	
	@Override
	public void afterCopyData(EventObject e) {
		super.afterCopyData(e);
		splitSet(true);
	}


}
