package com.hotent.portal.controller;

import java.io.File;
import java.io.IOException;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.hotent.base.enums.ResponseErrorEnums;
import com.hotent.base.exception.BaseException;
import com.hotent.base.feign.BpmModelFeignService;
import com.hotent.base.feign.BpmRuntimeFeignService;
import com.hotent.base.feign.FormFeignService;
import com.hotent.base.query.*;
import com.hotent.base.util.*;
import com.hotent.base.util.Base64;
import com.hotent.portal.model.AppDingModel;
import com.hotent.portal.model.AppModelList;
import com.hotent.sys.persistence.model.SysApp;
import com.hotent.sys.util.SysPropertyUtil;
import com.hotent.uc.api.impl.vo.BoDefVo;
import com.hotent.uc.api.impl.vo.FormDataTemplateVo;
import com.hotent.uc.api.impl.vo.FormVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import com.hotent.base.controller.BaseController;
import com.hotent.base.model.CommonResult;
import com.hotent.base.util.time.DateFormatUtil;
import com.hotent.portal.model.AppModel;
import com.hotent.portal.params.AppTree;
import com.hotent.portal.persistence.manager.AppModelManager;
import com.hotent.uc.api.impl.util.ContextUtil;
import com.hotent.uc.api.model.IUser;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

/**
 * 
 * <pre> 
 * 描述：移动端应用 控制器类
 * 构建组：x7
 * 作者:pangq
 * 邮箱:pangq@jee-soft.cn
 * 日期:2020-07-06 15:25:12
 * 版权：广州宏天软件股份有限公司
 * </pre>
 */
@RestController
@RequestMapping(value="/portal/appModel/v1")
@Api(tags="appModelController")
public class AppModelController extends BaseController<AppModelManager,AppModel>{
	@Resource
	AppModelManager appModelManager;
//	@Resource
//	FormManager formManager;
//	@Resource
//	FormDataTemplateManager formDataTemplateManager;
//	@Resource
//	FormController formController;
//	@Autowired
//	BoDefManager boDefManager;
//	@Resource
//	FormMetaManager formMetaManager;
	@Resource
	FormFeignService formFeignService;
	@Resource
	BpmModelFeignService bpmModelFeignService;
	@Resource
	BpmRuntimeFeignService bpmRuntimeFeignService;

   @Autowired
   private com.hotent.portal.persistence.manager.AppDingModelManager appDingModelManager;
	/**
	 * 移动端应用列表(分页条件查询)数据
	 * @param queryFilter
	 * @return
	 * @throws Exception 
	 * PageJson
	 * @exception 
	 */
	@PostMapping("/listJson")
	@ApiOperation(value="移动端应用数据列表", httpMethod = "POST", notes = "获取移动端应用列表")
	public PageList<AppModel> list(@ApiParam(name="queryFilter",value="查询对象")@RequestBody QueryFilter<AppModel> queryFilter) throws Exception{
		List<FieldSort> sorter = queryFilter.getSorter();
		sorter.add(new FieldSort("ID_", Direction.DESC));
		queryFilter.setSorter(sorter);

		//content是json格式,真正检索的是json里面的name
		for (QueryField oneQuery : queryFilter.getQuerys()) {
			if (oneQuery.getProperty().equals("content")) {
				oneQuery.setValue("name\":\"%"+oneQuery.getValue().toString()+"%\"");
			}
		}
		PageList<AppModel> pageList=appModelManager.query(queryFilter);
		pageList.getRows().stream().forEach(item->{
			List<AppDingModel> appDingModel=appDingModelManager.getDingApp(item.getPkVal(),"");
			if(appDingModel!=null&&appDingModel.size()>0){
				item.setDingFlag("1");
				item.setDingAppName(appDingModel.get(0).getDingAppName());
				item.setDingAppDesc(appDingModel.get(0).getDingAppDesc());
				item.setDingAppIcon(appDingModel.get(0).getDingAppIcon());
			}else{
				item.setDingFlag("0");
			}
		});
		return pageList;
	}
	
