package com.muchinfo.mtp3century.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.muchinfo.mtp.proto.Common;
import com.muchinfo.mtp.proto.ShortMessageMtp1;
import com.muchinfo.mtp3century.service.ICommonService;
import com.muchinfo.mtp3century.service.INoticeService;
import com.muchinfo.mtp3century.utils.AjaxResult;
import com.muchinfo.mtp3common.enumtype.*;
import com.muchinfo.mtp3common.utils.CommonUtil;
import com.muchinfo.mtp3common.utils.EncryptionUtils;
import com.muchinfo.mtp3common.utils.SerialNumberUtils;
import com.muchinfo.mtp3common.utils.DateTimeUtils;
import com.muchinfo.mtp3common.vo.PageResult;
import com.muchinfo.mtp3common.vo.ProtoHelper;
import com.muchinfo.mtp3interface.mapper.*;
import com.muchinfo.mtp3pojos.entity.*;
import com.muchinfo.mtp3pojos.vo.notice.*;
import org.apache.commons.lang3.StringEscapeUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class NoticeServiceImpl implements INoticeService {

    private final Logger log = LoggerFactory.getLogger(this.getClass());
    @Resource
    private ICommonService iCommonService;
    @Resource
    private ISystemmanagerMapper iSystemmanagerMapper;
    @Resource
    private INoticemsgMapper iNoticemsgMapper;
    @Resource
    private IMsgreceiverMapper iMsgreceiverMapper;
    @Resource
    private IMemberrecvMapper iMemberrecvMapper;
    @Resource
    private IUseraccountMapper iUseraccountMapper;
    @Resource
    private SystemmanagerServiceImpl systemmanagerService;
    @Resource
    private ISmscollectionMapper iSmscollectionMapper;
    @Resource
    private ISmsparametersMapper iSmsparametersMapper;
    @Resource
    private RabbitTemplate rabbitTemplate;
    @Resource
    private ISiteColumnconfigMapper iSiteColumnconfigMapper;
    @Resource
    private IGzMemberinfoMapper iGzMemberinfoMapper;
    @Resource
    private ISiteColumndetailMapper iSiteColumndetailMapper;

    @Override
    public AjaxResult noticemsgadd(NoticeMsgAddParam param, HttpServletRequest request) throws ParseException {
        Systemmanager systemmanager = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("LOGINCODE", iCommonService.getUserLoginCode(request)));
        Noticemsg noticeMsg = new Noticemsg();
        BeanUtils.copyProperties(param, noticeMsg);
        noticeMsg.setCreatorid(systemmanager.getAutoid());
        noticeMsg.setCreatetime(new Date());
        noticeMsg.setEndtime(DateTimeUtils.parseDate(param.getEndtime()));
        noticeMsg.setScheduletime(DateTimeUtils.parseDate(param.getScheduletime()));
        noticeMsg.setPublisher(systemmanager.getAreauserid().toString());
        noticeMsg.setSentstatus(0);
        noticeMsg.setIsforcedisplay(0);

        /*
         * 1:全体广播
         * 如果是平台管理员发布的， 所有的投资者和管理员都能接收到消息，
         * 如果是会员管理员发的全体广播，改会员下的投资者和管理员能接收消息。
         * 2：按会员广播
         * 只有平台管理员才有此选项，选中会员管理员及下属投资者都可以接收消息
         * 3：按个人推送
         * 只推送给投资者
         * 4：按会员广播(仅会员)
         * 只有平台管理员才有此选项，只有选中会员管理员都可以接收消息（不包括其下属投资者）
         */
        if (SysEnums.SendTypeEnum.ALLSEND.getCode().equals(param.getSendtype())) {
            saveSendAll(noticeMsg);
        } else if (SysEnums.SendTypeEnum.MEMBERSEND.getCode().equals(param.getSendtype())) {
            String[] split = param.getMemberidlist().split(",");

            if (split.length <= 0) {
                return AjaxResult.error(Constants.Error_Code_Design, MessageType.MESSAGE_NOTICE_ERROR_CODE_01.getCode(), request.getHeader("Accept-Language"));
            }
            saveSendMember(noticeMsg, split);
        } else if (SysEnums.SendTypeEnum.PERSONSEND.getCode().equals(param.getSendtype())) {
            //3:当推送方式个人推送   消息接受者只有投资者  消息为一条
            noticeMsg.setUserid(param.getInvertorID());
            iNoticemsgMapper.insert(noticeMsg);
        } else if (SysEnums.SendTypeEnum.ONLYMEMBERSEND.getCode().equals(param.getSendtype())) {
            String[] split = param.getMemberidlist().split(",");

            if (split.length <= 0) {
                return AjaxResult.error(Constants.Error_Code_Design, MessageType.MESSAGE_NOTICE_ERROR_CODE_01.getCode(), request.getHeader("Accept-Language"));
            }
            saveSendOnlyMember(noticeMsg, split);
        } else if (SysEnums.SendTypeEnum.ALLUSER.getCode().equals(param.getSendtype())) {
            saveSendAllUser(noticeMsg);
        }
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"));
    }

    @Override
    public PageResult<NoticeMsgQueryResult> query(NoticeMsgQueryParam param, HttpServletRequest request) {
        Systemmanager systemmanager = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("LOGINCODE", iCommonService.getUserLoginCode(request)));
        //平台登陆  查所有
        if (systemmanager.getAreauserid() != 0) {
            if (StringUtils.isBlank(param.getPublisher())) {
                param.setPublisher(systemmanager.getAreauserid().toString());
            }
        }
        PageResult<NoticeMsgQueryResult> pageResult = new PageResult<>();
        IPage<NoticeMsgQueryResult> page = new Page<>(param.getPageNum(), param.getPageSize());
        IPage<NoticeMsgQueryResult> resultIPage = iNoticemsgMapper.query(page, param);
        pageResult.setCode(Constants.Success_Code_Design);
        pageResult.setMessage(AjaxResult.dealMsg(MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language")));
        pageResult.setPages(resultIPage.getPages());
        pageResult.setCurrent(resultIPage.getCurrent());
        pageResult.setTotal(resultIPage.getTotal());
        pageResult.setPageSize(resultIPage.getSize());
        pageResult.setData(resultIPage.getRecords());
        return pageResult;
    }

    @Override
    public AjaxResult<Noticemsg> noticeMsgDetail(Long msgId, HttpServletRequest request) {

        Noticemsg noticeMsg = iNoticemsgMapper.selectOne(new QueryWrapper<Noticemsg>().eq("autoid", msgId));

        Integer sendType = noticeMsg.getSendtype();
        Systemmanager user = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("autoid", noticeMsg.getCreatorid()));
        if (user != null) {
            noticeMsg.setCreatorName(user.getUsername());
        }
        if (noticeMsg.getAuditoruserid() != null) {
            user = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("autoid", noticeMsg.getAuditoruserid()));
            if (user != null) {
                noticeMsg.setAuditName(user.getUsername());
            }
        }
        //按会员发送
        if (SysEnums.SendTypeEnum.MEMBERSEND.getCode().equals(sendType)) {
            List<Memberrecv> userRecvs = iMemberrecvMapper.selectList(new QueryWrapper<Memberrecv>().eq("msgid", msgId));
            StringBuilder name = new StringBuilder();
            for (Memberrecv userRecv : userRecvs) {
                Useraccount organization = iUseraccountMapper.selectOne(new QueryWrapper<Useraccount>().eq("userid", userRecv.getMemberid()));
                if (organization == null) {
                    return AjaxResult.error(Constants.Error_Code_Design, MessageType.MESSAGE_NOTICE_ERROR_CODE_02.getCode(), request.getHeader("Accept-Language"));
                }
                name.append(organization.getAccountname()).append(",");
            }
            name = new StringBuilder(name.substring(0, name.length() - 1));
            noticeMsg.setMembername(name.toString());
        } else if (SysEnums.SendTypeEnum.PERSONSEND.getCode().equals(sendType)) {
            noticeMsg.setMembername(iUseraccountMapper.selectOne(new QueryWrapper<Useraccount>().eq("userid", noticeMsg.getUserid())).getAccountname());
        } else if (SysEnums.SendTypeEnum.ONLYMEMBERSEND.getCode().equals(sendType)) {
            //4当推送方式为按会员广播(仅会员)
            List<Msgreceiver> managerRecvs = iMsgreceiverMapper.selectList(new QueryWrapper<Msgreceiver>().eq("autoid", msgId));
            StringBuilder name = new StringBuilder();
            for (Msgreceiver managerRecv : managerRecvs) {
                Systemmanager systemManager = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("autoid", managerRecv.getManagerid()));
                Useraccount organization = iUseraccountMapper.selectOne(new QueryWrapper<Useraccount>().eq("userid", systemManager.getAreauserid()));
                if (organization == null) {
                    return AjaxResult.error(Constants.Error_Code_Design, MessageType.MESSAGE_NOTICE_ERROR_CODE_02.getCode(), request.getHeader("Accept-Language"));
                }
                name.append(organization.getAccountname()).append(",");
            }
            name = new StringBuilder(name.substring(0, name.length() - 1));
            noticeMsg.setMembername(name.toString());
        }
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"), noticeMsg);
    }

    @Override
    public AjaxResult delete(Long autoid, HttpServletRequest request) {
        iMemberrecvMapper.delete(new QueryWrapper<Memberrecv>().eq("msgid", autoid));
        iMsgreceiverMapper.delete(new QueryWrapper<Msgreceiver>().eq("autoid", autoid));
        iNoticemsgMapper.delete(new QueryWrapper<Noticemsg>().eq("autoid", autoid));
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"));
    }

    @Override
    public AjaxResult updateforcedisplay(Long msgId, Integer isforcedisplay, HttpServletRequest request) {
        Systemmanager user = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("LOGINCODE", iCommonService.getUserLoginCode(request)));
        Noticemsg msg = iNoticemsgMapper.selectOne(new QueryWrapper<Noticemsg>().eq("autoid", msgId));
        if (msg != null) {
            int oldValue = msg.getIsforcedisplay() == null ? 0 : msg.getIsforcedisplay();
            msg.setIsforcedisplay(isforcedisplay);

            iNoticemsgMapper.updateById(msg);

            //写操作日志
            systemmanagerService.writeOperateLog(SysConstants.NOTICEMSG_MANAGE, "设置/取消公告消息强制弹出：" + msg.getAutoid().toString(), user, "公告标题【" + msg.getTitle() + "】", Integer.toString(oldValue), isforcedisplay.toString());
        }
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"));
    }

    @Override
    public AjaxResult auditMsg(Long auditid, Integer auditflag, String msg, HttpServletRequest request) {
        Systemmanager user = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("LOGINCODE", iCommonService.getUserLoginCode(request)));
        Noticemsg noticeMsg = iNoticemsgMapper.selectOne(new QueryWrapper<Noticemsg>().eq("autoid", auditid));
        if (noticeMsg != null) {
            if (noticeMsg.getSentstatus() == 0) {
                if (auditflag == 1) {
                    noticeMsg.setSentstatus(1);
                } else {
                    noticeMsg.setSentstatus(2);
                }
                noticeMsg.setAudittime(new Date());
                noticeMsg.setAuditoruserid(user.getAutoid());
                if (msg != null) {
                    noticeMsg.setAuditremark(msg);
                }
                iNoticemsgMapper.updateById(noticeMsg);
            }
        }
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"));
    }

    @Override
    public PageResult<SmsQueryResult> smsquery(SmsQueryParam param, HttpServletRequest request) {
        Systemmanager systemmanager = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("LOGINCODE", iCommonService.getUserLoginCode(request)));
        //平台登录  查所有
        //经纪会员登录，要根据手机号码查投资者并且投资者所属当前登录经纪会员
        if (systemmanager.getAreauserid() != 1) {
            if (param.getUserid() == null) {
                param.setUserid(systemmanager.getAreauserid());
            }
        }
        if (StringUtils.isNotBlank(param.getRecvphone())) {
            // 有手机号时，加密后查询
            param.setRecvphone(EncryptionUtils.encryptByAES(param.getRecvphone()));
        }
        PageResult<SmsQueryResult> pageResult = new PageResult<>();
        IPage<SmsQueryResult> page = new Page<>(param.getPageNum(), param.getPageSize());
        IPage<SmsQueryResult> resultIPage = iNoticemsgMapper.smsquery(page, param);
        resultIPage.getRecords().forEach(a -> {
            if (!param.getSensitive().contains("2")) {
                a.setRecvphone(CommonUtil.unViewMobile(EncryptionUtils.decryptForAES(a.getRecvphone())));
                a.setFailedphone(CommonUtil.unViewMobile(EncryptionUtils.decryptForAES(a.getFailedphone())));

            } else {
                a.setRecvphone(EncryptionUtils.decryptForAES(a.getRecvphone()));
                a.setFailedphone(EncryptionUtils.decryptForAES(a.getFailedphone()));
            }
        });
        pageResult.setCode(Constants.Success_Code_Design);
        pageResult.setMessage(AjaxResult.dealMsg(MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language")));
        pageResult.setPages(resultIPage.getPages());
        pageResult.setCurrent(resultIPage.getCurrent());
        pageResult.setTotal(resultIPage.getTotal());
        pageResult.setPageSize(resultIPage.getSize());
        pageResult.setData(resultIPage.getRecords());
        return pageResult;
    }

    @Override
    public AjaxResult resend(Long msgid, HttpServletRequest request) {
        Smscollection con = iSmscollectionMapper.selectOne(new QueryWrapper<Smscollection>().eq("msgid", msgid));
        List<Smsparameters> params = iSmsparametersMapper.selectList(new QueryWrapper<Smsparameters>().eq("msgid", msgid));

        ShortMessageMtp1.ShortMsgSendReq.Builder smsbuilder = ShortMessageMtp1.ShortMsgSendReq.newBuilder();
        smsbuilder.setMsgType(2);
        smsbuilder.setPriority(2);
        smsbuilder.setScheduledTime("");
        smsbuilder.addRecvPhone(EncryptionUtils.decryptForAES(con.getRecvphone()));
        smsbuilder.setTemplateID(con.getTemplid().intValue());

        params.sort((Smsparameters o1, Smsparameters o2) ->
                o1.getOffset().compareTo(o2.getOffset()));

        params.forEach(p -> {
            smsbuilder.addParamValues(p.getParam());
        });

        Long uuid = SerialNumberUtils.getNewSerialNumberByFuncode(FunCodeConstants.FunCode_Trade_ShortMsgSendRsp);
        // 添加消息头
        Common.MessageHead.Builder headBuil = Common.MessageHead.newBuilder();
        headBuil.setFunCode(FunCodeConstants.FunCode_Trade_ShortMsgSendReq);
        headBuil.setUUID(uuid.toString());
        smsbuilder.setHeader(headBuil.build());
        byte[] body = ProtoHelper.getNTAS(smsbuilder.build().toByteArray(),
                FunCodeConstants.FunCode_Trade_ShortMsgSendReq);
        MessageProperties msgProperties = new MessageProperties();
        msgProperties.setHeader("messageType", "protoBuf");
        rabbitTemplate.send(SysConstants.RabbitShortMessage, new Message(body, msgProperties));
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"));
    }

    @Override
    public PageResult<ColumnQueryResult> columnquery(ColumnQueryParam param, HttpServletRequest request) {
        PageResult<ColumnQueryResult> pageResult = new PageResult<>();
        IPage<ColumnQueryResult> page = new Page<>(param.getPageNum(), param.getPageSize());
        IPage<ColumnQueryResult> resultIPage = iNoticemsgMapper.columnquery(page, param);
        resultIPage.getRecords().forEach(a -> {
            a.setCreatoruser(iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("autoid", a.getCreatorid())).getUsername());
        });
        pageResult.setCode(Constants.Success_Code_Design);
        pageResult.setMessage(AjaxResult.dealMsg(MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language")));
        pageResult.setPages(resultIPage.getPages());
        pageResult.setCurrent(resultIPage.getCurrent());
        pageResult.setTotal(resultIPage.getTotal());
        pageResult.setPageSize(resultIPage.getSize());
        pageResult.setData(resultIPage.getRecords());
        return pageResult;
    }

    @Override
    public AjaxResult dealcolumn(ColumnAddParam param, HttpServletRequest request) {
        Systemmanager systemmanager = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("LOGINCODE", iCommonService.getUserLoginCode(request)));
        if (param.getId() != null) {
            SiteColumnconfig temp = iSiteColumnconfigMapper.selectOne(new QueryWrapper<SiteColumnconfig>().eq("id", param.getId()));
            temp.setColumnname(param.getColumnname());
            temp.setColumntype(param.getColumntype());
            temp.setIsshow(param.getIsshow());
            temp.setSort(param.getSort());
            temp.setUpdatedate(new Date());
            temp.setModifierid(systemmanager.getAutoid());
            iSiteColumnconfigMapper.updateById(temp);
        } else {
            SiteColumnconfig config = new SiteColumnconfig();
            config.setColumnname(param.getColumnname());
            config.setColumntype(param.getColumntype());
            config.setIsshow(param.getIsshow());
            config.setSort(param.getSort());
            config.setCreaedate(new Date());
            config.setUpdatedate(new Date());
            config.setCreatorid(systemmanager.getAutoid());
            config.setModifierid(systemmanager.getAutoid());
            iSiteColumnconfigMapper.insert(config);
        }
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"));
    }

    @Override
    public AjaxResult<SiteColumnconfig> columnDetail(Long id, HttpServletRequest request) {
        SiteColumnconfig temp = iSiteColumnconfigMapper.selectOne(new QueryWrapper<SiteColumnconfig>().eq("id", id));
        temp.setModifieruser(iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("autoid", temp.getModifierid())).getUsername());
        temp.setCreatoruser(iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("autoid", temp.getCreatorid())).getUsername());
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"), temp);
    }

    @Override
    public AjaxResult columndelete(Long id, HttpServletRequest request) {
        iSiteColumnconfigMapper.delete(new QueryWrapper<SiteColumnconfig>().eq("id", id));
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"));
    }

    @Override
    public PageResult<ColumnSourceQueryResult> columnsourcequery(String smembername, Integer pageNum, Integer pageSize, HttpServletRequest request) {
        PageResult<ColumnSourceQueryResult> pageResult = new PageResult<>();
        IPage<ColumnSourceQueryResult> page = new Page<>(pageNum, pageSize);
        IPage<ColumnSourceQueryResult> resultIPage = iNoticemsgMapper.columnsourcequery(page, smembername);
        pageResult.setCode(Constants.Success_Code_Design);
        pageResult.setMessage(AjaxResult.dealMsg(MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language")));
        pageResult.setPages(resultIPage.getPages());
        pageResult.setCurrent(resultIPage.getCurrent());
        pageResult.setTotal(resultIPage.getTotal());
        pageResult.setPageSize(resultIPage.getSize());
        pageResult.setData(resultIPage.getRecords());
        return pageResult;
    }

    @Override
    public AjaxResult dealcolumnsource(ColumnSourceAddParam param, HttpServletRequest request) {
        if (param.getMemberid() == null) {
            GzMemberinfo entity = new GzMemberinfo();
            entity.setMemberid(param.getMemberid());
            entity.setMembername(param.getMembername());
            String tags = param.getMembertags();
            if (tags == null) {
                entity.setMembertags("");
            } else {
                //替换中文逗号为英文逗号
                entity.setMembertags(tags.replace("，", ","));
            }
            entity.setImageurl(param.getImageurl());
            entity.setUpdatetime(new Date());

            iGzMemberinfoMapper.insert(entity);
        } else {
            GzMemberinfo entity = iGzMemberinfoMapper.selectOne(new QueryWrapper<GzMemberinfo>().eq("memberid", param.getMemberid()));
            entity.setMembername(param.getMembername());
            String tags = param.getMembertags();
            if (tags == null) {
                entity.setMembertags("");
            } else {
                //替换中文逗号为英文逗号
                entity.setMembertags(tags.replace("，", ","));
            }
            entity.setImageurl(param.getImageurl());
            entity.setUpdatetime(new Date());
            iGzMemberinfoMapper.updateById(entity);
        }
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"));
    }

    @Override
    public AjaxResult columnsourcedelete(Long memberid, HttpServletRequest request) {
        iGzMemberinfoMapper.delete(new QueryWrapper<GzMemberinfo>().eq("memberid", memberid));
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"));
    }

    @Override
    public AjaxResult<GzMemberinfo> columnsourceDetail(Long memberid, HttpServletRequest request) {
        GzMemberinfo entity = iGzMemberinfoMapper.selectOne(new QueryWrapper<GzMemberinfo>().eq("memberid", memberid));
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"), entity);
    }

    @Override
    public PageResult<InforManQueryResult> informManquery(InforManQueryParam param, HttpServletRequest request) {
        PageResult<InforManQueryResult> pageResult = new PageResult<>();
        IPage<InforManQueryResult> page = new Page<>(param.getPageNum(), param.getPageSize());
        IPage<InforManQueryResult> resultIPage = iNoticemsgMapper.informManquery(page, param);
        pageResult.setCode(Constants.Success_Code_Design);
        pageResult.setMessage(AjaxResult.dealMsg(MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language")));
        pageResult.setPages(resultIPage.getPages());
        pageResult.setCurrent(resultIPage.getCurrent());
        pageResult.setTotal(resultIPage.getTotal());
        pageResult.setPageSize(resultIPage.getSize());
        pageResult.setData(resultIPage.getRecords());
        return pageResult;
    }

    @Override
    public AjaxResult<InformManinitMessage> informManinit(HttpServletRequest request) {
        InformManinitMessage message = new InformManinitMessage();
        List<SiteColumnconfig> siteColumnconfigs = iSiteColumnconfigMapper.selectList(new QueryWrapper<SiteColumnconfig>()
                .eq("columntype", SysEnums.columntype.getColumntypeString("information"))
                .eq("isshow", 1));
        List<GzMemberinfo> gzMemberinfos = iGzMemberinfoMapper.selectList(new QueryWrapper<>());
        message.setGzMemberinfo(gzMemberinfos);
        message.setSiteColumnconfig(siteColumnconfigs);
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"), message);
    }

    @Override
    public AjaxResult<SiteColumndetail> informDetail(Long id, HttpServletRequest request) {
        SiteColumndetail siteColumndetail = iSiteColumndetailMapper.selectOne(new QueryWrapper<SiteColumndetail>().eq("id", id));
        siteColumndetail.setColumnname(iSiteColumnconfigMapper.selectOne(new QueryWrapper<SiteColumnconfig>().eq("id", siteColumndetail.getColumnid())).getColumnname());
        if(siteColumndetail.getSrcid() != null){
            siteColumndetail.setSrcname(iGzMemberinfoMapper.selectOne(new QueryWrapper<GzMemberinfo>().eq("memberid", siteColumndetail.getSrcid())).getMembername());
        }
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"), siteColumndetail);
    }

    @Override
    public AjaxResult isshow(Long id, HttpServletRequest request) {
        SiteColumndetail temp = iSiteColumndetailMapper.selectOne(new QueryWrapper<SiteColumndetail>().eq("id", id));
        temp.setIsshow(temp.getIsshow() == 1 ? 0 : 1);
        iSiteColumndetailMapper.updateById(temp);
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"));
    }

    @Override
    public AjaxResult dealinform(SiteColumndetail param, HttpServletRequest request) {
        Systemmanager user = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("LOGINCODE", iCommonService.getUserLoginCode(request)));
        if (param.getId() == null) {
            SiteColumndetail config = new SiteColumndetail();
            BeanUtils.copyProperties(param, config);
            try {
                if (StringUtils.isNotBlank(param.getPublishdate2())) {
                    config.setPublishdate(DateTimeUtils.parseDate(config.getPublishdate2(),
                            DateTimeUtils.DATE_PATTERN));
                } else {
                    config.setPublishdate(new Date());
                }
            } catch (ParseException e) {
                log.error("SiteColumndetail 日期转换异常，请检查");
            }
            config.setContext(convertToHtml(config.getContext()));

            if (config.getHits() == null) {
                config.setHits(0L);
            }

            if (config.getUserid() == null) {
                config.setUserid(user.getAreauserid());
            }
            config.setCreaedate(new Date());
            config.setCreatorid(user.getAutoid());
            config.setUpdatedate(new Date());
            config.setModifierid(user.getAutoid());
            iSiteColumndetailMapper.insert(config);
        } else {
            SiteColumndetail temp = iSiteColumndetailMapper.selectOne(new QueryWrapper<SiteColumndetail>().eq("id", param.getId()));

            log.debug("updateSiteColumnDetail:");
            temp.setContext(convertToHtml(param.getContext()));
            temp.setTitle(param.getTitle());
            temp.setCoverimage(param.getCoverimage());
            temp.setAuthor(param.getAuthor());
            temp.setBrief(param.getBrief());
            temp.setIstop(param.getIstop());
            temp.setStatus(param.getStatus());
            temp.setUpdatedate(new Date());
            temp.setModifierid(user.getAutoid());
            temp.setIsshow(param.getIsshow());
            temp.setHits((param.getHits()) == null ? 0L : param.getHits());
            temp.setSrcid(param.getSrcid());
            try {
                if (StringUtils.isNotBlank(param.getPublishdate2())) {
                    temp.setPublishdate(DateTimeUtils.parseDate(param.getPublishdate2(),
                            DateTimeUtils.DATE_PATTERN));
                }
            } catch (ParseException e) {
                log.error("SiteColumndetail 日期转换异常，请检查");
            }
            iSiteColumndetailMapper.updateById(temp);
        }
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"));
    }

    @Override
    public AjaxResult auditinform(Long id, Integer flag, HttpServletRequest request) {
        SiteColumndetail temp = iSiteColumndetailMapper.selectOne(new QueryWrapper<SiteColumndetail>().eq("id", id));
        if (flag == 1) {
            temp.setStatus(20);
        } else {
            temp.setStatus(30);
        }

        iSiteColumndetailMapper.updateById(temp);
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"));
    }

    @Override
    public AjaxResult deleteinform(Long id, HttpServletRequest request) {
        iSiteColumndetailMapper.delete(new QueryWrapper<SiteColumndetail>().eq("id", id));
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"));
    }

    @Override
    public AjaxResult noticemsgedit(NoticeMsgAddParam addParam, HttpServletRequest request) throws ParseException {
        Noticemsg oldNoticeMsg = iNoticemsgMapper.selectOne(new QueryWrapper<Noticemsg>().eq("AUTOID", addParam.getAutoid()));
        oldNoticeMsg.setTitle(addParam.getTitle());
        oldNoticeMsg.setContent(addParam.getContent());
        oldNoticeMsg.setEndtime(DateTimeUtils.parseDate(addParam.getEndtime()));
        oldNoticeMsg.setScheduletime(DateTimeUtils.parseDate(addParam.getScheduletime()));
        iNoticemsgMapper.updateById(oldNoticeMsg);
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"));
    }

    @Override
    public AjaxResult invalid(Long auditid, HttpServletRequest request) {
        Systemmanager user = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("LOGINCODE", iCommonService.getUserLoginCode(request)));
        Noticemsg msg = iNoticemsgMapper.selectOne(new QueryWrapper<Noticemsg>().eq("AUTOID", auditid));
        if (msg != null) {
            // 3:提前失效
            Integer oldValue = msg.getSentstatus();
            msg.setSentstatus(3);
            iNoticemsgMapper.updateById(msg);

            //写操作日志
            systemmanagerService.writeOperateLog(SysConstants.NOTICEMSG_MANAGE, "提前失效公告：" + auditid.toString(), user, "公告标题【" + msg.getTitle() + "】", oldValue.toString(), "3");
        }
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"));
    }

    private void saveSendAllUser(Noticemsg noticeMsg) {
        iNoticemsgMapper.insert(noticeMsg);

        //查所有的全体交易商
        List<Useraccount> userAccountList = iUseraccountMapper.selectList(new QueryWrapper<Useraccount>().eq("usertype", SysEnums.SZDivideTargetType.INVESTOR.getCode()));
        if (CollectionUtils.isNotEmpty(userAccountList)) {
            for (Useraccount ua : userAccountList) {
                Msgreceiver mr = new Msgreceiver();
                mr.setAutoid(noticeMsg.getAutoid());
                mr.setManagerid(ua.getUserid());
                mr.setReadstatus(1);//消息状态  未阅读
                mr.setReceivertype(2);
                mr.setUpdatetime(new Date());
                iMsgreceiverMapper.insert(mr);
            }
        }
    }

    private void saveSendOnlyMember(Noticemsg noticeMsg, String[] split) {
        iNoticemsgMapper.insert(noticeMsg);

        for (String memberid : split) {
            //会员管理员   记录到管理端消息接收表
            Map<String, Object> maps = new HashMap<String, Object>();
            List<Systemmanager> users = iSystemmanagerMapper.selectList(new QueryWrapper<Systemmanager>()
                    .eq("managerstatus", SysEnums.SysStatus.ok.getCode())
                    .eq("areauserid", Long.valueOf(memberid)));
            addMsgreceiver(noticeMsg, users);
        }
    }

    private void saveSendMember(Noticemsg noticeMsg, String[] split) {
        iNoticemsgMapper.insert(noticeMsg);

        for (String memberid : split) {
            //会员   记录到会员消息接受表
            Memberrecv ur = new Memberrecv();
            ur.setMsgid(noticeMsg.getAutoid());
            ur.setMemberid(Long.valueOf(memberid));
            iMemberrecvMapper.insert(ur);
            //会员管理员   记录到管理端消息接收表
            List<Systemmanager> users = iSystemmanagerMapper.selectList(new QueryWrapper<Systemmanager>()
                    .eq("managerstatus", SysEnums.SysStatus.ok.getCode())
                    .eq("areauserid", Long.valueOf(memberid)));
            addMsgreceiver(noticeMsg, users);
        }
    }

    private void saveSendAll(Noticemsg noticeMsg) {
        iNoticemsgMapper.insert(noticeMsg);

        //查所有的管理端用户包括机构用户，平台用户，会员用户
        List<Systemmanager> users = iSystemmanagerMapper.selectList(new QueryWrapper<Systemmanager>().eq("managerstatus", SysEnums.SysStatus.ok.getCode()));
        addMsgreceiver(noticeMsg, users);
    }

    private void addMsgreceiver(Noticemsg noticeMsg, List<Systemmanager> users) {
        if (CollectionUtils.isNotEmpty(users)) {
            for (Systemmanager u : users) {
                Msgreceiver mr = new Msgreceiver();
                mr.setManagerid(u.getAutoid());
                mr.setAutoid(noticeMsg.getAutoid());
                mr.setReadstatus(1);//消息状态  未阅读
                mr.setReceivertype(1);
                iMsgreceiverMapper.insert(mr);
            }
        }
    }

    public String convertToHtml(String oriString) {
        String desString = StringEscapeUtils.unescapeHtml4(oriString);
        String ignorStr = "<p>&nbsp;</p>";
        if (desString != null) {
            desString = desString.replaceAll("(\\r\\n|\\r|\\n|\\n\\r)", "\n").trim();
            desString = desString.replaceAll("(\\\\r\\\\n|\\\\r|\\\\n|\\\\n\\\\r)", "\n").trim();
            desString = desString.replaceAll(ignorStr, "\n").trim();

            //删除最后的\n
            while (desString.endsWith("\n")) {
                desString = desString.substring(0, desString.length() - 1).trim();
            }

            //删除最后的ignorStr
            while (desString.endsWith(ignorStr)) {
                desString = desString.substring(0, desString.length() - ignorStr.length()).trim();
            }

//			desString =	desString.replaceAll("(\\n)", "<br />").trim();
        }
        return desString;
    }
}
