package com.seeyon.apps.jync_file.node;

import java.util.List;

import cn.hutool.log.Log;
import com.seeyon.apps.bip.constants.BipConstants;
import com.seeyon.apps.common.config.ICstConfigApi;
import com.seeyon.apps.common.workflow.constants.WorkFlowType;
import com.seeyon.apps.common.workflow.node.ACommonSuperNode;
import com.seeyon.apps.ext.workflow.vo.FieldDataVo;
import com.seeyon.apps.ext.workflow.vo.FormDataVo;
import com.seeyon.apps.ext.workflow.vo.SuperNodeContext;
import org.apache.commons.lang3.StringUtils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.seeyon.apps.jync_file.kit.PropKit;
import com.seeyon.apps.jync_file.util.HeaderUtil;
import com.seeyon.apps.jync_file.util.InterfaceListUtil;
import com.seeyon.apps.jync_file.util.ProtUtil;
import com.seeyon.cap4.form.bean.FormDataMasterBean;
import com.seeyon.ctp.common.AppContext;
import com.seeyon.ctp.common.SystemEnvironment;
import com.seeyon.ctp.common.ctpenumnew.manager.EnumManager;
import com.seeyon.ctp.common.filemanager.manager.AttachmentManager;
import com.seeyon.ctp.common.po.filemanager.Attachment;
import com.seeyon.v3x.services.form.FormFactory;

public class XinChouFileNode  extends ACommonSuperNode {

	private static final Log log = Log.get(XinChouFileNode.class);
	protected ICstConfigApi cstConfigApi = (ICstConfigApi) AppContext.getBean("cstConfigApi");

	@Override
	public String getNodeId() {
		return "xinChouFileNode";
	}
	@Override
	public String getNodeName() {
		return "OA薪酬分账单推送附件BIP付款单超级节点";
	}
	@Override
	public String getPluginId() {
		return BipConstants.getPluginId();
	}
	@Override
	public String getFormParse() {
		return "json";
	}
	@Override
	public WorkFlowType[] getTypes() {
		return new WorkFlowType[] {WorkFlowType.superNode};
	}

	private FormFactory formFactory;

	public FormFactory getFormFactory() {
		if (formFactory == null) {
			formFactory = (FormFactory) AppContext.getBean("formFactory");
		}
		return formFactory;
	}
	private AttachmentManager attachmentManager;

	public void setAttachmentManager(AttachmentManager attachmentManager) {
		this.attachmentManager = attachmentManager;
	}

	public AttachmentManager getAttachmentManagery() {
		if (attachmentManager == null) {
			attachmentManager = (AttachmentManager) AppContext.getBean("attachmentManager");
		}
		return attachmentManager;
	}

	private  EnumManager enumManagerNew;

	public void setEnumManagerNew(EnumManager enumManagerNew) {
		this.enumManagerNew = enumManagerNew;
	}

	public EnumManager getEnumManagerNew() {
		if (enumManagerNew == null) {
			enumManagerNew = (EnumManager) AppContext.getBean("enumManagerNew");
		}
		return enumManagerNew;
	}