	@RequestMapping(value="getApp", method=RequestMethod.GET, produces = { "application/json; charset=utf-8" })
	@ApiOperation(value = "根据可以key获取App", httpMethod = "GET", notes = "根据可以key获取App,根据appname查询app")
	public List<AppTree> getApp(@ApiParam(name="typeKey", value="分类key", required = true)@RequestParam String typeKey,
								@RequestParam(name="appName", value="appName", required = false) String appName) throws Exception {
		return appModelManager.getApp(typeKey,appName);
	}

	@RequestMapping(value="getAppByNoAuth", method=RequestMethod.GET, produces = { "application/json; charset=utf-8" })
	@ApiOperation(value = "根据可以key获取App", httpMethod = "GET", notes = "根据可以key获取App,根据appname查询app")
	public List<AppTree> getAppByNoAuth(@ApiParam(name="typeKey", value="分类key", required = true)@RequestParam String typeKey,
								@RequestParam(name="appName", value="appName", required = false) String appName) throws Exception {
		return appModelManager.getAppByNoAuth(typeKey,appName);
	}


	/**
	 * 移动端应用明细页面
	 * @param id
	 * @return
	 * @throws Exception 
	 * ModelAndView
	 */
	@GetMapping(value="/getJson")
	@ApiOperation(value="移动端应用数据详情",httpMethod = "GET",notes = "移动端应用数据详情")
	public AppModel get(@ApiParam(name="id",value="业务对象主键", required = true)@RequestParam String id) throws Exception{
		return appModelManager.get(id);
	}
	
    /**
	 * 新增移动端应用
	 * @param appModel
	 * @throws Exception 
	 * @return
	 * @exception 
	 */
	@PostMapping(value="save")
	@ApiOperation(value = "新增,更新移动端应用数据", httpMethod = "POST", notes = "新增,更新移动端应用数据")
	public CommonResult<String> save(@ApiParam(name="appModel",value="移动端应用业务对象", required = true)@RequestBody AppModel appModel) throws Exception{
        return appModelManager.createOrUpdate(appModel);
	}

	@GetMapping(value="updateEnable/{id}")
	@ApiOperation(value = "更改应用中心状态", httpMethod = "POST", notes = "更改应用中心状态")
	public CommonResult<String> updateEnable(@PathVariable("id") String id) throws Exception {
		AppModel appModel = appModelManager.get(id);
		if (BeanUtils.isEmpty(appModel)){
			return new CommonResult<>(false,"根据ID无法查询到应用中心");
		}

		//判断是否需要 应用上下架审核
		String appPublishFlag = SysPropertyUtil.getByAlias("appPublishFlag");
		if("true".equals(appPublishFlag)) {
			String appAction = "0";
			if (appModel.getEnable().equals(0)) {
				appAction = "0";
			} else {
				appAction = "1";
			}

			//发起上下架审核流程
			IUser user = ContextUtil.getCurrentUser(); //获取当前用户
			ObjectNode startFlowParam = JsonUtil.getMapper().createObjectNode();
			startFlowParam.put("account", user.getAccount());
			startFlowParam.put("approval", true);
			startFlowParam.put("businessKey", "");
			startFlowParam.put("data", "");
			startFlowParam.put("defId", "");
			startFlowParam.put("flowKey", "yysjshlc");
			startFlowParam.put("formType", "");
			startFlowParam.put("proInstId", "");
			startFlowParam.put("startOrgId", "");
			startFlowParam.put("supportMobile", 0);

			ObjectNode datas = JsonUtil.getMapper().createObjectNode();
			ObjectNode vars = JsonUtil.getMapper().createObjectNode();
			vars.put("code", this.generateSerialNumber());
			vars.put("userId", user.getUserId());
			vars.put("userName", user.getUsername());
			vars.put("appId", appModel.getId());
			vars.put("appName", appModel.getName());
			vars.put("appDesc", "");
			vars.put("menuName", appModel.getTypeName());
			vars.put("type", String.valueOf(10 + Integer.valueOf(appModel.getMode())));
			vars.put("appType", "1");
			vars.put("appAction", appAction);
			String content = appModel.getContent();
			//1:站内地址 2:跳转网页地址 3:表单列表 4:图表 5:新建流程
			if("1".equals(appModel.getMode()) || "2".equals(appModel.getMode())) {
				vars.put("relName", content);
			} else if("3".equals(appModel.getMode())) {
				JsonNode node = JsonUtil.toJsonNode(content);
				vars.put("relName", node.get("name").textValue());
				vars.put("relKey", node.get("alias").textValue());
			} else if("4".equals(appModel.getMode()) || "5".equals(appModel.getMode())) {
				JsonNode node = JsonUtil.toJsonNode(content);
				vars.put("relId", node.get("id").textValue());
				vars.put("relName", node.get("name").textValue());
			}
			datas.set("qzdef_yysj", vars);
			startFlowParam.put("data", Base64.getBase64(datas.toString()));
			bpmRuntimeFeignService.start(startFlowParam);
			String message = appModel.getEnable().equals(0) ? "移动应用上架审核过程中。。。" : "移动应用下架审核过程中。。。";
			return new CommonResult<>(true,message);
		} else {
			if (appModel.getEnable().equals(0)) {
				appModel.setEnable(1);
			} else {
				appModel.setEnable(0);
			}
			appModelManager.update(appModel);
			return new CommonResult<>(true,"状态修改成功");
		}
	}

