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.NotifyMI1;
import com.muchinfo.mtp.proto.PublicMI1;
import com.muchinfo.mtp3century.service.ICommonService;
import com.muchinfo.mtp3century.service.IRedisInitService;
import com.muchinfo.mtp3century.service.ISendMsgService;
import com.muchinfo.mtp3century.service.ISystemSetUpService;
import com.muchinfo.mtp3century.utils.AjaxResult;
import com.muchinfo.mtp3century.utils.RedisServiceUtil;
import com.muchinfo.mtp3century.vo.TreeNode;
import com.muchinfo.mtp3common.enumtype.*;
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.I18nconfig;
import com.muchinfo.mtp3pojos.vo.systemsetup.*;
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.text.SimpleDateFormat;
import java.util.*;

@Service
public class SystemSetUpServiceImpl implements ISystemSetUpService {
    private final Logger log = LoggerFactory.getLogger(this.getClass());
    @Resource
    private ISystemmanagerMapper iSystemmanagerMapper;
    @Resource
    private ICommonService iCommonService;
    @Resource
    private ISystemparamMapper iSystemparamMapper;
    @Resource
    private RedisServiceUtil redisServiceUtil;
    @Resource
    private IErrorcodeMapper iErrorcodeMapper;
    @Resource
    private IMarketMapper iMarketMapper;
    @Resource
    private IMarketsectionMapper iMarketsectionMapper;
    @Resource
    private SystemmanagerServiceImpl systemmanagerService;
    @Resource
    private IMarketsectionconfignewMapper iMarketsectionconfignewMapper;
    @Resource
    private ISzdz2ImageconfigMapper iSzdz2ImageconfigMapper;
    @Resource
    private IWskhOpenaccountconfigMapper iWskhOpenaccountconfigMapper;
    @Resource
    private IDivisionMapper iDivisionMapper;
    @Resource
    private IUserinfoMapper iUserinfoMapper;
    @Resource
    private ISendMsgService iSendMsgService;
    @Resource
    private RabbitTemplate rabbitTemplate;
    @Resource
    private IMarketrunstepdetailMapper iMarketrunstepdetailMapper;
    @Resource
    private IEnumdicMapper iEnumdicMapper;
    @Resource
    private IEnumgroupMapper iEnumgroupMapper;
    @Resource
    private IEnumdicitemMapper iEnumdicitemMapper;
    @Resource
    private ICertificatetypeconfigMapper iCertificatetypeconfigMapper;
    @Resource
    private IRedisInitService iRedisInitService;

    @Override
    public PageResult<Systemparam> queryByPage(Integer pageNum, Integer pageSize, HttpServletRequest request) {
        Systemmanager systemmanager = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("LOGINCODE", iCommonService.getUserLoginCode(request)));
        IPage<Systemparam> page = new Page<>(pageNum, pageSize);
        QueryWrapper<Systemparam> wrapper = new QueryWrapper<>();
        if (systemmanager.getAutoid() > 0) {
            wrapper.eq("showflag", 1);
        }
        IPage<Systemparam> queryResultIPage = iSystemparamMapper.selectPage(page, wrapper);
        PageResult<Systemparam> result = new PageResult<>();
        result.setCode(Constants.Success_Code_Design);
        result.setMessage(AjaxResult.dealMsg(MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language")));
        result.setPages(queryResultIPage.getPages());
        result.setCurrent(queryResultIPage.getCurrent());
        result.setTotal(queryResultIPage.getTotal());
        result.setPageSize(queryResultIPage.getSize());
        result.setData(queryResultIPage.getRecords());
        return result;
    }

    @Override
    public AjaxResult dealParam(SystemParamUpdate sysparm, HttpServletRequest request) {

        log.debug("sysparam_code={},sysparam_value={}", sysparm.getParaCode(), sysparm.getParaValue());
        Systemmanager systemmanager = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("LOGINCODE", iCommonService.getUserLoginCode(request)));
        if (systemmanager.getReletype() != 1) {
            return AjaxResult.error(Constants.Error_Code_Design, MessageType.MESSAGE_ERROR_CODE_SYSTEM003.getCode(), request.getHeader("Accept-Language"));
        }
        Systemparam old = iSystemparamMapper.selectOne(new QueryWrapper<Systemparam>().eq("PARAMCODE", sysparm.getParaCode()));
        // 修改系统参数
        if (sysparm.getStatus() == 1) {
            updateSysParam(sysparm, systemmanager, old);
        } else {
            // 新增或修改终端参数
            if (Objects.isNull(old)) addTerminalSysParam(sysparm, systemmanager);
            else updateTerminalSysParam(sysparm, systemmanager, old);
        }
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"));
    }

