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.mtp3century.service.ICommonService;
import com.muchinfo.mtp3century.service.ISystemRunService;
import com.muchinfo.mtp3common.enumtype.Constants;
import com.muchinfo.mtp3common.enumtype.MessageType;
import com.muchinfo.mtp3common.enumtype.SysConstants;
import com.muchinfo.mtp3common.enumtype.SysEnums;
import com.muchinfo.mtp3century.utils.AjaxResult;
import com.muchinfo.mtp3common.utils.DateTimeUtils;
import com.muchinfo.mtp3common.utils.ExportUtil;
import com.muchinfo.mtp3common.vo.PageResult;
import com.muchinfo.mtp3common.vo.ExportResult;
import com.muchinfo.mtp3interface.mapper.*;
import com.muchinfo.mtp3pojos.entity.*;
import com.muchinfo.mtp3pojos.vo.systemrun.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

@Service
public class SystemRunServiceImpl implements ISystemRunService {
    private final Logger log = LoggerFactory.getLogger(this.getClass());
    @Resource
    private ISystemmanagerMapper iSystemmanagerMapper;
    @Resource
    private ICommonService iCommonService;
    @Resource
    private IUseraccountMapper iUseraccountMapper;
    @Resource
    private ISystemmanagerlogMapper iSystemmanagerlogMapper;
    @Resource
    private IWskhBlacklistMapper iWskhBlacklistMapper;
    @Resource
    private IIpbacklistMapper iIpbacklistMapper;

    @Override
    public PageResult<SystemUserLogResult> queryByPage(SystemUserLogParam param, HttpServletRequest request) {
        Systemmanager systemmanager = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("LOGINCODE", iCommonService.getUserLoginCode(request)));
        //如果不是平台管理员
        PageResult<SystemUserLogResult> pageResult = new PageResult<>();
        if (!SysConstants.SYS_TYPE_MANAGE.equals(systemmanager.getReletype())) {
            param.setAreauserid(systemmanager.getAreauserid());
            String roles = "," + param.getOrgztypes() + ",";
            //如果是经纪会员
            if (roles.contains("," + SysEnums.OrganRole.broker.getCode() + ",")) {
                //经纪会员或者子机构 可以查下级，那么要判断传入的机构是否 就是他的下级
                log.debug("parentuserid={},userid={}", systemmanager.getAreauserid(), param.getAreauserid());
                if (param.getAreaids() != null && !"".equals(param.getAreaids().trim())) {
                    String[] aids = param.getAreaids().split(",");
                    for (String aid : aids) {
                        //当前登录账号的所属会员与要查的会员相同
                        if (systemmanager.getAreauserid().toString().equals(aid))
                            continue;
                        List<Useraccount> l = iUseraccountMapper.selectList(new QueryWrapper<Useraccount>()
                                .eq("userid", systemmanager.getAreauserid())
                                .eq("parentuserid", Long.parseLong(aid)));
                        if (CollectionUtils.isEmpty(l)) {
                            pageResult.setCode(Constants.Error_Code_Design);
                            pageResult.setMessage(AjaxResult.dealMsg(MessageType.QUERY_ERROR_CODE_004.getCode(), request.getHeader("Accept-Language")));
                            return pageResult;
                        }
                    }
                }
            }
        } else if (param.getAreauserid() == null) {
            //如果是平台管理员，默认只查平台的日志
            param.setAreauserid(systemmanager.getAreauserid());
        }

        if (StringUtils.isNotBlank(param.getStarttime())) {
            param.setStarttime(param.getStarttime() + " 00:00:00");
        }
        if (StringUtils.isNotBlank(param.getEndtime())) {
            param.setEndtime(param.getEndtime() + " 23:59:59");
        }