	public String generateSerialNumber() {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
		String timestamp = sdf.format(new Date());
		Random random = new Random();
		int randomNum = random.nextInt(900) + 100; // 生成100到999之间的随机数
		return timestamp + randomNum;
	}

	/**
	 * 批量删除移动端应用记录
	 * @param ids
	 * @throws Exception 
	 * @return
	 * @exception 
	 */
	@DeleteMapping(value="/remove")
	@ApiOperation(value = "批量删除移动端应用记录", httpMethod = "DELETE", notes = "批量删除移动端应用记录")
	public CommonResult<String> removes(@ApiParam(name="ids",value="业务主键数组,多个业务主键之间用逗号分隔", required = true)@RequestParam String...ids) throws Exception{
		appModelManager.removeByIds(ids);
		return new CommonResult<String>(true, "删除成功");
	}

	@RequestMapping(value="exportXml" ,method= RequestMethod.GET, produces = { "application/json; charset=utf-8" })
	@ApiOperation(value = "导出移动端应用xml", httpMethod = "GET", notes = "导出移动端应用xml")
	public void exportXml(HttpServletRequest request, HttpServletResponse response,
						  @ApiParam(name="ids",value="移动端应用id", required = true) @RequestParam String ids) throws Exception {
		response.setContentType("APPLICATION/OCTET-STREAM");
		if (BeanUtils.isNotEmpty(ids)) {
			String[] stringsIds = ids.split(",");
			List<String> list = Arrays.asList(stringsIds);
			String zipName = "ht_appModel_"+ DateFormatUtil.format(LocalDateTime.now(), "yyyy_MMdd_HHmmss");
			// 写XML
			Map<String, String> strXml = baseService.exportData(list);
			HttpUtil.downLoadFile(request, response, strXml,zipName);
		}
	}

	@RequestMapping(value = "import", method = RequestMethod.POST, produces = {"application/json; charset=utf-8"})
	@ApiOperation(value = "移动端应用导入", httpMethod = "POST", notes = "移动端应用导入")
	public CommonResult<String> importData(MultipartHttpServletRequest request, HttpServletResponse response) throws Exception {
		return appModelManager.importData(request,response);
	}