    @Override
    public PageResult<Errorcode> queryErr(SystemErrorCodeParam param, HttpServletRequest request) {
        IPage<Errorcode> page = new Page<>(param.getPageNum(), param.getPageSize());
        IPage<Errorcode> queryResultIPage = iErrorcodeMapper.selectPage(page, new QueryWrapper<Errorcode>()
                .eq(StringUtils.isNotBlank(param.getErrorid()), "ERRORID", param.getErrorid())
                .like(StringUtils.isNotBlank(param.getErrorcode()), "ERRORCODE", param.getErrorcode())
                .like(StringUtils.isNotBlank(param.getDescription()), "DESCRIPTION", param.getDescription()));
        PageResult<Errorcode> result = new PageResult<>();
        result.setCode(Constants.Success_Code_Design);
        result.setMessage(AjaxResult.dealMsg(MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language")));
        result.setPages(queryResultIPage.getPages());
        result.setCurrent(queryResultIPage.getCurrent());
        result.setTotal(queryResultIPage.getTotal());
        result.setPageSize(queryResultIPage.getSize());
        result.setData(queryResultIPage.getRecords());
        return result;
    }

    @Override
    public AjaxResult dealErr(SystemErrorCodeParam param, HttpServletRequest request) {
        Errorcode entity = iErrorcodeMapper.selectOne(new QueryWrapper<Errorcode>().eq("ERRORID", param.getErrorid()));
        entity.setDescription(param.getDescription());
        iErrorcodeMapper.update(entity, new QueryWrapper<Errorcode>().eq("ERRORID", param.getErrorid()));
        Systemparam sp = iSystemparamMapper.selectOne(new QueryWrapper<Systemparam>().eq("PARAMCODE", SysConstants.SYSPARAM_ERRORCODE));
        if (Objects.nonNull(sp)) {
            sp.setParamvalue(String.valueOf(System.currentTimeMillis()));
            sp.setUpdatetime(new Date());
            iSystemparamMapper.update(sp, new QueryWrapper<Systemparam>().eq("PARAMCODE", SysConstants.SYSPARAM_ERRORCODE));
        }
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"));
    }

    @Override
    public PageResult<SystemMarketSectionResult> queryMarketSet(SystemMarketSectionParam param, HttpServletRequest request) {
        IPage<SystemMarketSectionResult> page = new Page<>(param.getPageNum(), param.getPageSize());
        IPage<SystemMarketSectionResult> resultIPage = iSystemmanagerMapper.queryMarketSet(page, param);
        PageResult<SystemMarketSectionResult> pageResult = new PageResult<>();
        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<SystemMarketSetDetail> marketSetDetail(Integer marketsectionid, HttpServletRequest request) {
        SystemMarketSetDetail detail = iSystemmanagerMapper.queryMarketSectionBean(marketsectionid);
        List<ListMarketSectionConfig> configs = iSystemmanagerMapper.queryMarketSectionConfigNewList(marketsectionid);
        detail.setConfigs(configs);
        List<I18nconfig> i18nconfigs = iSystemmanagerMapper.queryI18nConfigs();
        detail.setI18nconfigs(i18nconfigs);
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"), detail);
    }

    @Override
    public AjaxResult deletemarketSet(Integer marketsectionid, HttpServletRequest request) {
        iSystemmanagerMapper.deletemarketSet(marketsectionid);
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"));
    }

    @Override
    public AjaxResult<SystemMarketSetResult> querytrademodes(HttpServletRequest request, Integer editmarketsectionid, String selectedmarketids) {
        String[] splits = null;
        if (StringUtils.isNotBlank(selectedmarketids)) {
            splits = selectedmarketids.split(",");
        }
        List<SystemMarketSetResult> markets = iMarketMapper.queryTradeModeListNew(editmarketsectionid, splits);

        for (SystemMarketSetResult market : markets) {
            List<SystemMarketNameResult> results = iMarketMapper.querymarkets(market.getTrademode(), splits);
            market.setResults(results);
        }
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"), markets);
    }

    @Override
    public AjaxResult delmarket(SystemMarketSectionAddParam param, HttpServletRequest request) {
        Systemmanager systemmanager = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("LOGINCODE", iCommonService.getUserLoginCode(request)));
        if (param.getMarketsectionid() != null) {
            // 修改
            Marketsection marketSection = iMarketsectionMapper.selectOne(new QueryWrapper<Marketsection>().eq("marketsectionid", param.getMarketsectionid()));
            if (marketSection != null) {
                marketSection.setMarketsectionname(param.getMarketsectionname());
                marketSection.setOrderindex(param.getOrderindex());
                marketSection.setPictureurl(param.getPictureurl());
                marketSection.setRemark(param.getRemark());
                marketSection.setModifytime(new Date());
                marketSection.setModifierid(systemmanager.getAutoid());
                marketSection.setModifiersrc(1);
                marketSection.setIsvalid(1);
                marketSection.setMarketsectionnameen(param.getMarketsectionnameen());
                marketSection.setMarketsectionnamezhTw(param.getMarketsectionnamezhtw());
                marketSection.setMarketsectionnameth(param.getMarketsectionnameth());
                marketSection.setMarketsectionnamevi(param.getMarketsectionnamevi());
                iMarketsectionMapper.updateById(marketSection);

                // 删除 “MarketSectionConfigNew” 相关记录
                iMarketsectionconfignewMapper.delete(new QueryWrapper<Marketsectionconfignew>().eq("marketsectionid", marketSection.getMarketsectionid()));

                // 添加“MarketSectionConfigNew”表相关记录
                addConfigNew(marketSection.getMarketsectionid(), param);

                systemmanagerService.writeOperateLog(SysConstants.PART_CODE_ORGZ, "修改版块, id=" + systemmanager.getLogincode(), systemmanager, null, null, null);
            }

        } else {
            // 新增
            Marketsection m = new Marketsection();
            m.setMarketsectionname(param.getMarketsectionname());
            m.setOrderindex(param.getOrderindex());
            m.setRemark(param.getRemark());
            m.setPictureurl(param.getPictureurl());
            m.setCreatetime(new Date());
            m.setCreatorid(systemmanager.getAutoid());
            m.setCreatorsrc(1);
            m.setModifytime(new Date());
            m.setModifierid(systemmanager.getAutoid());
            m.setModifiersrc(1);
            m.setIsvalid(1);
            m.setMarketsectionnameen(param.getMarketsectionnameen());
            m.setMarketsectionnamezhTw(param.getMarketsectionnamezhtw());
            m.setMarketsectionnameth(param.getMarketsectionnameth());
            m.setMarketsectionnamevi(param.getMarketsectionnamevi());
            iMarketsectionMapper.insert(m);

            // 添加“MarketSectionConfigNew”表相关记录
            addConfigNew(m.getMarketsectionid(), param);

            systemmanagerService.writeOperateLog(SysConstants.PART_CODE_ORGZ, "新增版块, id=" + systemmanager.getLogincode(), systemmanager, null, null, null);
        }
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"));
    }

    @Override
    public PageResult<Szdz2Imageconfig> querypicture(SystemPictureSetParam param, HttpServletRequest request) {
        Systemmanager systemmanager = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("LOGINCODE", iCommonService.getUserLoginCode(request)));
        if (systemmanager.getReletype().intValue() != SysConstants.SYS_TYPE_MANAGE) {
            param.setAreauserid(systemmanager.getAreauserid());
        }
        IPage<Szdz2Imageconfig> page = new Page<>(param.getPageNum(), param.getPageSize());
        IPage<Szdz2Imageconfig> resultIPage = iSzdz2ImageconfigMapper.selectPage(page, new QueryWrapper<Szdz2Imageconfig>()
                .eq(param.getImagetype() != null, "imagetype", param.getImagetype())
                .eq(param.getIsshow() != null, "isshow", param.getIsshow())
                .eq(param.getAreauserid() != null, "areauserid", param.getAreauserid())
                .like(StringUtils.isNotBlank(param.getTitle()), "title", param.getTitle()));
        PageResult<Szdz2Imageconfig> pageResult = new PageResult<>();
        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<Szdz2Imageconfig> pictureDetail(Integer configid, HttpServletRequest request) {
        Szdz2Imageconfig imageconfig = iSzdz2ImageconfigMapper.selectOne(new QueryWrapper<Szdz2Imageconfig>()
                .eq("configid", configid));
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"), imageconfig);
    }

    @Override
    public AjaxResult dealpicture(SystemPictureDealParam vo, HttpServletRequest request) {
        Systemmanager user = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("LOGINCODE", iCommonService.getUserLoginCode(request)));
        if (vo.getConfigid() != null) {
            Szdz2Imageconfig sic = iSzdz2ImageconfigMapper.selectOne(new QueryWrapper<Szdz2Imageconfig>()
                    .eq("configid", vo.getConfigid()));
            sic.setTitle(vo.getTitle());
            sic.setImagepath(vo.getImagepath());

            sic.setUrltype(vo.getUrltype());

            if (vo.getUrltype() == 1 || vo.getUrltype() == 4 || vo.getUrltype() == 5) {
                sic.setUrl(vo.getUrl());
            } else if (vo.getUrltype() == 2) {
                sic.setUrl(vo.getUrl2());
            }
            sic.setSort(vo.getSort());
            sic.setIsshow(vo.getIsshow());
            sic.setUpdatedate(new Date());
            sic.setModifierid(user.getAutoid());
            sic.setImagedetailpath(vo.getImagedetailpath());
            iSzdz2ImageconfigMapper.updateById(sic);
        } else {
            Szdz2Imageconfig sic = new Szdz2Imageconfig();
            sic.setImagetype(1);
            sic.setTitle(vo.getTitle());
            sic.setImagepath(vo.getImagepath());
            sic.setUrltype(vo.getUrltype());
            if (vo.getUrltype() == 1 || vo.getUrltype() == 4 || vo.getUrltype() == 5) {
                sic.setUrl(vo.getUrl());
            } else if (vo.getUrltype() == 2) {
                sic.setUrl(vo.getUrl2());
            }

            sic.setSort(vo.getSort());
            sic.setIsshow(vo.getIsshow());
            sic.setCreatedate(new Date());
            sic.setCreatorid(user.getAutoid());
            sic.setUpdatedate(new Date());
            sic.setModifierid(user.getAreauserid());
            sic.setAreauserid(user.getAreauserid());
            sic.setImagedetailpath(vo.getImagedetailpath());
            iSzdz2ImageconfigMapper.insert(sic);

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

    @Override
    public AjaxResult deletepicture(Integer configid, HttpServletRequest request) {
        iSzdz2ImageconfigMapper.delete(new QueryWrapper<Szdz2Imageconfig>()
                .eq("configid", configid));
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"));
    }

    @Override
    public AjaxResult<WskhConfigResult> oaconfig(HttpServletRequest request) {
        List<WskhOpenaccountconfig> list = iWskhOpenaccountconfigMapper.selectList(new QueryWrapper<>());
        List<WskhConfigResult> results = new ArrayList<>();
        list.forEach(p -> {
            WskhConfigResult result = new WskhConfigResult();
            result.setConfigid(p.getConfigid());
            result.setConfigvalue(p.getConfigvalue());
            results.add(result);
        });
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"), results);
    }

    @Override
    public AjaxResult oaconfigAdd(OaConfigParam param, HttpServletRequest request) {
        Systemmanager user = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("LOGINCODE", iCommonService.getUserLoginCode(request)));
        for (OaConfigAddParam paramParam : param.getParams()) {
            WskhOpenaccountconfig openaccountconfig = iWskhOpenaccountconfigMapper.selectOne(new QueryWrapper<WskhOpenaccountconfig>().eq("configid", paramParam.getConfigid()));
            openaccountconfig.setConfigvalue(paramParam.getConfigvalue());
            iWskhOpenaccountconfigMapper.update(openaccountconfig, new QueryWrapper<WskhOpenaccountconfig>().eq("configid", paramParam.getConfigid()));
        }
        systemmanagerService.writeOperateLog(SysConstants.WSKH_CONFIG, "修改参数, id=" + user.getLogincode(), user, null, null, null);
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"));
    }

    @Override
    public AjaxResult<TreeNode> divisiontree(HttpServletRequest request) {
        List<Division> divisions = iDivisionMapper.selectList(new QueryWrapper<Division>().in("divisionlevel", "country", "province", "city"));
        List<TreeNode> treeNodes = changeDivToTreeNode(divisions);
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"), treeNodes);
    }

    @Override
    public AjaxResult<Division> queryAreaByCondition(HttpServletRequest request, String parentcode) {
        List<Division> divisions = iDivisionMapper.selectList(new QueryWrapper<Division>().eq("parentcode", parentcode));
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"), divisions);
    }

    @Override
    public AjaxResult<Division> getParentByAreacode(HttpServletRequest request, String parentcode) {
        Division division = iDivisionMapper.selectOne(new QueryWrapper<Division>().eq("divisioncode", parentcode));
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"), division);
    }

    @Override
    public AjaxResult dealDiv(HttpServletRequest request, DivisionAddParam param) {
        Systemmanager user = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("LOGINCODE", iCommonService.getUserLoginCode(request)));
        Division areaisexit = iDivisionMapper.selectOne(new QueryWrapper<Division>().eq("divisioncode", param.getDivisioncode()));
        Division areaisexit2 = iDivisionMapper.selectOne(new QueryWrapper<Division>()
                .eq("divisionname", param.getDivisionname())
                .eq("parentcode", param.getParentcode()));
        if (param.getAutoid() != null) {
            Division div = iDivisionMapper.selectOne(new QueryWrapper<Division>().eq("autoid", param.getAutoid()));
            if (areaisexit != null && !param.getDivisioncode().equals(div.getDivisioncode())) {
                return AjaxResult.error(Constants.Error_Code_Design, MessageType.MESSAGE_ERROR_CODE_SYSTEM023.getCode(), request.getHeader("Accept-Language"));
            }
            if (areaisexit2 != null && !param.getDivisionname().equals(div.getDivisionname())) {
                return AjaxResult.error(Constants.Error_Code_Design, MessageType.MESSAGE_ERROR_CODE_SYSTEM024.getCode(), request.getHeader("Accept-Language"));
            }
            update(param, user, div);
        } else {
            if (areaisexit != null) {
                return AjaxResult.error(Constants.Error_Code_Design, MessageType.MESSAGE_ERROR_CODE_SYSTEM023.getCode(), request.getHeader("Accept-Language"));
            }
            if (areaisexit2 != null) {
                return AjaxResult.error(Constants.Error_Code_Design, MessageType.MESSAGE_ERROR_CODE_SYSTEM024.getCode(), request.getHeader("Accept-Language"));
            }
            add(param, user);
        }
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"));
    }

    @Override
    public AjaxResult deleteDiv(HttpServletRequest request, Long areaid) {
        Division area = iDivisionMapper.selectOne(new QueryWrapper<Division>().eq("autoid", areaid));
        // 三级菜单，直接delete
        if (("district").equals(area.getDivisionlevel()))
            iDivisionMapper.delete(new QueryWrapper<Division>().eq("autoid", areaid));
        // 二级菜单，删除时需先删掉三级菜单      一级菜单，删除时需先删掉二级菜单
        if (("province").equals(area.getDivisionlevel()) || ("city").equals(area.getDivisionlevel())) {
            List<Division> aList = iDivisionMapper.selectList(new QueryWrapper<Division>().eq("parentcode", area.getDivisioncode()));
            if (!aList.isEmpty()) {
                return AjaxResult.error(Constants.Error_Code_Design, MessageType.MESSAGE_ERROR_CODE_SYSTEM025.getCode(), request.getHeader("Accept-Language"));
            } else {
                iDivisionMapper.delete(new QueryWrapper<Division>().eq("autoid", areaid));
            }
        }
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"));
    }

    @Override
    public AjaxResult syncTaToCenter(HttpServletRequest request) {
        List<Userinfo> taList = iUserinfoMapper.queryUserinfoTa();

        //发送银行服务同步信息
        for (Userinfo ta : taList) {
            if (ta == null) {
                continue;
            }
            try {
                iSendMsgService.sendCustomerInfo(ta, ta.getAccountid(), "1", 0);
            } catch (Exception e) {
                log.error("同步信息发送失败，失败原因：" + e.getMessage());
            }
        }
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"));
    }

    @Override
    public AjaxResult updateTransaction(HttpServletRequest request) {
        Systemmanager user = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("LOGINCODE", iCommonService.getUserLoginCode(request)));
        //发送通知
        NotifyMI1.UpdateUserTradeRightNtf.Builder builder = NotifyMI1.UpdateUserTradeRightNtf.newBuilder();
        Common.MessageHead.Builder hd = Common.MessageHead.newBuilder();
        PublicMI1.NotifyHead.Builder nhd = PublicMI1.NotifyHead.newBuilder();
        nhd.setNtfMode(0);
        builder.setNtfHeader(nhd);
        hd.setFunCode(FunCodeConstants.FuncCode_UpdateUserTradeRightNtf);
        hd.setClientTime(System.currentTimeMillis());
        builder.setHeader(hd);
        builder.setNotifyTime(new SimpleDateFormat(DateTimeUtils.DATETIME_PATTERN).format(new Date()));
        byte[] body = ProtoHelper.getNTAS(builder.build().toByteArray(), FunCodeConstants.FuncCode_UpdateUserTradeRightNtf);
        rabbitTemplate.send(SysConstants.RabbitNtfKey, new Message(body, new MessageProperties()));
        //记录操作日志
        systemmanagerService.writeOperateLog(SysConstants.BUSINESS_SYSTEMSETTING, "更新交易权限", user, null, null, null);
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"));
    }

