package weaver.aiyh_pcn.copy_attachment;

import aiyh.utils.Util;
import aiyh.utils.mapUtil.ParaMap;
import aiyh.utils.sqlUtil.sqlResult.impl.PrepSqlResultImpl;
import aiyh.utils.zwl.common.ToolUtil;
import com.api.aiyh_pcn.copy_attachment.dao.DocTemplateDao;
import com.api.aiyh_pcn.copy_attachment.model.ConfigEmpty;
import org.h2.util.StringUtils;
import weaver.conn.RecordSet;
import weaver.hrm.User;
import weaver.interfaces.workflow.action.Action;
import weaver.soa.workflow.request.RequestInfo;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author EBU7-dev1-ayh
 * @create 2021/11/8 0008 15:38
 * baomixieyi
 */


public class CopyAttachmentSecretAction extends ToolUtil implements Action {
	private String attachmentTemplateId;
	private String isBrowseBox;
	@Override
	public String execute(RequestInfo requestInfo) {
		ToolUtil toolUtil = new ToolUtil();

		try {
			User user = requestInfo.getRequestManager().getUser();
			String billTableName = requestInfo.getRequestManager().getBillTableName();
			String requestId = requestInfo.getRequestid();
			String workflowId = requestInfo.getWorkflowid();
			RecordSet rs_1 = new RecordSet();
//		查询流程数据
			String query = "select * from " + billTableName + " where requestid = ?";
			toolUtil.writeErrorLog("进入保密协议action!");
			rs_1.executeQuery(query, requestId);
			Map<String, Object> requestData = Util.recordSet2Map(rs_1);
			toolUtil.writeErrorLog(requestData.toString());

//		查询配置表,获取配置数据
			String querySql = "select ufta.id,ufta.workflow_type,wftva.fieldname as template_field,  " +
					"wftvb.fieldname as attachment_field,wftv.fieldname as show_field, wftvb.id as attachment_field_id,  " +
					"ufta.is_template_show,ufta.model_table_name, ufta.model_field,wsl.selectvalue as show_value,  " +
					"wftv.tablename as show_table_name,wftva.tablename as template_table_name,wftvb.tablename as attachment_table_name,  " +
					"wsla.selectvalue as hidden_value from uf_temp_attachment as ufta  " +
					"left join workflow_selectitem as wsl on wsl.id = ufta.show_value " +
					"left join workflow_selectitem as wsla on wsla.id = ufta.hidden_value " +
					"left join workflow_field_table_view as wftv on wftv.id = ufta.show_field " +
					"left join workflow_field_table_view as wftva on wftva.id = ufta.template_field " +
					"left join workflow_field_table_view as wftvb on wftvb.id = ufta.attachment_field " +
					"where workflow_type in " +
					"(select id from workflow_base where activeVersionID in " +
					"(select activeVersionID  from workflow_base where id = ?) or id = ?) and attachment_type = ?";
			RecordSet rs = new RecordSet();
			rs.executeQuery(querySql, workflowId, workflowId, 1);
			ConfigEmpty configEmpty = null;
			while(rs.next()){
//			    id
				int id = Util.getIntValue(rs.getString("id"));
//			    显示值
				int showValue = Util.getIntValue(rs.getString("show_value"));
//			    隐藏值
				int hiddenValue = Util.getIntValue(rs.getString("hidden_value"));
//			    流程id
				String workflowType = rs.getString("workflow_type");
//			    模板字段
				String templateField = rs.getString("template_field");
//			    附件字段
				String attachmentField = rs.getString("attachment_field");
//			    是否用字段控制模板
				String isTemplateShow = rs.getString("is_template_show");
//			    模板建模表表名
				String modelTableName = rs.getString("model_table_name");
//			    控制模板显示与否的字段
				String showField = rs.getString("show_field");
//			    建模表福建模板字段
				String modelField = rs.getString("model_field");
//			    控制显示所在表
				String showTableName = rs.getString("show_table_name");
//			    模板字段所在表
				String templateTableName = rs.getString("template_table_name");
//			    附件字段所在表
				String attachmentTableName = rs.getString("attachment_table_name");
//			    附件字段id
				String attachmentFieldId = rs.getString("attachment_field_id");
				toolUtil.writeDebuggerLog("保密协议已经查询到数据!");

				configEmpty = ConfigEmpty.create()
						.id(id)
						.showValue(showValue)
						.hiddenValue(hiddenValue)
						.workflowType(workflowType)
						.templateField(templateField)
						.attachmentField(attachmentField)
						.isTemplateShow(isTemplateShow)
						.modelTableName(modelTableName)
						.showField(showField)
						.modelField(modelField)
						.showTableName(showTableName)
						.templateTableName(templateTableName)
						.attachmentTableName(attachmentTableName)
						.attachmentFieldId(attachmentFieldId)
						.builder();
				toolUtil.writeErrorLog("保密协议数据:" + configEmpty.toString());
//			    如果不控制是否使用模板,那就默认不添加保密协议
				if ("1".equals(isTemplateShow)) {
//				不使用模板
					toolUtil.writeErrorLog("不使用安全协议数据!因为不控制模板的使用!");
					return Action.SUCCESS;
				}
				String showFieldValue = String.valueOf(requestData.get(configEmpty.getShowField()));
//			不使用保密协议模板
				if (configEmpty.getShowValue() != Integer.parseInt(showFieldValue)) {
					toolUtil.writeErrorLog("不使用安全协议数据!因为不使用保密协议!");
					return Action.SUCCESS;
				}
			}
			if(configEmpty != null){
//			使用保密协议模板
				String docIds = copyFile(user, configEmpty,String.valueOf(requestData.get(configEmpty.getTemplateField())));
				toolUtil.writeErrorLog("复制完成文件id:" + docIds);
				if (StringUtils.isNullOrEmpty(docIds)) {
					requestInfo.getRequestManager().setMessageid("1");
//				TODO 修改htmlLabel
					requestInfo.getRequestManager().setMessagecontent(aiyh.utils.Util.getHtmlLabelName(-87783, user.getLanguage(), "保密协议复制失败,未能正确复制保密协议!"));
					return Action.FAILURE_AND_CONTINUE;
				}
				String fileIds = Util.null2String(rs_1.getString(configEmpty.getAttachmentField()));
				String[] split = fileIds.split(",");
				List<String> list = Arrays.stream(split).collect(Collectors.toList());
				String[] split1 = docIds.split(",");
				list.addAll(Arrays.stream(split1).collect(Collectors.toList()));

//			修改流程数据,将保密协议的docid更新到流程中
				PrepSqlResultImpl sqlResult = Util.createSqlBuilder().updateSql(billTableName, ParaMap.create().put(configEmpty.getAttachmentField(), String.join(",", list)),
						Util.createPrepWhereImpl().whereAnd("requestid").whereEqual(requestId));
				toolUtil.writeErrorLog("sql : " + sqlResult.getSqlStr() + "  参数: ---> " + sqlResult.getArgs());
				rs.executeUpdate(sqlResult.getSqlStr(), sqlResult.getArgs());
			}
		}catch (Exception e){
			toolUtil.writeErrorLog("出现错误: " + e);
		}
		return Action.SUCCESS;
	}