	/**
	 * 发布移动端应用为钉钉应用
	 * @param appDingModel
	 * @throws Exception
	 * @return
	 * @exception
	 */
	@PostMapping(value="/pushDingApp")
//	@ApiOperation(value = "发布移动端应用为钉钉应用", httpMethod = "POST", notes = "发布移动端应用为钉钉应用")
	public CommonResult<String> pushDingApp(@ApiParam(name="appDingModel",value="移动端应用业务对象", required = true)@RequestBody AppDingModel appDingModel) throws Exception{
		return appModelManager.pushDingApp(appDingModel);
	}
	/**
	 * 发布移动端应用为钉钉应用
	 * @param appDingModel
	 * @throws Exception
	 * @return
	 * @exception
	 */
	@GetMapping(value="/getDingUserByCode")
//	@ApiOperation(value = "发布移动端应用为钉钉应用", httpMethod = "POST", notes = "发布移动端应用为钉钉应用")
	public CommonResult<JsonNode> getDingUserByCode(@ApiParam(name="code",value="免登code", required = true)@RequestParam String code, @ApiParam(name="corpId",value="钉钉企业id", required = true)@RequestParam String corpId, @ApiParam(name="appId",value="移动端应用id", required = true)@RequestParam String appId) throws Exception{
		return appModelManager.getDingUserInfo(code,corpId,appId);
	}

	/**
	 * 发布移动端应用为钉钉应用
	 * @param
	 * @throws Exception
	 * @return
	 * @exception
	 */
	@GetMapping(value="/getMobileAppById")
//	@ApiOperation(value = "发布移动端应用为钉钉应用", httpMethod = "POST", notes = "发布移动端应用为钉钉应用")
	public AppModel getMobileAppById(@ApiParam(name="appId",value="移动端appId", required = true)@RequestParam String appId) throws Exception{
		return appModelManager.getAppById(appId);
	}