    @Override
    public AjaxResult<SystemSetUpDetail> initdetail(HttpServletRequest request) {
        SystemSetUpDetail result = new SystemSetUpDetail();
        List<Systemparam> sysparmList = iSystemparamMapper.selectList(new QueryWrapper<Systemparam>()
                .in("paramcode", "009", "010", "011", "012", "013", "014"));
        for (Systemparam sp : sysparmList) {
            switch (sp.getParamcode()) {
                case SysConstants.SYSPARAM_SETTING_OPEN_MARKET:
                    result.setOpenMarket(sp.getParamvalue());
                    break;
                case SysConstants.SYSPARAM_SETTING_SETTLEMENT:
                    result.setSettlement(sp.getParamvalue());
                    break;
                case SysConstants.SYSPARAM_SETTING_SIGN_IN:
                    result.setSignIn(sp.getParamvalue());
                    break;
                case SysConstants.SYSPARAM_SETTING_SIGN_OUT:
                    result.setSignOut(sp.getParamvalue());
                    break;
                case SysConstants.SYSPARAM_SETTING_SETTLE_TRADEDAY:
                    result.setOpenMarketDayType(sp.getParamvalue());
                    break;
                case SysConstants.SYSPARAM_SETTING_SYS_CLEAN:
                    result.setSysclean(sp.getParamvalue());
                    break;
                default:
                    break;
            }
        }

        Systemparam ss = iSystemparamMapper.selectOne(new QueryWrapper<Systemparam>().eq("PARAMCODE", "980"));
        if (ss != null) {
            result.setSysparmParaValue(ss.getParamvalue());
        } else {
            result.setSysparmParaValue("0");
        }
        Systemparam s = iSystemparamMapper.selectOne(new QueryWrapper<Systemparam>().eq("PARAMCODE", "974"));
        if (s != null && StringUtils.isNotBlank(s.getParamvalue()) && "1.5".equals(s.getParamvalue())) {
            result.setClearFlag(1);
        } else {
            result.setClearFlag(0);
        }
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"));
    }

