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.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.muchinfo.mtp3century.service.ICommonService;
import com.muchinfo.mtp3century.service.ISystemSetUpService;
import com.muchinfo.mtp3century.utils.AjaxResult;
import com.muchinfo.mtp3century.utils.RedisServiceUtil;
import com.muchinfo.mtp3common.enumtype.*;
import com.muchinfo.mtp3common.vo.PageResult;
import com.muchinfo.mtp3interface.mapper.IErrorcodeMapper;
import com.muchinfo.mtp3interface.mapper.ISystemmanagerMapper;
import com.muchinfo.mtp3interface.mapper.ISystemparamMapper;
import com.muchinfo.mtp3pojos.entity.Errorcode;
import com.muchinfo.mtp3pojos.entity.Systemmanager;
import com.muchinfo.mtp3pojos.entity.Systemparam;
import com.muchinfo.mtp3pojos.vo.I18nconfig;
import com.muchinfo.mtp3pojos.vo.systemsetup.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.Objects;

@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;

    @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, Integer pageNum, Integer pageSize, HttpServletRequest request) {
        IPage<SystemMarketSectionResult> page = new Page<>(pageNum, pageSize);
        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);
    }

    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());
        }
    }
}