	@RequestMapping(value = "removeFullXml", method = RequestMethod.GET, produces = {"application/json; charset=utf-8"})
	@ApiOperation(value = "删除完整应用xml", httpMethod = "GET", notes = "删除完整应用xml")
	public CommonResult<String> removeFullXml(HttpServletRequest request, HttpServletResponse response,
											  @ApiParam(name = "ids", value = "应用id", required = true) @RequestParam String ids) throws Exception {
		if (BeanUtils.isEmpty(ids)) {
			throw new BaseException(ResponseErrorEnums.NO_PERMISSION, "缺少应用id，导出失败！");
		}
		String[] stringsIds = ids.split(",");
		if (stringsIds.length > 1) {
			throw new BaseException(ResponseErrorEnums.NO_PERMISSION, "仅支持单笔应用id导出，导出失败！");
		}

		try {
			String appId = stringsIds[0];
			AppModel appModel = appModelManager.get(appId);
			Integer appModelMode = appModel.getMode();
			String content = appModel.getContent();
			if(appModelMode!=2 && appModelMode!=3 && appModelMode!=5) {
				throw new BaseException(ResponseErrorEnums.NO_PERMISSION, "仅支持对跳转网页地址/表单列表/流程类型的应用进行删除，删除失败！");
			}

			if(appModelMode==2) { // 网页跳转
				appModelManager.removeByIds(appId);
			} else if(appModelMode==3) { //表单列表
				JsonNode contentNode = JsonUtil.toJsonNode(content);
				String alias = contentNode.get("alias").asText();
				ObjectNode formDataTemplateNode = formFeignService.getFormDataTemplateByAlias(alias);
				FormDataTemplateVo formDataTemplate = JsonUtil.toBean(formDataTemplateNode.toString(), FormDataTemplateVo.class);
				//FormDataTemplate formDataTemplate = formDataTemplateManager.getByAlias(alias);

				String formKey = formDataTemplate.getFormKey();
				String mobileFormAlias = formDataTemplate.getMobileFormAlias();
				FormVo bpmForm = null;
				if(StringUtil.isNotEmpty(formKey)) {
					ObjectNode bpmFormNode = formFeignService.getMainByFormKey(formKey);
					bpmForm = JsonUtil.toBean(bpmFormNode.toString(), FormVo.class);
				}
				//Form bpmForm = formManager.getMainByFormKey(formKey);
				FormVo mobileBpmForm = null;
				if(StringUtil.isNotEmpty(mobileFormAlias)) {
					ObjectNode mobileBpmFormNode = formFeignService.getMainByFormKey(mobileFormAlias);
					mobileBpmForm = JsonUtil.toBean(mobileBpmFormNode.toString(), FormVo.class);
				}
				//Form mobileBpmForm = formManager.getMainByFormKey(mobileFormAlias);
				List<String> listIds = new ArrayList<>();
				if(bpmForm!=null) {
					listIds.add(bpmForm.getId());
				}
				if(mobileBpmForm!=null) {
					listIds.add(mobileBpmForm.getId());
				}
				String[] aryIds = listIds.toArray(new String[0]);
				String bpmNames  = formFeignService.checkBpmForm(String.join(",", aryIds)); //检查是否绑定了流程
				//String bpmNames  = formController.checkBpmForm(aryIds); //检查是否绑定了流程
				if(StringUtil.isEmpty(bpmNames)){
					appModelManager.removeByIds(appId);
					formFeignService.removeFormDataTemplateByIds(formDataTemplate.getId());
					//formDataTemplateManager.removeByIds(formDataTemplate.getId());
					//删除mobile表单
					if(mobileBpmForm!=null) {
						String[] bpmFormIds = new String[]{mobileBpmForm.getId()};
						formFeignService.removeForm(String.join(",", bpmFormIds));
						//formManager.remove(bpmFormIds);
					}
					ArrayNode boIdArrayNode = formFeignService.getBODefIdByFormId(bpmForm.getDefId());
					List<JsonNode> boIds = JsonUtil.arrayToListByJsonNode(boIdArrayNode);
					//List<String> boIds = formMetaManager.getBODefIdByFormId(bpmForm.getDefId());
					String[] formIds = new String[]{bpmForm.getId()};
					formFeignService.removeForm(String.join(",", formIds));
					//formManager.remove(formIds);
					for (int i = 0; i < boIds.size(); i++) {
						JsonNode node = boIds.get(i);
						String boId = node.asText();
						//String boId = boIds.get(i);
						formFeignService.removeBODefByIds(boId);
						//boDefManager.removeByIds(boId);
					}
				}else{
					return new CommonResult(false, "删除失败："+bpmNames, null);
				}
			} else if(appModelMode==5) { // 流程
				JsonNode contentNode = JsonUtil.toJsonNode(content);
				String contentId = contentNode.get("id").asText();
				CommonResult<String> result = bpmModelFeignService.getFlowKeyByDefId(contentId);
				if(result==null || result.getState().equals(false) || !"200".equals(result.getErrorCode())) {
					throw new BaseException(ResponseErrorEnums.NO_PERMISSION, "未匹配到流程信息，导出失败！");
				}
				String contentAlias = result.getValue();
				ObjectNode objectNode = bpmModelFeignService.getProcDefByDefKey(contentAlias);
				String defId = objectNode.get("defId").asText();
				Map<String, Object> map = bpmModelFeignService.definitionData(defId);
				Map<String, String> pcFormMap = (LinkedHashMap)map.get("pcForm");
				Map<String, String> mobileFormMap = (LinkedHashMap)map.get("mobileForm");
				//删除流程
				String bpmIds = objectNode.get("id").asText();
				bpmModelFeignService.physicsRemoveAllVersionByIds(bpmIds);
				//删除应用
				appModelManager.removeByIds(appId);
				//删除mobile表单
				if(mobileFormMap!=null) {
					String mobileAlias = mobileFormMap.get("mobileAlias");
					ObjectNode mobileBpmFormNode = formFeignService.getMainByFormKey(mobileAlias);
					FormVo mobileBpmForm = JsonUtil.toBean(mobileBpmFormNode.toString(), FormVo.class);
					//Form mobileBpmForm = formManager.getMainByFormKey(mobileAlias);
					String[] bpmFormIds = new String[]{mobileBpmForm.getId()};
					formFeignService.removeForm(String.join(",", bpmFormIds));
					//formManager.remove(bpmFormIds);
				}
				//删除pc表单
				if(pcFormMap!=null) {
					String pcAlias = pcFormMap.get("pcAlias");
					ObjectNode bpmFormNode = formFeignService.getMainByFormKey(pcAlias);
					FormVo bpmForm = JsonUtil.toBean(bpmFormNode.toString(), FormVo.class);
					//Form bpmForm = formManager.getMainByFormKey(pcAlias);
					String[] aryIds = {bpmForm.getId()};

					ArrayNode boIdArrayNode = formFeignService.getBODefIdByFormId(bpmForm.getDefId());
					List<JsonNode> boIds = JsonUtil.arrayToListByJsonNode(boIdArrayNode);
					//List<String> boIds = formMetaManager.getBODefIdByFormId(bpmForm.getDefId());
					formFeignService.removeForm(String.join(",", aryIds));
					//formManager.remove(aryIds);
					for (int i = 0; i < boIds.size(); i++) {
						JsonNode node = boIds.get(i);
						String boId = node.asText();
						//String boId = boIds.get(i);
						formFeignService.removeBODefByIds(boId);
						//boDefManager.removeByIds(boId);
					}
				}
			}
			return new CommonResult<>(true, "删除应用成功");
		} catch (Exception e) {
			e.printStackTrace();
			return new CommonResult<>(false, "删除应用失败：" + e.getMessage());
		}
	}