	@Override
	public SuperNodeContext proceed(String request, FormDataVo formDataVo, FormDataMasterBean formDataMasterBean) throws Exception {
		//进入超级审核节点
		SuperNodeContext context = new SuperNodeContext();
		context.setNeedSave(true);
		System.out.println("开始处理单据XinChouFileNode");
		try {
			InterfaceListUtil interfaceListUtil = new InterfaceListUtil();
//        	获取OAtoken需要带入用户名请求
			String oatoken = interfaceListUtil.getToken("BIP2OA");
			log.info("token:"+oatoken);
			FieldDataVo retVo = formDataVo.getFieldData("BIP返回结果");
			String ret = "";
			if(retVo!= null){
				ret = retVo.getStringValue();
			}
			List<FormDataVo> subFormMap = formDataVo.getSubFormMap().get("分账明细表");
			int row = 0;
			StringBuffer stb = new StringBuffer();
			for(FormDataVo subFormDataVo:subFormMap) {
				row++;
				FieldDataVo isnumVo = subFormDataVo.getFieldData("附件是否上传");
				String isnum = "";
				if(isnumVo!=null){
					isnum = isnumVo.getStringValue();
				}
				FieldDataVo isFileVo = subFormDataVo.getFieldData("相关附件明细");
				if(isFileVo!=null && "0".equals(isnum)) {
					String isqushid = "";
					FieldDataVo isqushidVo = subFormDataVo.getFieldData("分账是否薪资代发");
					if(isqushidVo!=null) {
						isqushid = isqushidVo.getStringValue();
					}
					String isqush = "";
					if("".equals(isqushid)) {
						isqush = "是";
					}else {
						isqush = getEnumManagerNew().getEnumItem(Long.parseLong(isqushid)).getLabel();
					}
					if("是".equals(isqush)) {
						FieldDataVo subReferenceVo = subFormDataVo.getFieldData("相关附件明细");
						String subReference = "";
						if(subReferenceVo != null){
							subReference = subReferenceVo.getDbValue().toString();
						}
//                    	获取表单中附件的相关信息
						List<Long> attachmentIds = attachmentManager.getBySubReference(Long.parseLong(subReference));
						JSONArray jsonArray = new JSONArray();
						for (int i = 0 ; i < attachmentIds.size();i++) {
							Attachment attachment = attachmentManager.getAttachmentByFileURL(attachmentIds.get(i));
							Long fileUrl = attachment.getFileUrl();
							String filename = attachment.getFilename();
//                    		String[] fileType = filename.split("\\.");
							String fileType = filename.substring(filename.lastIndexOf(".")+1);
							String oaFileName =  filename.substring(0,filename.lastIndexOf("."));
							log.info(oaFileName);
//                    		调用接口下载文件,文件存放在指定的路径下
							String dowUrl = PropKit.getProp(PropKit.DOWURL)+"/"+fileUrl+"?fileName="+fileType+"&token="+oatoken;
							String str = SystemEnvironment.getApplicationFolder();
							String dowPath = str+"/jyncfile/"+filename;
							context.setUrl(dowUrl);
							context.setRequest(dowPath);
							String download = interfaceListUtil.download(dowUrl, dowPath);
							context.setResponse(download);
							JSONObject jsonObject = new JSONObject();
							jsonObject.put("name", oaFileName);
							jsonObject.put("type", fileType);
							jsonObject.put("url", PropKit.getProp(PropKit.JYNCFILE)+"/"+filename);
							jsonArray.add(jsonObject);
							log.info(jsonObject.toString());
						}
//                    	封装推送接口参数调用接口
						JSONObject headerer = HeaderUtil.getHeader();
						log.info("headerer:"+headerer);
						JSONObject jsonObject = new JSONObject();
						FieldDataVo billnoVo = subFormDataVo.getFieldData("分账单据流水号");
						String billno= "";
						if(billnoVo!=null){
							billno = billnoVo.getStringValue();
						}
						jsonObject.put("billno", billno);
						jsonObject.put("code", "FJ01");
						jsonObject.put("fileList", jsonArray);
						System.out.println(jsonObject);
						JSONObject res = ProtUtil.doPost(jsonObject, PropKit.getProp(PropKit.PAYBILLFILEURL), headerer);
						String  isStatus =  res.get("status").toString();
						if("1".equals(isStatus)) {
							stb.append("；\n第"+row+"行推送BIP付款结算单附件成功");
							System.out.println("第"+row+"行推送BIP付款结算单附件成功");
							log.info("第"+row+"行推送BIP付款结算单附件成功");
							formDataVo.getNewFieldDataMap().put("附件是否上传","1");
							context.success("第"+row+"行推送BIP付款结算单附件成功");
						}else {
							String msg = res.get("msg").toString();
							System.out.println(msg);
							context.back(msg);
							context.setErrMsg(msg);
							log.info("第"+row+"行数据推送BIP付款结算单附件失败,"+res.get("msg").toString());
							stb.append("；\n第"+row+"行推送BIP付款结算单附件失败,"+res.get("msg").toString());
							break;
						}
					}
				}
			}
			String[] rets = ret.split("；");
			String r = "";
			if(rets.length>1) {
				rets[rets.length-1] = stb.toString().substring(1,stb.length());
				r = StringUtils.join(rets, "；");
			}else {
				r = rets[0]+stb.toString();
			}
			formDataVo.getNewFieldDataMap().put("BIP返回结果", r);
		} catch (Exception e) {
			log.error("异常："+ e);
			e.printStackTrace();
			context.back("异常："+ e);
			context.setErrMsg("异常："+ e);
		}
		return context;
	}

}

