package com.hotent.portal.controller.openController;

import cn.hutool.json.JSONArray;
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.annotation.ApiGroup;
import com.hotent.base.annotation.OpenApi;
import com.hotent.base.constants.ApiGroupConsts;
import com.hotent.base.feign.BpmModelFeignService;
import com.hotent.base.feign.FormFeignService;
import com.hotent.base.feign.UCFeignService;
import com.hotent.base.jms.NoticeMessageType;
import com.hotent.base.jwt.JwtTokenHandler;
import com.hotent.base.model.CommonResult;
import com.hotent.base.query.PageBean;
import com.hotent.base.query.PageList;
import com.hotent.base.query.QueryFilter;
import com.hotent.base.query.QueryOP;
import com.hotent.base.util.JsonUtil;
import com.hotent.base.util.JwtUtil;
import com.hotent.base.util.StringUtil;
import com.hotent.base.util.UniqueIdUtil;
import com.hotent.base.vo.DataTemplateQueryVo;
import com.hotent.portal.model.AppModel;
import com.hotent.portal.model.MessageReceiver;
import com.hotent.portal.model.PortalNewsNotice;
import com.hotent.portal.model.SysMessage;
import com.hotent.portal.persistence.manager.AppModelManager;
import com.hotent.portal.persistence.manager.MessageReceiverManager;
import com.hotent.portal.persistence.manager.PortalNewsNoticeManager;
import com.hotent.portal.persistence.manager.SysMessageManager;
import com.hotent.sys.persistence.manager.SysAppManager;
import com.hotent.sys.persistence.model.SysApp;
import com.hotent.uc.api.impl.model.UserFacade;
import com.hotent.uc.api.impl.vo.BoDefVo;
import com.hotent.uc.api.impl.vo.FormDataTemplateVo;
import io.jsonwebtoken.Claims;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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.RestController;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;

/**
 * 三方厂家Api 系统消息和个人消息接口
 * @author: 梁宏锦
 * @date: 2024/05/29
 **/
@RestController
@Api(tags = "三方厂家Api 系统消息和个人消息接口")
@RequestMapping("/${openApi.prefix}/server/push/msginfo/")
@ApiGroup(group= {ApiGroupConsts.GROUP_PORTAL})
@OpenApi(moduleName = "系统消息和个人消息模块",function = "开放接口")
public class SysMessageApiController {
    private final Logger logger= LoggerFactory.getLogger(this.getClass());
    @Resource
    JwtTokenHandler jwtTokenHandler;
    @Resource
    SysMessageManager sysMessageManager;
    @Resource
    MessageReceiverManager messageReceiverManager;
    @Resource
    UCFeignService ucFeignService;
    @Resource
    SysAppManager sysAppManager;
    @Resource
    AppModelManager appModelManager;
    @Resource
    BpmModelFeignService bpmModelFeignService;
    @Resource
    PortalNewsNoticeManager portalNewsNoticeManager;
    @Resource
    FormFeignService formFeignService;

    //public static String Form_Template_SysMsg_Alias = "xxmb"; //模板消息 别名
    //public static String Form_Template_SysMsg_formKey = "qzdef_xxmb"; //模板消息 表单Key
    //public static String Form_Template_SysMsg_boAlias = "qzdef_xxmb"; //模板消息 boAlias