	@RequestMapping(value = "exportFullXml", method = RequestMethod.GET, produces = {"application/json; charset=utf-8"})
	@ApiOperation(value = "导出完整应用xml", httpMethod = "GET", notes = "导出完整应用xml")
	public void exportFullXml(HttpServletRequest request, HttpServletResponse response,
							  @ApiParam(name = "ids", value = "应用id", required = true) @RequestParam String ids,
							  @ApiParam(name = "backupFlag", value = "备份标志", required = false) @RequestParam(required = false) boolean backupFlag) throws Exception {
		if (BeanUtils.isEmpty(ids)) {
			throw new BaseException(ResponseErrorEnums.NO_PERMISSION, "缺少应用id，导出失败！");
		}
		String[] stringsIds = ids.split(",");
		if(stringsIds.length>1) {
			throw new BaseException(ResponseErrorEnums.NO_PERMISSION, "仅支持单笔应用id导出，导出失败！");
		}

		String appId = stringsIds[0];
		AppModel appModel = appModelManager.get(appId);
		Integer appModelMode = appModel.getMode();
		String content = appModel.getContent();
		if(appModelMode!=2 && appModelMode!=3 && appModelMode!=5) {
			throw new BaseException(ResponseErrorEnums.NO_PERMISSION, "仅支持对跳转网页地址/表单列表/流程类型的应用进行导出，导出失败！");
		}

		Map<String,String> resultMap = new LinkedHashMap<>();
		List<String> appIdList = new ArrayList<>(Arrays.asList(appId));
		Map<String, String> mapApp = baseService.exportData(appIdList);
		resultMap.putAll(mapApp);

		if (BeanUtils.isNotEmpty(content) && content.startsWith("{") && content.endsWith("}")) {
			JsonNode contentNode = JsonUtil.toJsonNode(content);
			if(appModelMode==2) { //跳转网页地址

			} else if(appModelMode==3) { //表单列表
				String alias = contentNode.get("alias").asText();
				ObjectNode formDataTemplateNode = formFeignService.getFormDataTemplateByAlias(alias);
				FormDataTemplateVo formDataTemplate = JsonUtil.toBean(formDataTemplateNode.toString(), FormDataTemplateVo.class);
				//FormDataTemplate formDataTemplate = formDataTemplateManager.getByAlias(alias);
				String contentId = formDataTemplate.getId();

				List<String> formTemplateIdList = new ArrayList<>(Arrays.asList(contentId));
				String formTemplateIdListJson = JSONUtil.toJsonStr(formTemplateIdList);
				ObjectNode mapTemplateNode = formFeignService.exportDef(formTemplateIdListJson);
				Map mapTemplate = JsonUtil.toMap(mapTemplateNode.toString());
				//Map mapTemplate = formDataTemplateManager.exportDef(formTemplateIdList);
				resultMap.putAll(mapTemplate);

				String formKey = formDataTemplate.getFormKey();
				String mobileFormAlias = formDataTemplate.getMobileFormAlias();
				FormVo bpmForm = null;
				if(StringUtil.isNotEmpty(formKey)) {
					ObjectNode bpmFormNode = formFeignService.getMainByFormKey(formKey);
					bpmForm = JsonUtil.toBean(bpmFormNode.toString(), FormVo.class);
				}
				//Form bpmForm = formManager.getMainByFormKey(formKey);
				FormVo mobileBpmForm = null;
				if(StringUtil.isNotEmpty(mobileFormAlias)) {
					ObjectNode mobileBpmFormNode = formFeignService.getMainByFormKey(mobileFormAlias);
					mobileBpmForm = JsonUtil.toBean(mobileBpmFormNode.toString(), FormVo.class);
				}
				//Form mobileBpmForm = formManager.getMainByFormKey(mobileFormAlias);
				List<String> formIdList = new ArrayList<>();
				if(bpmForm!=null) {
					formIdList.add(bpmForm.getId());
				}
				if(mobileBpmForm!=null) {
					formIdList.add(mobileBpmForm.getId());
				}

				String formIdListJson = JSONUtil.toJsonStr(formIdList);
				ObjectNode mapFormNode = formFeignService.exportForms(formIdListJson);
				Map mapForm = JsonUtil.toMap(mapFormNode.toString());
				//Map mapForm = formManager.exportForms(formIdList,true, true);
				resultMap.putAll(mapForm);
			} else if(appModelMode==5) { // 流程
				String contentId = contentNode.get("id").asText();
				CommonResult<String> result = bpmModelFeignService.getFlowKeyByDefId(contentId);
				if(result==null || result.getState().equals(false) || !"200".equals(result.getErrorCode())) {
					throw new BaseException(ResponseErrorEnums.NO_PERMISSION, "未匹配到流程信息，导出失败！");
				}
				String contentAlias = result.getValue();
				Map mapFlow = bpmModelFeignService.getExportXmlByDefKey(contentAlias);
				resultMap.putAll(mapFlow);
			}
		}

		if(!backupFlag){
			String jsonStr = JSONUtil.toJsonStr(resultMap);
			resultMap = bpmModelFeignService.getExportXmlReplaceAlias(jsonStr);
		}
		response.setContentType("APPLICATION/OCTET-STREAM");
		String zipName = "ht_appModelFull_" + DateFormatUtil.format(LocalDateTime.now(), "yyyy_MMdd_HHmmss");
		HttpUtil.downLoadFile(request, response, resultMap, zipName);
	}