        IPage<SystemUserLogResult> page = new Page<>(param.getPageNum(), param.getPageSize());
        IPage<SystemUserLogResult> queryResultIPage = iSystemmanagerMapper.selectLogByParam(page, param);
        PageResult<SystemUserLogResult> 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 PageResult<SystemLoginErrorResult> queryError(SystemLoginErrorParam param, HttpServletRequest request) {
        Systemmanager systemmanager = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("LOGINCODE", iCommonService.getUserLoginCode(request)));
        //如果不是平台管理员
        if (!SysConstants.SYS_TYPE_MANAGE.equals(systemmanager.getReletype())) {
            param.setParentuserid(systemmanager.getAreauserid());
        }
        IPage<SystemLoginErrorResult> page = new Page<>(param.getPageNum(), param.getPageSize());
        IPage<SystemLoginErrorResult> queryResultIPage = iSystemmanagerMapper.queryUserLoginFlow(page, param);
        PageResult<SystemLoginErrorResult> 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 export(SystemLoginErrorParam param, HttpServletRequest request) {
        try {
            String fileName = "登录异常流水_" + DateTimeUtils.getDateTime("yyyyMMdd");
            Systemmanager systemmanager = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("LOGINCODE", iCommonService.getUserLoginCode(request)));
            //如果不是平台管理员
            if (!SysConstants.SYS_TYPE_MANAGE.equals(systemmanager.getReletype())) {
                param.setParentuserid(systemmanager.getAreauserid());
            }
            List<SystemLoginErrorResult> results = iSystemmanagerMapper.queryUserLoginFlow(param);

            if (CollectionUtils.isEmpty(results)) {
                return AjaxResult.error(Constants.Error_Code_Design, MessageType.QUERY_ERROR_CODE_005.getCode(), request.getHeader("Accept-Language"));
            }
            ExportResult exportResult = ExportUtil.write(fileName, SystemLoginErrorResult.class, results);
            return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"), exportResult);
        } catch (Exception e) {
            log.error("登录异常流水_导出失败，失败原因：" + e);
            return AjaxResult.error(Constants.Error_Code_Design, MessageType.QUERY_ERROR_CODE_006.getCode(), request.getHeader("Accept-Language"));
        }
    }

    @Override
    public PageResult<YmrslQueryResult> querymrsl(YmrslQueryParam param, HttpServletRequest request) {
        IPage<YmrslQueryResult> page = new Page<>(param.getPageNum(), param.getPageSize());
        IPage<YmrslQueryResult> queryResultIPage = iSystemmanagerMapper.querymrsl(page, param);
        PageResult<YmrslQueryResult> 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<Systemmanagerlog> view(Long id, HttpServletRequest request) {
        Systemmanagerlog userLog = iSystemmanagerlogMapper.selectOne(new QueryWrapper<Systemmanagerlog>().eq("autoid", id));
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"), userLog);
    }

    @Override
    public PageResult<WskhBlacklist> queryBlackList(Integer pageNum, Integer pageSize, HttpServletRequest request) {
        IPage<WskhBlacklist> page = new Page<>(pageNum, pageSize);
        IPage<WskhBlacklist> queryResultIPage = iWskhBlacklistMapper.selectPage(page, new QueryWrapper<>());
        PageResult<WskhBlacklist> 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 dealBlackList(BlackListAddParam param, HttpServletRequest request) {
        Systemmanager systemmanager = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("LOGINCODE", iCommonService.getUserLoginCode(request)));
        if (systemmanager.getReletype() != 1) {
            return AjaxResult.error(Constants.Error_Code_Design, MessageType.QUERY_ERROR_CODE_006.getCode(), request.getHeader("Accept-Language"));
        }
        if (param.getAutoid() == null) {
            WskhBlacklist blacklist = new WskhBlacklist();
            if (checkOnlyOne(param)) {
                return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM028.getCode(), request.getHeader("Accept-Language"));
            }
            blacklist.setCreatetime(new Date());
            blacklist.setOperatorid(systemmanager.getAutoid());
            blacklist.setCardtype(param.getCardtype());
            blacklist.setCardnum(param.getCardnum());
            iWskhBlacklistMapper.insert(blacklist);
        } else {
            if (checkOnlyOne(param)) {
                return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM028.getCode(), request.getHeader("Accept-Language"));
            }
            WskhBlacklist blacklist = iWskhBlacklistMapper.selectOne(new QueryWrapper<WskhBlacklist>().eq("autoid", param.getAutoid()));
            blacklist.setOperatorid(systemmanager.getAutoid());
            blacklist.setCardtype(param.getCardtype());
            blacklist.setCardnum(param.getCardnum());
            blacklist.setCreatetime(new Date());
            iWskhBlacklistMapper.updateById(blacklist);
        }
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"));
    }

    @Override
    public AjaxResult delBlackList(Long id, HttpServletRequest request) {
        Systemmanager systemmanager = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("LOGINCODE", iCommonService.getUserLoginCode(request)));
        if (systemmanager.getReletype() != 1) {
            return AjaxResult.error(Constants.Error_Code_Design, MessageType.QUERY_ERROR_CODE_006.getCode(), request.getHeader("Accept-Language"));
        }
        iWskhBlacklistMapper.delete(new QueryWrapper<WskhBlacklist>().eq("autoid", id));
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"));
    }

    @Override
    public PageResult<Ipbacklist> queryIPList(String adress, Integer pageNum, Integer pageSize, HttpServletRequest request) {
        IPage<Ipbacklist> page = new Page<>(pageNum, pageSize);
        IPage<Ipbacklist> queryResultIPage = iIpbacklistMapper.selectPage(page, new QueryWrapper<Ipbacklist>().like("IP", adress));
        PageResult<Ipbacklist> 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 addIPList(IpListDelParam param, HttpServletRequest request) {
        if (param.getIp() == null || param.getIp().trim().isEmpty()) {
            return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM029.getCode(), request.getHeader("Accept-Language"));
        }
        Ipbacklist ipbacklist = iIpbacklistMapper.selectOne(new QueryWrapper<Ipbacklist>()
                .eq("ip", param.getIp())
                .eq("iptype", param.getIptype()));
        if (Objects.nonNull(ipbacklist)) {
            return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM030.getCode(), request.getHeader("Accept-Language"));
        }
        Ipbacklist ip = new Ipbacklist();
        ip.setIp(param.getIp());
        ip.setIptype(param.getIptype());
        iIpbacklistMapper.insert(ip);
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"));
    }

    @Override
    public AjaxResult delIPList(IpListDelParam param, HttpServletRequest request) {
        iIpbacklistMapper.delete(new QueryWrapper<Ipbacklist>()
                .eq("ip", param.getIp())
                .eq("iptype", param.getIptype()));
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"));
    }

    @Override
    public PageResult<LoginLogQueryResult> queryloginlog(LoginLogQueryParam param, HttpServletRequest request) {
        Systemmanager systemmanager = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("LOGINCODE", iCommonService.getUserLoginCode(request)));
        if (!Objects.equals(systemmanager.getReletype(), SysConstants.SYS_TYPE_MANAGE)) {
            param.setMemberuserid(systemmanager.getAreauserid());
        }
        IPage<LoginLogQueryResult> page = new Page<>(param.getPageNum(), param.getPageSize());
        IPage<LoginLogQueryResult> queryResultIPage = iSystemmanagerMapper.queryloginlog(page, param);
        PageResult<LoginLogQueryResult> 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<LoginLogQueryResult> loginlogview(LoginLogQueryParam param, HttpServletRequest request) {
        List<LoginLogQueryResult> results = iSystemmanagerMapper.queryloginlog(param);
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"), results.get(0));
    }

    @Override
    public AjaxResult loginlogExport(LoginLogQueryParam param, HttpServletRequest request) {
        try {
            String fileName = "终端登录日志_" + DateTimeUtils.getDateTime("yyyyMMdd");
            List<LoginLogQueryResult> resultIPage = iSystemmanagerMapper.queryloginlog(param);
            if (CollectionUtils.isEmpty(resultIPage)) {
                return AjaxResult.error(Constants.Error_Code_Design, MessageType.QUERY_ERROR_CODE_006.getCode(), request.getHeader("Accept-Language"));
            }
            ExportResult exportResult = ExportUtil.write(fileName, LoginLogQueryResult.class, resultIPage);
            return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"), exportResult);
        } catch (Exception e) {
            log.error("终端登录日志导出失败，失败原因：" + Arrays.toString(e.getStackTrace()));
            return AjaxResult.error(Constants.Error_Code_Design, MessageType.QUERY_ERROR_CODE_006.getCode(), request.getHeader("Accept-Language"));
        }
    }

    private boolean checkOnlyOne(BlackListAddParam blacklist) {
        Long num = iWskhBlacklistMapper.selectCount(new QueryWrapper<WskhBlacklist>()
                .eq("cardtype", blacklist.getCardtype())
                .eq("cardnum", blacklist.getCardnum()));
        return num.intValue() > 0;
    }
}