    /**
     * 推送系统消息
     * @param json 请求json数据
     */
    @RequestMapping(value="submitSysMsgInfo",method= RequestMethod.POST, produces = { "application/json; charset=utf-8" })
    @ApiOperation(value = "推送系统消息", httpMethod = "POST", notes = "推送系统消息")
    @OpenApi(description = "推送系统消息")
    public CommonResult<?> submitMsgInfo(HttpServletRequest request, @RequestBody JSONObject json) throws Exception {
        String token = JwtUtil.getToken(request);
        Claims claims = jwtTokenHandler.parseToken(token);

        String sysCode = (String) claims.get("sysCode");

        String subject = json.getStr("subject");
        String description = json.getStr("description");
        String content = json.getStr("content");
        String messageSourceType = json.getStr("messageSourceType");
        String messageParams = json.getStr("messageParams");
        String templateCode = json.getStr("templateCode");
        String templateData = json.getStr("templateData");
        String supportMobile = json.getStr("supportMobile");
        String messageUrl = json.getStr("messageUrl");
        String resourceId = json.getStr("resourceId");
        String appId = json.getStr("appId");
        String flowId = json.getStr("flowId");
        String appMobileId = json.getStr("appMobileId");
        String ownerSource = json.getStr("ownerSource");
        String ownerSourceId = json.getStr("ownerSourceId");
        String pushRule = json.getStr("pushRule");
        String templateId = "";
        String templateJson = "";

        if(StringUtil.isEmpty(subject)) {
            return new CommonResult<>(false, "消息主题不能为空");
        }
        if(StringUtil.isEmpty(description)) {
            return new CommonResult<>(false, "消息摘要信息不能为空");
        }
        if(StringUtil.isEmpty(messageSourceType)) {
            return new CommonResult<>(false, "消息类型不能为空");
        }
        //发帖来源类型 -1:平台 0:PC应用 1:移动应用 2:流程
        if(SysMessage.OWNER_SOURCE_APP_PC.equals(ownerSource)) {
            if(StringUtil.isEmpty(ownerSourceId)) {
                return new CommonResult<>(false, "PC应用Id不能为空");
            }
            SysApp sysApp = sysAppManager.getById(ownerSourceId);
            if(sysApp==null) {
                return new CommonResult<>(false, "未匹配到该应用");
            }
        } else if(SysMessage.OWNER_SOURCE_APP_MOBILE.equals(ownerSource)) {
            if(StringUtil.isEmpty(ownerSourceId)) {
                return new CommonResult<>(false, "移动应用Id不能为空");
            }
            AppModel appModel = appModelManager.getById(ownerSourceId);
            if(appModel==null) {
                return new CommonResult<>(false, "未匹配到该移动应用");
            }
        } else if(SysMessage.OWNER_SOURCE_FLOW.equals(ownerSource)) {
            if(StringUtil.isEmpty(ownerSourceId)) {
                return new CommonResult<>(false, "流程Id不能为空");
            }
            ObjectNode definition = bpmModelFeignService.getDefGet(ownerSourceId);
            if(definition==null) {
                return new CommonResult<>(false, "未匹配到该流程");
            }
        }

        //消息跳转类型 0:固定内容 1:跳转地址 2:资讯 3:PC应用 4:流程 5:移动应用 6:模板消息
        if(SysMessage.MESSAGE_SOURCE_TYPE_CONTENT.equals(messageSourceType)) {
            if(StringUtil.isEmpty(content)) {
                return new CommonResult<>(false, "消息内容不能为空");
            }
        } else if(SysMessage.MESSAGE_SOURCE_TYPE_URL.equals(messageSourceType)) {
            if(StringUtil.isEmpty(messageUrl)) {
                return new CommonResult<>(false, "消息跳转地址不能为空");
            }
        } else if(SysMessage.MESSAGE_SOURCE_TYPE_NEWS.equals(messageSourceType)) {
            if(StringUtil.isEmpty(resourceId)) {
                return new CommonResult<>(false, "消息资讯Id不能为空");
            }
            PortalNewsNotice notice = portalNewsNoticeManager.getById(resourceId);
            if(notice==null) {
                return new CommonResult<>(false, "未匹配到该消息资讯");
            }
        } else if(SysMessage.MESSAGE_SOURCE_TYPE_APP_PC.equals(messageSourceType)) {
            if(StringUtil.isEmpty(appId)) {
                return new CommonResult<>(false, "PC应用Id不能为空");
            }
            SysApp sysApp = sysAppManager.getById(appId);
            if(sysApp==null) {
                return new CommonResult<>(false, "未匹配到该应用");
            }
        } else if(SysMessage.MESSAGE_SOURCE_TYPE_FLOW.equals(messageSourceType)) {
            if(StringUtil.isEmpty(flowId)) {
                return new CommonResult<>(false, "流程Id不能为空");
            }
            ObjectNode definition = bpmModelFeignService.getDefGet(ownerSourceId);
            if(definition==null) {
                return new CommonResult<>(false, "未匹配到该流程");
            }
        } else if(SysMessage.MESSAGE_SOURCE_TYPE_APP_MOBILE.equals(messageSourceType)) {
            if(StringUtil.isEmpty(appMobileId)) {
                return new CommonResult<>(false, "移动应用Id不能为空");
            }
            AppModel appModel = appModelManager.getById(ownerSourceId);
            if(appModel==null) {
                return new CommonResult<>(false, "未匹配到该移动应用");
            }
        } else if(SysMessage.MESSAGE_SOURCE_TYPE_TEMPLATE.equals(messageSourceType)) {
            if(StringUtil.isEmpty(templateCode) || StringUtil.isEmpty(templateData)) {
                return new CommonResult<>(false, "模板Id或模板内容不能为空");
            }
            //根据别名获取模板信息
            //ObjectNode templateNode = formFeignService.getFormDataTemplateByAlias(Form_Template_SysMsg_Alias);
            //FormDataTemplateVo templateVo = JsonUtil.toBean(templateNode.toString(), FormDataTemplateVo.class);
            //读取模板信息
            List<Map<String, Object>> templateList = sysMessageManager.getSysMsgTempletByCode(templateCode);
            if(templateList==null || templateList.size()<=0) {
                return new CommonResult<>(false, "未匹配到该模板消息");
            }
            Map<String, Object> templateMap = templateList.get(0);
            templateId = (String)templateMap.get("ID_");

            ObjectNode templateNode =  JsonUtil.getMapper().createObjectNode();
            JSONObject jsonObject = JSONUtil.parseObj(templateData);
            List<Map<String, Object>> templateDetailList = sysMessageManager.getSysMsgTempletChildById(templateId);
            for (int i = 0; i < templateDetailList.size(); i++) {
                Map<String, Object> detail = templateDetailList.get(i);
                String key = (String)detail.get("F_blbm");
                String type = (String)detail.get("F_bllx");

                String val = jsonObject.getStr(key);
                String str = this.checkTempleteType(type, key, val);
                if(StringUtil.isNotEmpty(str)) {
                    return new CommonResult<>(false, "模板参数错误：" + str);
                }
                templateNode.put(key, val);
            }
            templateJson = templateNode.toString();

            //DataTemplateQueryVo dataTemplateVo = new DataTemplateQueryVo();
            //dataTemplateVo.setTemplateId(templateVo.getId());
            //QueryFilter queryFilter = QueryFilter.build().withPage(new PageBean(1,PageBean.WITHOUT_PAGE));
            //queryFilter.addFilter("F_mbbm", templateCode, QueryOP.EQUAL);
            //queryFilter.addFilter("F_del_flag", 0, QueryOP.EQUAL);
            //dataTemplateVo.setQueryFilter(queryFilter);
            //ObjectNode res = formFeignService.listDataTemplateJson(dataTemplateVo);
            //if(res==null) {
            //    return new CommonResult<>(false, "未匹配到模板信息");
            //}
            //PageList<Map<String, Object>> pageList = JsonUtil.toBean(res.toString(), PageList.class);
            //String id = "";
            //ObjectNode res = formFeignService.getFormByFormKeyAndBoAlias(
            //        Form_Template_SysMsg_formKey, Form_Template_SysMsg_boAlias, id,
            //        "get", "", Form_Template_SysMsg_Alias);
            //System.out.println(pageList.toString());

            //PageList<Map<String, Object>> pageList = res.getValue();
            //校验模板内容格式

        } else {
            return new CommonResult<>(false, "消息跳转类型错误");
        }

        String id = UniqueIdUtil.getSuid();
        SysMessage sysMessage = new SysMessage();
        sysMessage.setId(id);
        sysMessage.setSubject(subject);
        sysMessage.setDescription(description);
        sysMessage.setContent(content);
        sysMessage.setMessageType(messageSourceType);
        sysMessage.setMessageTag(SysMessage.MESSAGE_TAG_SYS);
        sysMessage.setOwnerId("-1");
        sysMessage.setOwner("系统");
        sysMessage.setMessageType(NoticeMessageType.INNER.key());
        sysMessage.setCanReply(SysMessage.iS_REPLY_NO);
        sysMessage.setIsPublic(SysMessage.iS_PUBLIC_YES);
        sysMessage.setCreateTime(LocalDateTime.now());
        sysMessage.setSysCode(sysCode);

        sysMessage.setOwnerSource(ownerSource);
        sysMessage.setOwnerSourceId(ownerSourceId);
        sysMessage.setMessageSourceType(messageSourceType);
        sysMessage.setMessageParams(messageParams);
        //消息跳转类型 0:固定内容 1:跳转地址 2:资讯 3:PC应用 4:流程 5:移动应用 6:模板消息
        if(SysMessage.MESSAGE_SOURCE_TYPE_CONTENT.equals(messageSourceType)) {
            sysMessage.setContent(content);
        } else if(SysMessage.MESSAGE_SOURCE_TYPE_URL.equals(messageSourceType)) {
            sysMessage.setSupportMobile(StringUtil.isEmpty(supportMobile)? "1": supportMobile);
            sysMessage.setMessageUrl(messageUrl);
        } else if(SysMessage.MESSAGE_SOURCE_TYPE_NEWS.equals(messageSourceType)) {
            sysMessage.setResourceId(resourceId);
        } else if(SysMessage.MESSAGE_SOURCE_TYPE_APP_PC.equals(messageSourceType)) {
            sysMessage.setAppId(appId);
        } else if(SysMessage.MESSAGE_SOURCE_TYPE_FLOW.equals(messageSourceType)) {
            sysMessage.setFlowId(flowId);
        } else if(SysMessage.MESSAGE_SOURCE_TYPE_APP_MOBILE.equals(messageSourceType)) {
            sysMessage.setAppMobileId(appMobileId);
        } else if(SysMessage.MESSAGE_SOURCE_TYPE_TEMPLATE.equals(messageSourceType)) {
            sysMessage.setTemplateId(templateId);
            sysMessage.setTemplateData(templateJson);
        }
        sysMessageManager.create(sysMessage);

        String sysMessageId = sysMessage.getId();
        return new CommonResult<>(true, "推送系统消息成功!", sysMessageId);
    }