	@RequestMapping(value = "importFullXml", method = RequestMethod.POST, produces = {"application/json; charset=utf-8"})
	@ApiOperation(value = "应用复制完整导入", httpMethod = "POST", notes = "应用复制完整导入")
	public CommonResult<String> importFullXml(MultipartHttpServletRequest request, HttpServletResponse response) throws Exception {
		String unZipFilePath = null;
		try {
			MultipartFile file = request.getFile("file");
			String rootRealPath = Paths.get(FileUtil.getIoTmpdir(), "/attachFiles/unZip").toString();
			FileUtil.createFolder(rootRealPath, true);
			ZipUtil.unZipFile(file, rootRealPath);
			String name = file.getOriginalFilename();
			String fileDir = StringUtil.substringBeforeLast(name, ".");
			unZipFilePath = Paths.get(rootRealPath, fileDir).toString();

			if(!name.startsWith("ht_appModelFull")) {
				throw new BaseException(ResponseErrorEnums.NO_PERMISSION, "导入文件类型名称错误，导入失败！");
			}

			String boXmlStr = "";
			try {
				boXmlStr = FileUtil.readFile(Paths.get(unZipFilePath, "bo.xml").toString());
			} catch (Exception e) {}
			String formXmlStr = "";
			try {
				formXmlStr = FileUtil.readFile(Paths.get(unZipFilePath, "form.xml").toString());
			} catch (Exception e) {}
			String formRightsXml = "";
			try {
				formRightsXml = FileUtil.readFile(Paths.get(unZipFilePath, "formrights.xml").toString());
			} catch (Exception e) {}
			String sysAppsPortalXml = "";
			try {
				sysAppsPortalXml = FileUtil.readFile(Paths.get(unZipFilePath, "sysApps.portal.xml").toString());
			} catch (Exception e) {}
			String appModelsPortalXml = "";
			try {
				appModelsPortalXml = FileUtil.readFile(Paths.get(unZipFilePath, "appModels.portal.xml").toString());
			} catch (Exception e) {}
			String bpmdefsXml = "";
			try {
				bpmdefsXml = FileUtil.readFile(Paths.get(unZipFilePath, "bpmdefs.flow.xml").toString());
			} catch (Exception e) {}
			String formDataTemplatesXml = "";
			try {
				formDataTemplatesXml = FileUtil.readFile(Paths.get(unZipFilePath, "formDataTemplates.form.xml").toString());
			} catch (Exception e) {}

			ArrayNode boDefsNode = formFeignService.parseBoDefXml(boXmlStr);
			List<ObjectNode> boDefs = JsonUtil.arrayToList(boDefsNode);
			//List<BoDef> boDefs = boDefManager.parseXml(boXmlStr);
			for (int i = 0; i < boDefs.size(); i++) {
				ObjectNode boDefNode = boDefs.get(i);
				BoDefVo boDef = JsonUtil.toBean(boDefNode.toString(), BoDefVo.class);
				//BoDef boDef = boDefs.get(i);
				String alias = boDef.getAlias();

				ObjectNode boDefOldNode = formFeignService.getBODefByAlias(alias);
				BoDefVo boDefOld = JsonUtil.toBean(boDefOldNode.toString(), BoDefVo.class);
				//BoDef boDefOld = boDefManager.getByAlias(alias);
				if(boDefOld!=null) {
					throw new BaseException(ResponseErrorEnums.NO_PERMISSION, "导入文件建模已经存在，请删除后再导入，导入失败！");
				}
			}

			JSONObject json = JSONUtil.createObj();
			if (StringUtil.isNotEmpty(boXmlStr)) {
				json.set("boXmlStr", boXmlStr);
			}
			if (StringUtil.isNotEmpty(formXmlStr)) {
				json.set("formXmlStr", formXmlStr);
			}
			if (StringUtil.isNotEmpty(formRightsXml)) {
				json.set("formRightsXml", formRightsXml);
			}
			if (StringUtil.isNotEmpty(sysAppsPortalXml)) {
				json.set("sysAppsPortalXml", sysAppsPortalXml);
			}
			if (StringUtil.isNotEmpty(appModelsPortalXml)) {
				json.set("appModelsPortalXml", appModelsPortalXml);
			}
			if (StringUtil.isNotEmpty(bpmdefsXml)) {
				json.set("bpmdefsXml", bpmdefsXml);
			}
			if (StringUtil.isNotEmpty(formDataTemplatesXml)) {
				json.set("formDataTemplatesXml", formDataTemplatesXml);
			}

			CommonResult<String> message = bpmModelFeignService.importFullXml(json.toString());

			if(StringUtil.isNotEmpty(appModelsPortalXml)) {
				AppModelList list = (AppModelList) JAXBUtil.unmarshall(appModelsPortalXml, AppModelList.class);
				List<AppModel> appModelList = list.getAppModelList();
				for (AppModel appModel : appModelList) {
					Integer appModelMode = appModel.getMode();
					String content = appModel.getContent();
					if(appModelMode==5) { // 流程
						CommonResult<String> res = bpmModelFeignService.getBpmDefIdByXml(bpmdefsXml);
						String defId = res.getValue();
						JsonNode contentNode = JsonUtil.toJsonNode(content);
						String contentId = contentNode.get("id").asText();
						System.out.println(appModelsPortalXml);
						appModelsPortalXml = appModelsPortalXml.replaceAll("&quot;"+contentId+"&quot;", "&quot;"+defId+"&quot;");
						System.out.println(appModelsPortalXml);
					}
				}
				appModelManager.importDataByXml(appModelsPortalXml);
			}
			return message;
		} catch (Exception e) {
			e.printStackTrace();
			return new CommonResult<>(false, "导入失败：" + e.getMessage());
		} finally {
			if (StringUtil.isNotEmpty(unZipFilePath)) {
				File formDir = new File(unZipFilePath);
				if (formDir.exists()) {
					FileUtil.deleteDir(formDir);
				}
			}
		}
	}
}