	public String copyFile(User user, ConfigEmpty configEmpty,String browseBoxId){
		ToolUtil toolUtil = new ToolUtil();
//		建模表名称  params.get("tableName")
		String tableName = String.valueOf(configEmpty.getModelTableName());
//		建模字段名 params.get("fieldName")
		String fieldName = String.valueOf(configEmpty.getModelField());
//		附件字段id  params.get("fileFieldId")
		String fileFieldId = String.valueOf(configEmpty.getAttachmentField());
//		配置id params.get("configId")
//		String configId = String.valueOf(configEmpty.getId());
		String configId;
		if("true".equals(isBrowseBox)){
			configId = browseBoxId;
		}else {
			configId = attachmentTemplateId;
		}
//		流程id params.get("workflowId")
		String workflowId = String.valueOf(configEmpty.getWorkflowType());
		DocTemplateDao docTemplateDao = new DocTemplateDao();
		int[] docIds = null;
		try{
			docIds = docTemplateDao.copyFile(user.getUID(), tableName, fieldName, configId);
		}catch(Exception e){
			toolUtil.writeErrorLog("复制文件出错: " + e);
			return null;
		}
		if(docIds == null){
			return null;
		}
		try{
			docTemplateDao.updateFileInfo(workflowId,fileFieldId,docIds);
		}catch(Exception e){
			toolUtil.writeErrorLog("复制文件更新权限和目录出错: " + e);
			return null;
		}
		toolUtil.writeDebuggerLog("数据更新成功!" + Arrays.toString(docIds));
		List<String> intList= Arrays.stream(docIds).boxed().collect(Collectors.toList())
				.stream().map(String::valueOf).collect(Collectors.toList());
		return String.join(",",intList);
	}

	public String getAttachmentTemplateId() {
		return attachmentTemplateId;
	}

	public void setAttachmentTemplateId(String attachmentTemplateId) {
		this.attachmentTemplateId = attachmentTemplateId;
	}

	public String getIsBrowseBox() {
		return isBrowseBox;
	}

	public void setIsBrowseBox(String isBrowseBox) {
		this.isBrowseBox = isBrowseBox;
	}
}