    /**
     * 推送个人消息
     * @param json 请求json数据
     */
    @RequestMapping(value="submitUserMsgInfo",method= RequestMethod.POST, produces = {"application/json; charset=utf-8" })
    @ApiOperation(value = "推送个人消息", httpMethod = "POST", notes = "推送个人消息")
    @OpenApi(description = "推送个人消息")
    public CommonResult<?> submitUserMsgInfo(HttpServletRequest request, @RequestBody JSONObject json) throws Exception {
        String token = JwtUtil.getToken(request);
        Claims claims = jwtTokenHandler.parseToken(token);

        String sysCode = (String) claims.get("sysCode");

        String subject = json.getStr("subject");
        String description = json.getStr("description");
        String content = json.getStr("content");
        String messageSourceType = json.getStr("messageSourceType");
        String messageParams = json.getStr("messageParams");
        String templateCode = json.getStr("templateCode");
        String templateData = json.getStr("templateData");
        String supportMobile = json.getStr("supportMobile"); //是否支持手机表单 0:跳转全兼容(默认)  1:仅支持pc端跳转 2:仅支持移动端跳转 3:不跳转
        String messageUrl = json.getStr("messageUrl");
        String resourceId = json.getStr("resourceId");
        String appId = json.getStr("appId");
        String flowId = json.getStr("flowId");
        String appMobileId = json.getStr("appMobileId");
        String ownerSource = json.getStr("ownerSource");
        String ownerSourceId = json.getStr("ownerSourceId");
        String receiverId = json.getStr("receiverId");
        String pushRule = json.getStr("pushRule");
        String templateId = "";
        String templateJson = "";

        if(StringUtil.isEmpty(subject)) {
            return new CommonResult<>(false, "消息主题不能为空");
        }
        if(StringUtil.isEmpty(description)) {
            return new CommonResult<>(false, "消息摘要信息不能为空");
        }
        if(StringUtil.isEmpty(messageSourceType)) {
            return new CommonResult<>(false, "消息类型不能为空");
        }
        if(StringUtil.isEmpty(receiverId)) {
            return new CommonResult<>(false, "消息接收人id不能为空");
        }
        //发帖来源类型 -1:平台 0:PC应用 1:移动应用 2:流程
        if(SysMessage.OWNER_SOURCE_APP_PC.equals(ownerSource)) {
            if(StringUtil.isEmpty(ownerSourceId)) {
                return new CommonResult<>(false, "PC应用Id不能为空");
            }
            SysApp sysApp = sysAppManager.getById(ownerSourceId);
            if(sysApp==null) {
                return new CommonResult<>(false, "未匹配到该应用");
            }
        } else if(SysMessage.OWNER_SOURCE_APP_MOBILE.equals(ownerSource)) {
            if(StringUtil.isEmpty(ownerSourceId)) {
                return new CommonResult<>(false, "移动应用Id不能为空");
            }
            AppModel appModel = appModelManager.getById(ownerSourceId);
            if(appModel==null) {
                return new CommonResult<>(false, "未匹配到该移动应用");
            }
        } else if(SysMessage.OWNER_SOURCE_FLOW.equals(ownerSource)) {
            if(StringUtil.isEmpty(ownerSourceId)) {
                return new CommonResult<>(false, "流程Id不能为空");
            }
            ObjectNode definition = bpmModelFeignService.getDefGet(ownerSourceId);
            if(definition==null) {
                return new CommonResult<>(false, "未匹配到该流程");
            }
        }

        //消息跳转类型 0:固定内容 1:跳转地址 2:资讯 3:PC应用 4:流程 5:移动应用 6:模板消息
        if(SysMessage.MESSAGE_SOURCE_TYPE_CONTENT.equals(messageSourceType)) {
            if(StringUtil.isEmpty(content)) {
                return new CommonResult<>(false, "消息内容不能为空");
            }
        } else if(SysMessage.MESSAGE_SOURCE_TYPE_URL.equals(messageSourceType)) {
            if(StringUtil.isEmpty(messageUrl)) {
                return new CommonResult<>(false, "消息跳转地址不能为空");
            }
        } else if(SysMessage.MESSAGE_SOURCE_TYPE_NEWS.equals(messageSourceType)) {
            if(StringUtil.isEmpty(resourceId)) {
                return new CommonResult<>(false, "消息资讯Id不能为空");
            }
            PortalNewsNotice notice = portalNewsNoticeManager.getById(resourceId);
            if(notice==null) {
                return new CommonResult<>(false, "未匹配到该消息资讯");
            }
        } else if(SysMessage.MESSAGE_SOURCE_TYPE_APP_PC.equals(messageSourceType)) {
            if(StringUtil.isEmpty(appId)) {
                return new CommonResult<>(false, "PC应用Id不能为空");
            }
            SysApp sysApp = sysAppManager.getById(appId);
            if(sysApp==null) {
                return new CommonResult<>(false, "未匹配到该应用");
            }
        } else if(SysMessage.MESSAGE_SOURCE_TYPE_FLOW.equals(messageSourceType)) {
            if(StringUtil.isEmpty(flowId)) {
                return new CommonResult<>(false, "流程Id不能为空");
            }
            //DefaultBpmDefinition definition = defaultBpmDefinitionManager.getById(flowId);
            ObjectNode definition = bpmModelFeignService.getDefGet(ownerSourceId);
            if(definition==null) {
                return new CommonResult<>(false, "未匹配到该流程");
            }
        } else if(SysMessage.MESSAGE_SOURCE_TYPE_APP_MOBILE.equals(messageSourceType)) {
            if(StringUtil.isEmpty(appMobileId)) {
                return new CommonResult<>(false, "移动应用Id不能为空");
            }
            AppModel appModel = appModelManager.getById(ownerSourceId);
            if(appModel==null) {
                return new CommonResult<>(false, "未匹配到该移动应用");
            }
        } else if(SysMessage.MESSAGE_SOURCE_TYPE_TEMPLATE.equals(messageSourceType)) {
            if(StringUtil.isEmpty(templateCode) || StringUtil.isEmpty(templateData)) {
                return new CommonResult<>(false, "模板Id或模板内容不能为空");
            }
            //读取模板信息
            List<Map<String, Object>> templateList = sysMessageManager.getSysMsgTempletByCode(templateCode);
            if(templateList==null || templateList.size()<=0) {
                return new CommonResult<>(false, "未匹配到该模板消息");
            }
            Map<String, Object> templateMap = templateList.get(0);
            templateId = (String)templateMap.get("ID_");

            ObjectNode templateNode =  JsonUtil.getMapper().createObjectNode();
            JSONObject jsonObject = JSONUtil.parseObj(templateData);
            List<Map<String, Object>> templateDetailList = sysMessageManager.getSysMsgTempletChildById(templateId);
            for (int i = 0; i < templateDetailList.size(); i++) {
                Map<String, Object> detail = templateDetailList.get(i);
                String key = (String)detail.get("F_blbm");
                String type = (String)detail.get("F_bllx");

                String val = jsonObject.getStr(key);
                String str = this.checkTempleteType(type, key, val);
                if(StringUtil.isNotEmpty(str)) {
                    return new CommonResult<>(false, "模板参数错误：" + str);
                }
                templateNode.put(key, val);
            }
            templateJson = templateNode.toString();
        } else {
            return new CommonResult<>(false, "消息跳转类型错误");
        }

        CommonResult<JsonNode> res = ucFeignService.getUserById(receiverId); //
        if(res==null || !res.getState()) {
            return new CommonResult<>(false, "未匹配到该用户信息");
        }
        JsonNode jsonNode = res.getValue();
        UserFacade user = JsonUtil.toBean(jsonNode.toString(), UserFacade.class);

        String id = UniqueIdUtil.getSuid();
        SysMessage sysMessage = new SysMessage();
        sysMessage.setId(id);
        sysMessage.setSubject(subject);
        sysMessage.setDescription(description);
        sysMessage.setContent(content);
        sysMessage.setMessageType(messageSourceType);
        sysMessage.setMessageTag(SysMessage.MESSAGE_TAG_USER);
        sysMessage.setOwnerId("-1");
        sysMessage.setOwner("系统");
        sysMessage.setMessageType(NoticeMessageType.INNER.key());
        sysMessage.setCanReply(SysMessage.iS_REPLY_NO);
        sysMessage.setIsPublic(SysMessage.iS_PUBLIC_NO);
        sysMessage.setCreateTime(LocalDateTime.now());
        sysMessage.setSysCode(sysCode);

        sysMessage.setOwnerSource(ownerSource);
        sysMessage.setOwnerSourceId(ownerSourceId);
        sysMessage.setMessageSourceType(messageSourceType);
        sysMessage.setMessageParams(messageParams);
        sysMessage.setSupportMobile(StringUtil.isEmpty(supportMobile)? SysMessage.SUPPORT_MOBILE_ALL: supportMobile);
        //消息跳转类型 0:固定内容 1:跳转地址 2:资讯 3:PC应用 4:流程 5:移动应用 6:模板消息
        if(SysMessage.MESSAGE_SOURCE_TYPE_CONTENT.equals(messageSourceType)) {
            sysMessage.setContent(content);
        } else if(SysMessage.MESSAGE_SOURCE_TYPE_URL.equals(messageSourceType)) {
            sysMessage.setMessageUrl(messageUrl);
        } else if(SysMessage.MESSAGE_SOURCE_TYPE_NEWS.equals(messageSourceType)) {
            sysMessage.setResourceId(resourceId);
        } else if(SysMessage.MESSAGE_SOURCE_TYPE_APP_PC.equals(messageSourceType)) {
            sysMessage.setAppId(appId);
        } else if(SysMessage.MESSAGE_SOURCE_TYPE_FLOW.equals(messageSourceType)) {
            sysMessage.setFlowId(flowId);
        } else if(SysMessage.MESSAGE_SOURCE_TYPE_APP_MOBILE.equals(messageSourceType)) {
            sysMessage.setAppMobileId(appMobileId);
        } else if(SysMessage.MESSAGE_SOURCE_TYPE_TEMPLATE.equals(messageSourceType)) {
            sysMessage.setTemplateId(templateId);
            sysMessage.setTemplateData(templateJson);
        }
        sysMessageManager.create(sysMessage);
        String sysMessageId = sysMessage.getId();

        MessageReceiver receiver = new MessageReceiver();
        receiver.setId(UniqueIdUtil.getSuid());
        receiver.setMsgId(sysMessageId);
        receiver.setReceiverId(user.getId());
        receiver.setReceiver(user.getFullname());
        receiver.setReceiverType(MessageReceiver.TYPE_USER);
        messageReceiverManager.create(receiver);

        if("1".equals(pushRule) || "2".equals(pushRule)) {
            ObjectNode dingObj = JsonUtil.createObjectNode();
            dingObj.put("userId", user.getId());
            dingObj.put("todoId", sysMessageId);
            if (SysMessage.MESSAGE_SOURCE_TYPE_CONTENT.equals(messageSourceType)){
                dingObj.put("title", subject);
                dingObj.put("isPushType", SysMessage.SUPPORT_MOBILE_NO.toString());
                JsonNode resultNode = ucFeignService.sendDingMessage(JSONUtil.parseObj(dingObj.toString()));
                logger.info("dingResultNode:" + resultNode.toString());
            } else if (SysMessage.MESSAGE_SOURCE_TYPE_URL.equals(messageSourceType) || SysMessage.MESSAGE_SOURCE_TYPE_APP_PC.equals(messageSourceType) ||
                SysMessage.MESSAGE_SOURCE_TYPE_FLOW.equals(messageSourceType) || SysMessage.MESSAGE_SOURCE_TYPE_APP_MOBILE.equals(messageSourceType)){
                dingObj.put("title", subject);
                dingObj.put("isPushType", sysMessage.getSupportMobile());
                JsonNode resultNode = ucFeignService.sendDingMessage(JSONUtil.parseObj(dingObj.toString()));
                logger.info("dingResultNode:" + resultNode.toString());
            } else if(SysMessage.MESSAGE_SOURCE_TYPE_TEMPLATE.equals(messageSourceType)) {
                ArrayNode arrayNode = JsonUtil.createArrayNode();
                JsonNode jNode = JsonUtil.toJsonNode(templateJson);
                Iterator<Map.Entry<String, JsonNode>> fields = jNode.fields();
                while (fields.hasNext()) {
                    Map.Entry<String, JsonNode> entry = fields.next();
                    ObjectNode objectNode = JsonUtil.createObjectNode();
                    objectNode.put("key", entry.getKey());
                    objectNode.put("value", entry.getValue());
                    arrayNode.add(objectNode);
                }
                dingObj.set("formList", arrayNode);
                dingObj.put("isPushType", sysMessage.getSupportMobile());
                JsonNode resultNode = ucFeignService.sendDingMessage(JSONUtil.parseObj(dingObj.toString()));
                logger.info("dingResultNode:" + resultNode.toString());
            }
        }
        return new CommonResult<>(true, "推送个人消息成功!", sysMessageId);
    }