    @Override
    public AjaxResult update(HttpServletRequest request, SystemSetUpDetail param) {
        Systemmanager user = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("LOGINCODE", iCommonService.getUserLoginCode(request)));
        //更新待开市时间
        updateSystem(SysConstants.SYSPARAM_SETTING_OPEN_MARKET, param.getOpenMarket(), user.getLogincode(), user.getAutoid());
        //更新归属交易日
        updateSystem(SysConstants.SYSPARAM_SETTING_SETTLE_TRADEDAY, param.getOpenMarketDayType(), user.getLogincode(), user.getAutoid());
        //更新系统结算时间
        updateSystem(SysConstants.SYSPARAM_SETTING_SETTLEMENT, param.getSettlement(), user.getLogincode(), user.getAutoid());
        //更新银行签到时间
        updateSystem(SysConstants.SYSPARAM_SETTING_SIGN_IN, param.getSignIn(), user.getLogincode(), user.getAutoid());
        //银行签退时间
        updateSystem(SysConstants.SYSPARAM_SETTING_SIGN_OUT, param.getSignOut(), user.getLogincode(), user.getAutoid());

        if (StringUtils.isNotBlank(param.getSysclean())) {
            //系统清算时间
            updateSystem(SysConstants.SYSPARAM_SETTING_SYS_CLEAN, param.getSysclean(), user.getLogincode(), user.getAutoid());
        }

        Systemparam p = iSystemparamMapper.selectOne(new QueryWrapper<Systemparam>().eq("PARAMCODE", Constants.SYSPARAM_ID_CONFIG));
        if (p != null) {
            p.setParamvalue(String.valueOf(System.currentTimeMillis()));
            p.setUpdatetime(new Date());
            iSystemparamMapper.update(p, new QueryWrapper<Systemparam>().eq("PARAMCODE", Constants.SYSPARAM_ID_CONFIG));
        }

        //更新签退时间通知
        NotifyMI1.UpdateCheckoutTimeNtf.Builder builder = NotifyMI1.UpdateCheckoutTimeNtf.newBuilder();
        Common.MessageHead.Builder hd = Common.MessageHead.newBuilder();
        PublicMI1.NotifyHead.Builder nhd = PublicMI1.NotifyHead.newBuilder();
        nhd.setNtfMode(0);
        hd.setFunCode(FunCodeConstants.FuncCode_UpdateCheckoutTimeNtf);
        hd.setClientTime(System.currentTimeMillis());
        builder.setNtfHeader(nhd);
        builder.setNotifyTime(new SimpleDateFormat(DateTimeUtils.DATETIME_PATTERN).format(new Date()));
        builder.setHeader(hd);

        iSendMsgService.sendMsg(builder.build().toByteArray(), SysConstants.RabbitNtfKey,
                FunCodeConstants.FuncCode_UpdateCheckoutTimeNtf);

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