    /**
     * 删除系统或个人消息
     * @param json 请求json数据
     */
    @RequestMapping(value="deleteMsgInfo",method= RequestMethod.POST, produces = {"application/json; charset=utf-8" })
    @ApiOperation(value = "删除系统或个人消息", httpMethod = "POST", notes = "删除系统或个人消息")
    @OpenApi(description = "删除系统或个人消息")
    public CommonResult<?> deleteMsgInfo(HttpServletRequest request, @RequestBody JSONObject json) {
        String msgId = json.getStr("msgId");

        if(StringUtil.isEmpty(msgId)) {
            return new CommonResult<>(false, "消息id不能为空");
        }
        SysMessage sysMessage = sysMessageManager.getById(msgId);
        if(sysMessage==null) {
            return new CommonResult<>(false, "未匹配到该消息");
        }

        List list = new ArrayList();
        list.add(msgId);
        sysMessageManager.updateDelFlagByIds(list);

        return new CommonResult<>(true, "删除消息成功!");
    }

    /**
     * 模板参数校验
     * @param type 类型
     * @param key 别名
     * @param val 值
     */
    public String checkTempleteType(String type, String key, String val) {
        if("1".equals(type)) {
            //字符串（可数字、字母或符号组合） 32位以内数字、字母或符号
            if(val.length()>32) {
                return "【"+key+"】长度必须要控制在32位以内(数字、字母或符号)";
            }
        } else if("2".equals(type)) {
            //数字（只能数字，可带小数）32位以内数字
            if(val.length()>32) {
                return "【"+key+"】长度必须要控制在32位以内(数字、字母或符号)";
            }
            boolean flag = val.matches("-?\\d+(\\.\\d+)?");
            if(!flag) {
                return "【"+key+"】数值错误（只能数字，可带小数）";
            }
        } else if("3".equals(type)) {
            //时间（24小时制时间格式）例如：15:01，或：2019年10月01日 15:01
            if(val.length()==5) {
                SimpleDateFormat hourFormat = new SimpleDateFormat("HH:mm");
                try {
                    hourFormat.parse(val);
                } catch (ParseException e) {
                    return "【"+key+"】时间格式错误（24小时制时间格式 15:01）!";
                }
            } else if(val.length()==17){
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy年MM月dd日 HH:mm");
                try {
                    dateFormat.parse(val);
                } catch (ParseException e) {
                    return "【"+key+"】时间格式错误（24小时制时间格式 2019年10月01日 15:01）!";
                }
            } else {
                return "【"+key+"】时间格式错误!";
            }
        } else if("4".equals(type)) {
            //日期（年月日格式）例如：2019年10月01日
            if(val.length()==11){
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy年MM月dd日");
                try {
                    dateFormat.parse(val);
                } catch (ParseException e) {
                    return "【"+key+"】日期格式错误（24小时制时间格式 2019年10月01日）!";
                }
            } else {
                return "【"+key+"】日期格式错误!";
            }
        }
        return "";
    }
}