    @Override
    public AjaxResult clearMarketRunPlan(HttpServletRequest request) {
        Systemmanager user = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("LOGINCODE", iCommonService.getUserLoginCode(request)));
        iMarketrunstepdetailMapper.delete(new QueryWrapper<>());
        systemmanagerService.writeOperateLog(SysConstants.BUSINESS_SYSTEMSETTING, "清空运行时段", user, null, null, null);
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"));
    }

    @Override
    public AjaxResult<EnumDicsResult> getEnumDics(HttpServletRequest request) {
        EnumDicsResult enumDicsResult = new EnumDicsResult();
        List<Enumgroup> enumGroups = new ArrayList<>();
        List<Enumdic> enumDics = iEnumdicMapper.selectList(new QueryWrapper<Enumdic>()
                .eq("showflag", 1));
        for (Enumdic enumDic : enumDics) {
            Enumgroup eg = iEnumgroupMapper.selectOne(new QueryWrapper<Enumgroup>()
                    .eq("enumgroupid", enumDic.getEnumgroupid()));
            if (!enumGroups.contains(eg)) {
                enumGroups.add(eg);
            }
        }
        enumDicsResult.setEnumdics(enumDics);
        enumDicsResult.setEnumgroups(enumGroups);
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"), enumDicsResult);
    }

    @Override
    public PageResult<EnumDicsPageResult> queryEnumDicItemByPage(EnumDicsPageParam param, HttpServletRequest request) {
        IPage<EnumDicsPageResult> queryResultIPage;
        IPage<EnumDicsPageResult> page = new Page<>(param.getPageNum(), param.getPageSize());
        if (param.getEnumdiccode() == null || param.getIsmappingtobank() == null) {
            param.setModifyflag(1);
            param.setShowflag(1);
            queryResultIPage = iEnumdicMapper.queryEnumDicByPage(page, param);
        } else {
            param.setEnumitemstatus(1);
            queryResultIPage = iEnumdicMapper.queryEnumDicItemByPage(page, param);
        }
        PageResult<EnumDicsPageResult> result = new PageResult<>();
        result.setCode(Constants.Success_Code_Design);
        result.setMessage(AjaxResult.dealMsg(MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language")));
        result.setPages(queryResultIPage.getPages());
        result.setCurrent(queryResultIPage.getCurrent());
        result.setTotal(queryResultIPage.getTotal());
        result.setPageSize(queryResultIPage.getSize());
        result.setData(queryResultIPage.getRecords());
        return result;
    }

    @Override
    public AjaxResult<Enumdic> editEnumDic(Long autoid, Long enumgroupid, HttpServletRequest request) {
        if (autoid != null && autoid > 0) {
            Enumdic enumDic = iEnumdicMapper.selectOne(new QueryWrapper<Enumdic>().eq("AUTOID", autoid));
            return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"), enumDic);
        } else {
            Enumdic enumDic = new Enumdic();
            enumDic.setEnumgroupid(enumgroupid);
            enumDic.setIsmappingtobank(0);
            return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"), enumDic);
        }
    }

    @Override
    public AjaxResult<EnumdicitemVoResult> editEnumDicItem(Long autoid, String enumdiccode, Integer ismappingtobank, HttpServletRequest request) {
        EnumdicitemVoResult result = new EnumdicitemVoResult();
        if (autoid != null) {
            Enumdicitem enumdicitem = iEnumdicitemMapper.selectOne(new QueryWrapper<Enumdicitem>().eq("autoid", autoid));
            result.setEnumdicitem(enumdicitem);
        }
        if (("certificatetype".equals(enumdiccode)) && autoid != null) {
            Certificatetypeconfig certificateTypeConfig = iCertificatetypeconfigMapper.selectOne(new QueryWrapper<Certificatetypeconfig>()
                    .eq("enumdicitemid", autoid));
            result.setConfig(certificateTypeConfig);
        }
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"), result);
    }

    @Override
    public AjaxResult saveEnumDic(Enumdic enumdic, HttpServletRequest request) {
        Enumdic current = iEnumdicMapper.selectOne(new QueryWrapper<Enumdic>().eq("enumdiccode", enumdic.getEnumdiccode()));
        if (current != null) {
            return AjaxResult.error(Constants.Error_Code_Design, MessageType.MESSAGE_ERROR_CODE_SYSTEM026.getCode(), request.getHeader("Accept-Language"));
        }
        enumdic.setItemstatus(SysEnums.CommonStatus.WORK.getCode());
        enumdic.setShowflag(1);
        enumdic.setModifyflag(1);
        if (enumdic.getAutoid() == null || enumdic.getAutoid() <= 0) {
            iEnumdicMapper.insert(enumdic);
        } else {
            iEnumdicMapper.updateById(enumdic);
        }
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"));
    }

    @Override
    public AjaxResult updateOrSave(EnumDicItemSave param, HttpServletRequest request) {
        if (param.getAutoid() != null) {
            Enumdicitem enumDicItem = iEnumdicitemMapper.selectOne(new QueryWrapper<Enumdicitem>().eq("autoid", param.getAutoid()));
            Enumdicitem enumDicItemExit = iEnumdicitemMapper.selectOne(new QueryWrapper<Enumdicitem>()
                    .eq("enumdicname", param.getEnumdicname())
                    .eq("enumdiccode", param.getEnumdiccode()));
            if (enumDicItemExit != null && !param.getEnumdicname().equals(enumDicItem.getEnumdicname())) {
                return AjaxResult.error(Constants.Error_Code_Design, MessageType.MESSAGE_ERROR_CODE_SYSTEM027.getCode(), request.getHeader("Accept-Language"));
            }
            Enumdicitem enumDicItemExit2 = iEnumdicitemMapper.selectOne(new QueryWrapper<Enumdicitem>()
                    .eq("enumitemname", param.getEnumitemname())
                    .eq("enumdiccode", param.getEnumdiccode()));
            if (enumDicItemExit2 != null && !param.getEnumitemname().equals(enumDicItem.getEnumitemname())) {
                return AjaxResult.error(Constants.Error_Code_Design, MessageType.MESSAGE_ERROR_CODE_SYSTEM028.getCode(), request.getHeader("Accept-Language"));
            }
            enumDicItem.setEnumdiccode(param.getEnumdiccode());
            enumDicItem.setEnumdicname(param.getEnumdicname());
            enumDicItem.setEnumitemname(param.getEnumitemname());
            enumDicItem.setBankmappedvalue(param.getBankmappedvalue());
            enumDicItem.setRemark(param.getRemark());
            iEnumdicitemMapper.updateById(enumDicItem);
            if (("certificatetype".equals(param.getEnumdiccode()))) {
                Certificatetypeconfig certificateTypeConfig = iCertificatetypeconfigMapper.selectOne(new QueryWrapper<Certificatetypeconfig>()
                        .eq("enumdicitemid", param.getAutoid()));
                if (certificateTypeConfig == null) {
                    certificateTypeConfig = new Certificatetypeconfig();
                    certificateTypeConfig.setEnumdicitemid(param.getAutoid());
                }
                certificateTypeConfig.setCardlength(param.getCardlength());
                certificateTypeConfig.setIsperson(param.getIsperson());
                certificateTypeConfig.setRegexpress(param.getRegexpress());
                iCertificatetypeconfigMapper.update(certificateTypeConfig, new QueryWrapper<Certificatetypeconfig>()
                        .eq("enumdicitemid", param.getAutoid()));
            }
            redisServiceUtil.updateHash(Constants.REDIS_HEADER_DICT + enumDicItem.getEnumdiccode(),
                    enumDicItem.getEnumitemname().toString(), enumDicItem.getEnumdicname());
            return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"));
        } else {
            Enumdicitem enumDicItem = new Enumdicitem();
            Enumdic enumDic = iEnumdicMapper.selectOne(new QueryWrapper<Enumdic>().eq("enumdiccode", param.getEnumdiccode()));
            if (param.getEnumitemname() == null) {
                List<Enumdicitem> enumDicItems = iEnumdicitemMapper.selectList(new QueryWrapper<Enumdicitem>().eq("enumdiccode", param.getEnumdiccode()));
                enumDicItem.setEnumitemname(enumDicItems.size() + 1);
            } else {
                Enumdicitem enumDicItemExit = iEnumdicitemMapper.selectOne(new QueryWrapper<Enumdicitem>()
                        .eq("enumdicname", param.getEnumdicname())
                        .eq("enumdiccode", param.getEnumdiccode()));
                if (enumDicItemExit != null) {
                    return AjaxResult.error(Constants.Error_Code_Design, MessageType.MESSAGE_ERROR_CODE_SYSTEM027.getCode(), request.getHeader("Accept-Language"));
                }
                Enumdicitem enumDicItemExit2 = iEnumdicitemMapper.selectOne(new QueryWrapper<Enumdicitem>()
                        .eq("enumitemname", param.getEnumitemname())
                        .eq("enumdiccode", param.getEnumdiccode()));
                if (enumDicItemExit2 != null) {
                    return AjaxResult.error(Constants.Error_Code_Design, MessageType.MESSAGE_ERROR_CODE_SYSTEM028.getCode(), request.getHeader("Accept-Language"));
                }
                enumDicItem.setEnumitemname(param.getEnumitemname());
            }

            enumDicItem.setEnumdiccode(param.getEnumdiccode());
            enumDicItem.setEnumdicid(enumDic.getAutoid());
            enumDicItem.setEnumdicname(param.getEnumdicname());
            enumDicItem.setBankmappedvalue(param.getBankmappedvalue());
            enumDicItem.setRemark(param.getRemark());
            enumDicItem.setEnumitemstatus(1);
            iEnumdicitemMapper.insert(enumDicItem);
            if (("certificatetype".equals(param.getEnumdiccode()))) {
                Certificatetypeconfig certificateTypeConfig = new Certificatetypeconfig();
                certificateTypeConfig.setEnumdicitemid(enumDicItem.getAutoid());
                certificateTypeConfig.setCardlength(param.getCardlength());
                certificateTypeConfig.setIsperson(param.getIsperson());
                certificateTypeConfig.setRegexpress(param.getRegexpress());
                iCertificatetypeconfigMapper.insert(certificateTypeConfig);
            }
            redisServiceUtil.updateHash(Constants.REDIS_HEADER_DICT + enumDicItem.getEnumdiccode(),
                    enumDicItem.getEnumitemname().toString(), enumDicItem.getEnumdicname());
            return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"));
        }
    }

    @Override
    public AjaxResult delEnumdicItem(Long autoid, Integer flag, HttpServletRequest request) {
        if (flag == 1) {
            Enumdicitem enumDicItem = iEnumdicitemMapper.selectOne(new QueryWrapper<Enumdicitem>().eq("AUTOID", autoid));
            String enumdiccode = enumDicItem.getEnumdiccode();
            if (("certificatetype".equals(enumdiccode))) {
                iCertificatetypeconfigMapper.delete(new QueryWrapper<Certificatetypeconfig>()
                        .eq("enumdicitemid", autoid));
            }
            redisServiceUtil.delHash(Constants.REDIS_HEADER_DICT + enumDicItem.getEnumdiccode(), enumDicItem.getEnumitemname().toString());
            iEnumdicitemMapper.deleteById(enumDicItem);
        }
        if (flag == 0) {
            Enumdic enumDic = iEnumdicMapper.selectOne(new QueryWrapper<Enumdic>().eq("AUTOID", autoid));
            String enumdiccode = enumDic.getEnumdiccode();
            if (("certificatetype".equals(enumdiccode))) {
                iCertificatetypeconfigMapper.delete(new QueryWrapper<Certificatetypeconfig>()
                        .eq("enumdicitemid", autoid));
            }
            redisServiceUtil.delHash(Constants.REDIS_HEADER_DICT + enumDic.getEnumdiccode(), enumDic.getEnumdicname());
            iEnumdicMapper.deleteById(enumDic);
        }
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"));
    }

    @Override
    public AjaxResult refreshredis(HttpServletRequest request) {
        iRedisInitService.init();
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"));
    }

    private void updateSystem(String code, String openMarket, String logincode, Long value) {
        try {
            Systemparam systemparam = iSystemparamMapper.selectOne(new QueryWrapper<Systemparam>().eq("PARAMCODE", code));
            systemparam.setParamvalue(code.equals(SysConstants.SYSPARAM_SETTING_SETTLE_TRADEDAY) ? openMarket : formatHHMM(openMarket));
            systemparam.setLoginid(logincode);
            systemparam.setUserid(value);
            systemparam.setUpdatetime(new Date());
            iSystemparamMapper.update(systemparam, new QueryWrapper<Systemparam>().eq("PARAMCODE", code));
        } catch (Exception e) {
            log.error("时间格式错误！");
        }
    }

    private String formatHHMM(String time) throws ParseException {
        time = DateTimeUtils.format(DateTimeUtils.parseDate(time, "HH:mm"), "HH:mm");
        return time;
    }

    private void update(DivisionAddParam param, Systemmanager user, Division div) {
        String oldDivisionCode = div.getDivisioncode();
        div.setDivisioncode(param.getDivisioncode());
        div.setDivisionname(param.getDivisionname());
        div.setModifytime(new Date());
        div.setModifierid(user.getAutoid());

        // 修改一级菜单province
        if (("province").equals(div.getDivisionlevel())) {
            div.setPathname(param.getDivisionname());
            div.setSeparablename(param.getDivisionname());
        }
        // 修改二级菜单city
        if (("city").equals(div.getDivisionlevel())) {
            Division parentArea = iDivisionMapper.selectOne(new QueryWrapper<Division>().eq("divisioncode", div.getParentcode()));
            div.setPathname(parentArea.getDivisionname() + param.getDivisionname());
            div.setSeparablename(parentArea.getDivisionname() + ">" + param.getDivisionname());
        }
        // 修改二级菜单district
        if (("district").equals(div.getDivisionlevel())) {
            Division parentArea = iDivisionMapper.selectOne(new QueryWrapper<Division>().eq("divisioncode", div.getParentcode()));
            div.setPathname(parentArea.getPathname() + param.getDivisionname());
            div.setSeparablename(parentArea.getSeparablename() + ">" + param.getDivisionname());
        }

        iDivisionMapper.update(div, new QueryWrapper<Division>().eq("autoid", div.getAutoid()));

        // divisioncode变更时，须更新下一级的parentcode 20240614
        if (!oldDivisionCode.equals(param.getDivisioncode())) {
            iDivisionMapper.updateByParentCode(oldDivisionCode, param.getDivisioncode());
        }
    }

    private void add(DivisionAddParam param, Systemmanager user) {
        Division div = new Division();
        div.setDivisioncode(param.getDivisioncode());
        div.setDivisionname(param.getDivisionname());
        div.setParentcode(param.getParentcode());
        // 获取其父类
        Division parentArea = iDivisionMapper.selectOne(new QueryWrapper<Division>().eq("divisioncode", param.getParentcode()));
        String parentLevel = "";
        if (parentArea != null) {
            // 国家为初始化，不支持手动添加上级为NULL的记录
            parentLevel = parentArea.getDivisionlevel();

            if ("country".equals(parentLevel)) {
                div.setDivisionlevel("province");
                div.setSeparablename(param.getDivisionname());
                div.setPathname(param.getDivisionname());
            }
            if ("province".equals(parentLevel)) {
                div.setDivisionlevel("city");
                div.setSeparablename(parentArea.getDivisionname() + ">" + param.getDivisionname());
                div.setPathname(parentArea.getPathname() + param.getDivisionname());
            }
            if ("city".equals(parentLevel)) {
                div.setDivisionlevel("district");
                div.setSeparablename(parentArea.getSeparablename() + ">" + param.getDivisionname());
                div.setPathname(parentArea.getPathname() + param.getDivisionname());
            }

            div.setModifytime(new Date());
            div.setModifierid(user.getAutoid());
            iDivisionMapper.insert(div);
        }
    }

    private List<TreeNode> changeDivToTreeNode(List<Division> divisions) {
        List<TreeNode> node = new ArrayList<>();
        if (divisions == null || divisions.isEmpty()) {
            return node;
        }
        Map<String, List<Division>> treeMap = new HashMap<>();
        for (Division dis : divisions) {
            //一级菜单
            if (dis.getParentcode() == null || dis.getParentcode().trim().isEmpty()) {
                //开始存入
                if (treeMap.containsKey("0")) {
                    treeMap.get("0").add(dis);
                } else {
                    List<Division> temp = new ArrayList<>();
                    temp.add(dis);
                    treeMap.put("0", temp);
                }
            } else {
                //二级菜单
                if (treeMap.containsKey(dis.getParentcode())) {
                    treeMap.get(dis.getParentcode()).add(dis);
                } else {
                    List<Division> temp = new ArrayList<>();
                    temp.add(dis);
                    treeMap.put(dis.getParentcode(), temp);
                }
            }
        }
        //一级菜单
        List<Division> first = treeMap.get("0");
        TreeNode node_ = null;
        if (first != null && !first.isEmpty()) {
            for (Division menu_ : first) {
                //设置一级菜单
                node_ = initTreeNode(menu_);
                //设置一级菜单以下的所有菜单
                loadChild(treeMap, node_);
                //添加菜单
                if (node_.getChildren() != null && !node_.getChildren().isEmpty()) {
                    node.add(node_);
                } else if (org.springframework.util.StringUtils.isEmpty(node_.getParentCode())) {
                    node.add(node_);
                }
            }
        }

        return node;
    }

    private void loadChild(Map<String, List<Division>> treeMap, TreeNode parent) {
        String parentid = parent.getResourceCode();
        if (parentid == null) {
            return;
        }
        List<TreeNode> nodechilds = new ArrayList<TreeNode>();
        if (treeMap.containsKey(parentid)) {
            //设置二级菜单
            List<Division> list = treeMap.get(parentid);
            for (Division menu : list) {
                TreeNode node = initTreeNode(menu);
                //设置三级菜单
                loadChild(treeMap, node);
                nodechilds.add(node);
            }
            parent.setChildren(nodechilds);
        } else {
            parent.setChildren(new ArrayList<>());
        }
    }

    private TreeNode initTreeNode(Division dis) {
        TreeNode node = new TreeNode();
        node.setParentCode(Optional.ofNullable(dis.getParentcode()).orElse(""));
        node.setTitle(dis.getDivisionname());
        node.setResourceCode(dis.getDivisioncode());
        node.setPathname(dis.getPathname());
        return node;
    }

    private void addConfigNew(Long marketsectionid, SystemMarketSectionAddParam param) {
        // 添加“MarketSectionConfigNew”表相关记录
        if (CollectionUtils.isNotEmpty(param.getList())) {
            for (SystemMarketSectionAddMarket c : param.getList()) {
                Marketsectionconfignew ms = new Marketsectionconfignew();
                ms.setMarketsectionid(marketsectionid);
                ms.setOrderindex(c.getOrderindex());
                ms.setDisplayname(c.getDisplayname());
                ms.setMarketids(c.getMarketids());
                ms.setUpdatetime(new Date());
                ms.setTrademode(c.getTrademode());
                ms.setDisplaynameen(c.getDisplaynameen());
                ms.setDisplaynamezhTw(c.getDisplaynamezhtw());
                ms.setDisplaynameth(c.getDisplaynameth());
                ms.setDisplaynamevi(c.getDisplaynamevi());
                iMarketsectionconfignewMapper.insert(ms);
            }
        }
    }

    private void updateTerminalSysParam(SystemParamUpdate sysparm, Systemmanager systemmanager, Systemparam old) {
        // 修改
        old.setRemark(sysparm.getRemark());
        if (sysparm.getParamValue2() != null && !sysparm.getParamValue2().isEmpty()) {
            old.setParamvalue2(sysparm.getParamValue2());
        }
        old.setParamvalue(sysparm.getParaValue());

        old.setParamname(sysparm.getParaName());
        old.setLoginid(systemmanager.getLogincode());
        old.setUserid(systemmanager.getAutoid());
        old.setUpdatetime(new Date());
        iSystemparamMapper.update(old, new QueryWrapper<Systemparam>().eq("PARAMCODE", old.getParamcode()));
        redisServiceUtil.updateHash(Constants.REDIS_HEADER_SYSPARAM, old.getParamcode().trim(), old.getParamvalue().trim());

        if (old.getParamtype() == 0 || old.getParamtype() == 2) {
            Systemparam p = iSystemparamMapper.selectOne(new QueryWrapper<Systemparam>().eq("PARAMCODE", Constants.SYSPARAM_ID_CONFIG));

            if (p != null) {
                p.setParamvalue(String.valueOf(System.currentTimeMillis()));
                p.setUpdatetime(new Date());
                iSystemparamMapper.update(p, new QueryWrapper<Systemparam>().eq("PARAMCODE", p.getParamcode()));
            }
        }

        //修改了风险协议书的内容，更新时间戳
        if ("099".equals(sysparm.getParaCode())) {
            Systemparam p = iSystemparamMapper.selectOne(new QueryWrapper<Systemparam>().eq("PARAMCODE", Constants.SYSPARAM_ID_FENGX));

            if (p != null) {
                if (sysparm.getParamValue2() != null && !sysparm.getParamValue2().isEmpty()) {
                    p.setParamvalue2(sysparm.getParamValue2());
                }
                p.setParamvalue(String.valueOf(System.currentTimeMillis()));
                p.setUpdatetime(new Date());
                iSystemparamMapper.update(p, new QueryWrapper<Systemparam>().eq("PARAMCODE", p.getParamcode()));
            }
        }
    }

    private void addTerminalSysParam(SystemParamUpdate sysparm, Systemmanager systemmanager) {
        // 新增终端参数
        Systemparam systemparam = new Systemparam();
        BeanUtils.copyProperties(sysparm, systemparam);
        systemparam.setModifyflag(1);
        systemparam.setShowflag(1);
        systemparam.setParamtype(2);
        systemparam.setLoginid(systemmanager.getLogincode());
        systemparam.setUserid(systemmanager.getAutoid());

        systemparam.setParamvalue(sysparm.getParaValue());

        systemparam.setUpdatetime(new Date());
        iSystemparamMapper.insert(systemparam);
        redisServiceUtil.updateHash(Constants.REDIS_HEADER_SYSPARAM, sysparm.getParaCode().trim(), sysparm.getParaValue().trim());

        Systemparam p = iSystemparamMapper.selectOne(new QueryWrapper<Systemparam>().eq("PARAMCODE", Constants.SYSPARAM_ID_CONFIG));
        if (p != null) {
            p.setParamvalue(String.valueOf(System.currentTimeMillis()));
            if (sysparm.getParamValue2() != null && !sysparm.getParamValue2().isEmpty()) {
                p.setParamvalue2(sysparm.getParamValue2());
            }
            p.setUpdatetime(new Date());
            iSystemparamMapper.update(p, new QueryWrapper<Systemparam>().eq("PARAMCODE", p.getParamcode()));
        }
    }

    private void updateSysParam(SystemParamUpdate sysparm, Systemmanager systemmanager, Systemparam old) {
        if (old != null) {
            // 修改
            old.setParamvalue(sysparm.getParaValue());
            old.setRemark(sysparm.getRemark());
            if (sysparm.getParamValue2() != null && !sysparm.getParamValue2().isEmpty()) {
                old.setParamvalue2(sysparm.getParamValue2());
            }
            old.setLoginid(systemmanager.getLogincode());
            old.setUserid(systemmanager.getAutoid());
            old.setUpdatetime(new Date());
            iSystemparamMapper.update(old, new QueryWrapper<Systemparam>().eq("PARAMCODE", old.getParamcode()));
            redisServiceUtil.updateHash(Constants.REDIS_HEADER_SYSPARAM, old.getParamcode().trim(), old.getParamvalue().trim());
        }
    }
}
