package com.muchinfo.mtp3century.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
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.handler.GoodsMergeStrategy;
import com.muchinfo.mtp3century.service.ICommonService;
import com.muchinfo.mtp3century.service.IReportFormService;
import com.muchinfo.mtp3century.utils.RedisServiceUtil;
import com.muchinfo.mtp3common.enumtype.MessageType;
import com.muchinfo.mtp3common.utils.DateTimeUtils;
import com.muchinfo.mtp3common.utils.ExportUtil;
import com.muchinfo.mtp3century.utils.AjaxResult;
import com.muchinfo.mtp3common.vo.ExportResult;
import com.muchinfo.mtp3common.vo.PageResult;
import com.muchinfo.mtp3common.enumtype.SysConstants;
import com.muchinfo.mtp3common.enumtype.Constants;
import com.muchinfo.mtp3interface.mapper.*;
import com.muchinfo.mtp3pojos.entity.*;
import com.muchinfo.mtp3pojos.vo.reportform.*;
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.io.ByteArrayOutputStream;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.ParseException;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class ReportFormServiceImpl implements IReportFormService {

    private final Logger log = LoggerFactory.getLogger(this.getClass());
    @Resource
    private ISystemmanagerMapper iSystemmanagerMapper;
    @Resource
    private ICommonService iCommonService;
    @Resource
    private IUseraccountMapper iUseraccountMapper;
    @Resource
    private RedisServiceUtil redisServiceUtil;
    @Resource
    private IReckonDaydividecountdetailMapper detailMapper;
    @Resource
    private ITaaccountMapper iTaaccountMapper;
    @Resource
    private IReckonDaytaaccountMapper iReckonDaytaaccountMapper;
    @Resource
    private IReckonDayaccountppMapper iReckonDayaccountppMapper;
    @Resource
    private IReportTaaccountMapper iReportTaaccountMapper;
    @Resource
    private IReportPlateformppMapper iReportPlateformppMapper;
    @Resource
    private IGoodsMapper iGoodsMapper;

    @Override
    public AjaxResult<ShareAmountQueryResult> selectShareAmount(ShareAmountQueryParam param, HttpServletRequest request) {
        Systemmanager systemmanager = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("LOGINCODE", iCommonService.getUserLoginCode(request)));
        Object devidetype = redisServiceUtil.getCacheMapValue(Constants.REDIS_HEADER_SYSPARAM, SysConstants.SYSPARAM_CODE_DIVIDE);
        if (devidetype == null || "1".equals(devidetype.toString())) {
            param.setSearchtype(3);
        }
        if (systemmanager.getReletype() != 1) {
            if (param.getIsson() != null && param.getIsson() == 1) {
                param.setAreaid(null);
                param.setParentuserid(systemmanager.getAreauserid());
            } else {
                if (StringUtils.isNotBlank(param.getOrgztypes()) && param.getOrgztypes().equals("3")) {
                    param.setIsmarketing(1);
                }
                param.setAreaid(systemmanager.getAreauserid());
            }
        }
        List<ShareAmountQueryResult> resultIPage;
        if (param.getCycletype() == null || param.getCycletype() == 0) {
            resultIPage = detailMapper.queryDayDivide(param);
        } else {
            if (param.getCycletype() == 2 && param.getQuarter() != null) {
                param.setTradedate(param.getTradedate() + param.getQuarter());
            }
            if (param.getCycletype() == 4 && param.getTradedate().length() == 8) {
                param.setCycletime(param.getTradedate());
                param.setTradedate(null);
            }
            resultIPage = detailMapper.queryReportDivide(param);
        }
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"), resultIPage);
    }

    @Override
    public AjaxResult<ShareAmountQueryResult> shareAmountQueryPlat(ShareAmountQueryParam param, HttpServletRequest request) {
        //只能查询自己和下一级的
        Systemmanager systemmanager = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("LOGINCODE", iCommonService.getUserLoginCode(request)));
        if (systemmanager.getReletype() != 1) {
            if (param.getIsson() != null && param.getIsson() == 1) {
                param.setParentareaid(systemmanager.getAreauserid());
            } else {
                param.setParentuserid(systemmanager.getAreauserid());
            }
        }
        List<ShareAmountQueryResult> resultIPage;
        if (param.getCycletype() == 0) {
            resultIPage = detailMapper.queryByDate(param);
        } else {
            //周、月、季、年、全
            if (param.getCycletype() == 2) {
                //季报表
                param.setTradedate(param.getTradedate() + param.getQuarter());
            }
            resultIPage = detailMapper.queryByOther(param);
        }
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"), resultIPage);
    }

    @Override
    public PageResult<ReckonDivideOrderDetailResult> queryDODPage(ReckonDivideOrderDetailParam param, HttpServletRequest request) {
        if (StringUtils.isNotBlank(param.getOrgztypes())) {
            if (param.getOrgztypes().contains("7")) {
                //经纪会员 ，自营会员 才有历史查询  成交单查询权限  其他无  因此机构分润单据明细中成交单号不跳转
                param.setOrgztypes("7");
            } else if (param.getOrgztypes().contains("6")) {
                //经纪会员 ，自营会员 才有历史查询  成交单查询权限  其他无  因此机构分润单据明细中成交单号不跳转
                param.setOrgztypes("6");
            }
        } else {
            //既不是经纪会员也不是自营会员
            param.setOrgztypes("0");
        }

        IPage<ReckonDivideOrderDetailResult> page = new Page<>(param.getPageNum(), param.getPageSize());
        IPage<ReckonDivideOrderDetailResult> resultIPage;
        if (param.getTradefeetype() != null &&
                (param.getTradefeetype() == 103 || param.getTradefeetype() == 104 ||
                        param.getTradefeetype() == 107 ||
                        param.getTradefeetype() == 108 || param.getTradefeetype() == 109)) {
            resultIPage = detailMapper.queryDODPage(page, param);
        } else {
            String sp = iCommonService.getSysparmById(SysConstants.SYSPARAM_CODE_DIVIDE);
            if (sp != null && sp.equals("2")) {
                ReckonDivideOrderDetailParam detail = new ReckonDivideOrderDetailParam();
                detail.setSearchtype(param.getSearchtype());
                if (param.getMemberuserid() != null)
                    detail.setMemberuserid(param.getMemberuserid());
                if (param.getParentuserid() != null)
                    detail.setParentuserid(param.getParentuserid());
                if (param.getGoodsid() != null)
                    detail.setGoodsid(param.getGoodsid());
                if (param.getTradefeetype() != null)
                    detail.setTradefeetype(param.getTradefeetype());
                if (param.getStartDate() != null)
                    detail.setStartDate(param.getStartDate());
                if (param.getEndDate() != null)
                    detail.setEndDate(param.getEndDate());
                if (param.getAreatype() != null) {
                    detail.setAreatype(param.getAreatype());
                }
                if (param.getAreaid() != null) {
                    detail.setAreaid(param.getAreaid());
                }
                resultIPage = detailMapper.queryReckonAGDivideDetail(page, detail);
            } else {
                resultIPage = detailMapper.queryDODPage(page, param);
            }
        }
        PageResult<ReckonDivideOrderDetailResult> 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<RefUserResult> queryRefUserSelect(String searchcode, HttpServletRequest request) {
        Systemmanager systemmanager = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("LOGINCODE", iCommonService.getUserLoginCode(request)));
        Long refereeuserid = systemmanager.getAreauserid();
        List<RefUserResult> results = iTaaccountMapper.queryRefUserSelect(searchcode, refereeuserid);
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"), results);
    }

    @Override
    public PageResult<TradeQueryResult> queryTrade(TradeQueryParam param, HttpServletRequest request) {
        if (param.getCycletype() == 4) {
            // 周数不足两位前面补0 #5732 推荐成交报表-周报表查不到数据 -- 重构成公共函数
            param.setCycletime(DateTimeUtils.getYearWeekNum(param.getCycletime()));
        } else {
            param.setCycletime(formatDate(param.getCycletype(), param.getCycletime(), param.getQuarter()));
        }
        IPage<TradeQueryResult> page = new Page<>(param.getPageNum(), param.getPageSize());
        IPage<TradeQueryResult> resultIPage = detailMapper.queryTrade(page, param);
        PageResult<TradeQueryResult> 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 PageResult<OrgReportQueryResult> orgReportQuery(OrgReportQueryParam param, HttpServletRequest request) {
        Systemmanager systemmanager = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("LOGINCODE", iCommonService.getUserLoginCode(request)));
        PageResult<OrgReportQueryResult> pageResult = new PageResult<>();
        if (!iCommonService.checkTaaccountReport(systemmanager, param.getAccountid())) {
            pageResult.setCode(Constants.Error_Code_Design);
            pageResult.setMessage(AjaxResult.dealMsg(MessageType.QUERY_ERROR_CODE_004.getCode(), request.getHeader("Accept-Language")));
            return pageResult;
        }
        if (systemmanager.getReletype() != 1) {
            if (("," + param.getOrgztypes() + ",").contains(",3,")) {
                param.setChangeflag(3);
            }
            param.setUserid(systemmanager.getAreauserid());
        }
        if (param.getCycletype() == 2) {
            //季报表
            param.setReckondate(param.getReckondate() + param.getQuarter());
            param.setReckondateend(param.getReckondateend() + param.getQuarterend());
        }
        IPage<OrgReportQueryResult> page = new Page<>(param.getPageNum(), param.getPageSize());
        IPage<OrgReportQueryResult> resultIPage;
        if (param.getCycletype() == 0) {
            //日报表
            resultIPage = detailMapper.queryOrgReckonSum(page, param);
        } else {
            resultIPage = detailMapper.queryOrgReportSum(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 orgReportQueryExport(OrgReportQueryParam param, HttpServletRequest request) {
        try {
            Systemmanager systemmanager = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("LOGINCODE", iCommonService.getUserLoginCode(request)));
            if (systemmanager.getReletype() != 1) {
                if (("," + param.getOrgztypes() + ",").contains(",3,")) {
                    param.setChangeflag(3);
                }
                param.setUserid(systemmanager.getAreauserid());
            }
            if (param.getCycletype() == 2) {
                //季报表
                param.setReckondate(param.getReckondate() + param.getQuarter());
                param.setReckondateend(param.getReckondateend() + param.getQuarterend());
            }
            String fileName = "经纪会员报表_" + DateTimeUtils.getDateTime("yyyyMMdd");
            List<OrgReportQueryResult> resultIPage;
            if (param.getCycletype() == 0) {
                //日报表
                resultIPage = detailMapper.queryOrgReckonSum(param);
            } else {
                resultIPage = detailMapper.queryOrgReportSum(param);
            }
            if (CollectionUtils.isEmpty(resultIPage)) {
                return AjaxResult.error(Constants.Error_Code_Design, MessageType.QUERY_ERROR_CODE_005.getCode(), request.getHeader("Accept-Language"));
            }
            ExportResult exportResult = ExportUtil.write(fileName, OrgReportQueryResult.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"));
        }
    }

    @Override
    public PageResult<InvestorReportQueryResult> investorReportQuery(InvestorReportQueryParam param, HttpServletRequest request) {
        Systemmanager systemmanager = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("LOGINCODE", iCommonService.getUserLoginCode(request)));
        if (systemmanager.getReletype() != 1) {
            if (("," + param.getOrgztypes() + ",").contains(",3,")) {
                param.setChangeflag(3);
            }
            param.setParentuserid(systemmanager.getAreauserid());
        }
        //周、月、季、年、全
        if (param.getCycletype() == 2) {
            //季报表
            param.setReckondate(param.getReckondate() + param.getQuarter());
            param.setReckondateend(param.getReckondateend() + param.getQuarterend());
        }
        IPage<InvestorReportQueryResult> page = new Page<>(param.getPageNum(), param.getPageSize());
        IPage<InvestorReportQueryResult> resultIPage;
        if (param.getCycletype() == 0) {
            resultIPage = detailMapper.queryReckonDayTa(page, param);
        } else {
            resultIPage = detailMapper.queryReportTa(page, param);
        }
        PageResult<InvestorReportQueryResult> 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<ReportTaaccount> taaccountReportQuery(TaAccountReportParam param, HttpServletRequest request) {
        if (param.getCycletype() == 4) {
            // 周数不足两位前面补0 #5732 推荐成交报表-周报表查不到数据 -- 重构成公共函数
            String cycletime = DateTimeUtils.getYearWeekNum(param.getCycletime());
            param.setCycletime(cycletime);
        } else {
            param.setCycletime(formatDate(param.getCycletype(), param.getCycletime(), param.getQuarter()));
        }
        ReportTaaccount reportTaaccount = new ReportTaaccount();
        if (param.getCycletype() != 0) {
            ReportTaaccount result = iReportTaaccountMapper.selectOne(new QueryWrapper<ReportTaaccount>()
                    .eq(param.getAccountid() != null, "accountid", param.getAccountid())
                    .eq(StringUtils.isNotBlank(param.getCycletime()), "cycletime", param.getCycletime())
                    .eq(param.getCycletype() != null, "cycletype", param.getCycletype()));
            if (Objects.nonNull(result)) BeanUtils.copyProperties(result, reportTaaccount);
        } else {
            ReckonDaytaaccount result = iReckonDaytaaccountMapper.selectOne(new QueryWrapper<ReckonDaytaaccount>()
                    .eq(param.getAccountid() != null, "accountid", param.getAccountid())
                    .eq(StringUtils.isNotBlank(param.getCycletime()), "reckondate", param.getCycletime()));
            if (Objects.nonNull(result)) {
                BeanUtils.copyProperties(result, reportTaaccount);
                reportTaaccount.setCycletime(result.getReckondate());
            }
        }
        String value = iCommonService.getSysparmById("082") == null ? "0" : iCommonService.getSysparmById("082");
        /*  #68530
         * 其他收入 = 原其他收入 - （收到延期交割补偿费 + 收到货款）
         * 其他支出 = 原其他支出 - （支出延期交割补偿费 + 支出货款）
         */
        if ("1".equals(value)) {
            BigDecimal income = dealNull(reportTaaccount.getDeliverycompensationfeein()).add(dealNull(reportTaaccount.getDeliveryamountin()));
            reportTaaccount.setOtherincome(dealNull(reportTaaccount.getOtherincome()).subtract(income));
            BigDecimal pay = dealNull(reportTaaccount.getDeliverycompensationfeeout()).add(dealNull(reportTaaccount.getDeliveryamountout()));
            reportTaaccount.setOtherpay(dealNull(reportTaaccount.getOtherpay()).subtract(pay));
        }
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"), reportTaaccount);
    }

    public BigDecimal dealNull(BigDecimal bigDecimal) {
        return bigDecimal == null ? BigDecimal.ZERO : bigDecimal.setScale(2, RoundingMode.HALF_UP);
    }

    @Override
    public PageResult<HolderTotalResult> holdertotalquery(TaAccountReportParam param, HttpServletRequest request) {
        if (param.getCycletype() == 4) {
            // 周数不足两位前面补0 #5732 推荐成交报表-周报表查不到数据 -- 重构成公共函数
            String cycletime = DateTimeUtils.getYearWeekNum(param.getCycletime());
            param.setCycletime(cycletime);
        } else {
            param.setCycletime(formatDate(param.getCycletype(), param.getCycletime(), param.getQuarter()));
        }
        param.setExcludetrademodelarray(new String[]{"40", "41", "48", "51"});
        IPage<HolderTotalResult> page = new Page<>(param.getPageNum(), param.getPageSize());
        IPage<HolderTotalResult> resultIPage = detailMapper.tradeposition(page, param);
        PageResult<HolderTotalResult> 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 PageResult<WrPositionResult> wrpositionquery(TaAccountReportParam param, HttpServletRequest request) {
        if (param.getCycletype() == 4) {
            // 周数不足两位前面补0 #5732 推荐成交报表-周报表查不到数据 -- 重构成公共函数
            String cycletime = DateTimeUtils.getYearWeekNum(param.getCycletime());
            param.setCycletime(cycletime);
        } else {
            param.setCycletime(formatDate(param.getCycletype(), param.getCycletime(), param.getQuarter()));
        }
        IPage<WrPositionResult> page = new Page<>(param.getPageNum(), param.getPageSize());
        IPage<WrPositionResult> resultIPage = detailMapper.wrposition(page, param);
        PageResult<WrPositionResult> 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 PageResult<TradeReportQueryResult> tradequery(TaAccountReportParam param, HttpServletRequest request) {
        if (param.getCycletype() == 4) {
            // 周数不足两位前面补0 #5732 推荐成交报表-周报表查不到数据 -- 重构成公共函数
            String cycletime = DateTimeUtils.getYearWeekNum(param.getCycletime());
            param.setCycletime(cycletime);
        } else {
            param.setCycletime(formatDate(param.getCycletype(), param.getCycletime(), param.getQuarter()));
        }
        IPage<TradeReportQueryResult> page = new Page<>(param.getPageNum(), param.getPageSize());
        IPage<TradeReportQueryResult> resultIPage = detailMapper.tradequery(page, param);
        PageResult<TradeReportQueryResult> 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<ReportPlateformpp> accountppquery(TaAccountReportParam param, HttpServletRequest request) {
        if (param.getCycletype() == 4) {
            // 周数不足两位前面补0 #5732 推荐成交报表-周报表查不到数据 -- 重构成公共函数
            String cycletime = DateTimeUtils.getYearWeekNum(param.getCycletime());
            param.setCycletime(cycletime);
        } else {
            param.setCycletime(formatDate(param.getCycletype(), param.getCycletime(), param.getQuarter()));
        }
        ReportPlateformpp reportPlateformpp = new ReportPlateformpp();
        if (param.getCycletype() != 0) {
            ReportPlateformpp result = iReportPlateformppMapper.selectOne(new QueryWrapper<ReportPlateformpp>()
                    .eq(StringUtils.isNotBlank(param.getCycletime()), "cycletime", param.getCycletime())
                    .eq(param.getCycletype() != null, "cycletype", param.getCycletype()));
            if (Objects.nonNull(result)) BeanUtils.copyProperties(result, reportPlateformpp);
        } else {
            ReckonDayaccountpp result = iReckonDayaccountppMapper.selectOne(new QueryWrapper<ReckonDayaccountpp>()
                    .eq(param.getAccountid() != null, "accountid", param.getAccountid())
                    .eq(StringUtils.isNotBlank(param.getCycletime()), "reckondate", param.getCycletime()));
            if (Objects.nonNull(result)) {
                BeanUtils.copyProperties(result, reportPlateformpp);
                reportPlateformpp.setCycletime(result.getReckondate());
            }
        }
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"), reportPlateformpp);
    }

    @Override
    public AjaxResult<TAAccountChildrenSelect> queryTAAccountChildrenSelect(String searchcode, HttpServletRequest request) {
        Systemmanager systemmanager = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("LOGINCODE", iCommonService.getUserLoginCode(request)));
        List<TAAccountChildrenSelect> result = iTaaccountMapper.queryChildren(searchcode, systemmanager.getAreauserid());
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"), result);
    }

    @Override
    public PageResult<CusBankReportResult> cusbank(CusBankReportParam param, HttpServletRequest request) {
        IPage<CusBankReportResult> page = new Page<>(param.getPageNum(), param.getPageSize());
        IPage<CusBankReportResult> resultIPage = detailMapper.queryCusBank(page, param);
        PageResult<CusBankReportResult> 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 cusbankexport(CusBankReportParam param, HttpServletRequest request) {
        try {
            String fileName = "银行资金报表_" + DateTimeUtils.getDateTime("yyyyMMdd");
            List<CusBankReportResult> resultIPage = detailMapper.queryCusBank(param);
            if (CollectionUtils.isEmpty(resultIPage)) {
                return AjaxResult.error(Constants.Error_Code_Design, MessageType.QUERY_ERROR_CODE_005.getCode(), request.getHeader("Accept-Language"));
            }
            ExportResult exportResult = ExportUtil.write(fileName, CusBankReportResult.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"));
        }
    }

    @Override
    public PageResult<ManageDivReportResult> managediv(CusBankReportParam param, HttpServletRequest request) {
        IPage<ManageDivReportResult> page = new Page<>(param.getPageNum(), param.getPageSize());
        IPage<ManageDivReportResult> resultIPage = detailMapper.managediv(page, param);
        PageResult<ManageDivReportResult> 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 managedivexport(CusBankReportParam param, HttpServletRequest request) {
        try {
            String fileName = "服务费分润报表_" + DateTimeUtils.getDateTime("yyyyMMdd");
            List<ManageDivReportResult> resultIPage = detailMapper.managediv(param);
            if (CollectionUtils.isEmpty(resultIPage)) {
                return AjaxResult.error(Constants.Error_Code_Design, MessageType.QUERY_ERROR_CODE_005.getCode(), request.getHeader("Accept-Language"));
            }
            ExportResult exportResult = ExportUtil.write(fileName, ManageDivReportResult.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"));
        }
    }

    @Override
    public AjaxResult investorReportExport(InvestorReportQueryParam param, HttpServletRequest request) {
        try {
            String fileName = "交易商资金报表_" + DateTimeUtils.getDateTime("yyyyMMdd");
            Systemmanager systemmanager = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("LOGINCODE", iCommonService.getUserLoginCode(request)));
            if (systemmanager.getReletype() != 1) {
                if (("," + param.getOrgztypes() + ",").contains(",3,")) {
                    param.setChangeflag(3);
                }
                param.setParentuserid(systemmanager.getAreauserid());
            }
            //周、月、季、年、全
            if (param.getCycletype() == 2) {
                //季报表
                param.setReckondate(param.getReckondate() + param.getQuarter());
                param.setReckondateend(param.getReckondateend() + param.getQuarterend());
            }
            List<InvestorReportQueryResult> resultIPage;
            if (param.getCycletype() == 0) {
                resultIPage = detailMapper.queryReckonDayTa(param);
            } else {
                resultIPage = detailMapper.queryReportTa(param);
            }
            if (CollectionUtils.isEmpty(resultIPage)) {
                return AjaxResult.error(Constants.Error_Code_Design, MessageType.QUERY_ERROR_CODE_005.getCode(), request.getHeader("Accept-Language"));
            }
            ExportResult exportResult = ExportUtil.write(fileName, InvestorReportQueryResult.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"));
        }
    }

    @Override
    public AjaxResult investorReportOrgExport(InvestorReportQueryParam param, HttpServletRequest request) {
        try {
            String fileName = "机构资金报表_" + DateTimeUtils.getDateTime("yyyyMMdd");
            Systemmanager systemmanager = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("LOGINCODE", iCommonService.getUserLoginCode(request)));
            if (systemmanager.getReletype() != 1) {
                if (("," + param.getOrgztypes() + ",").contains(",3,")) {
                    param.setChangeflag(3);
                }
                param.setParentuserid(systemmanager.getAreauserid());
            }
            //周、月、季、年、全
            if (param.getCycletype() == 2) {
                //季报表
                param.setReckondate(param.getReckondate() + param.getQuarter());
                param.setReckondateend(param.getReckondateend() + param.getQuarterend());
            }
            List<InvestorReportQueryResult> resultIPage;
            if (param.getCycletype() == 0) {
                resultIPage = detailMapper.queryReckonDayTa(param);
            } else {
                resultIPage = detailMapper.queryReportTa(param);
            }
            List<InvestorReportOrgResult> results = new ArrayList<>();
            for (InvestorReportQueryResult investorReportQueryResult : resultIPage) {
                InvestorReportOrgResult result = new InvestorReportOrgResult();
                BeanUtils.copyProperties(investorReportQueryResult, result);
                results.add(result);
            }
            if (CollectionUtils.isEmpty(resultIPage)) {
                return AjaxResult.error(Constants.Error_Code_Design, MessageType.QUERY_ERROR_CODE_005.getCode(), request.getHeader("Accept-Language"));
            }
            ExportResult exportResult = ExportUtil.write(fileName, InvestorReportOrgResult.class, results);
            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"));
        }
    }

    @Override
    public AjaxResult rerun(String startDateStr, String endDateStr, HttpServletRequest request) {
        Systemmanager systemmanager = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("LOGINCODE", iCommonService.getUserLoginCode(request)));
        log.info("{},call report,startDate:{},endDate:{}", systemmanager.getUsername(), startDateStr, endDateStr);
        Object[] param = {startDateStr, endDateStr};
        try {
            Date startDate = DateTimeUtils.parseDate(startDateStr, DateTimeUtils.DATE_CHAR_PATTERN);
            Date endDate = DateTimeUtils.parseDate(endDateStr, DateTimeUtils.DATE_CHAR_PATTERN);
            if (startDate.compareTo(endDate) == 0) {
                detailMapper.execReportMonthType(startDate);
            } else {
                while (startDate.compareTo(endDate) < 0) {
                    detailMapper.execReportMonthType(startDate);
                    log.info("tradedate:{}", startDate);
                    startDate = DateTimeUtils.addDay(startDate, 7);
                }
                if (startDate.compareTo(endDate) > 0) {
                    detailMapper.execReportMonthType(endDate);
                    log.info("tradedate:{}", endDate);
                }
            }
        } catch (Exception e) {
            return AjaxResult.error(Constants.Error_Code_Design, MessageType.REPORT_ERROR_CODE_001.getCode(), param, request.getHeader("Accept-Language"));
        }
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"));
    }

    @Override
    public AjaxResult<Map<Long, List<GoodsReportResult>>> daygoodscount(GoodsReportParam param, HttpServletRequest request) {
        Systemmanager systemmanager = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("LOGINCODE", iCommonService.getUserLoginCode(request)));
        //平台登陆查所有    运营机构登陆
        if (systemmanager.getReletype() != 1) {
            param.setAreauserid(systemmanager.getAreauserid());
        }
        List<GoodsReportResult> list;
        if (param.getCycletype() == 0) {
            list = iGoodsMapper.queryByDate(param);
        } else {
            //周、月、季、年报表
            if (param.getCycletype() == 2) {
                //季报表
                param.setReckondate(param.getReckondate() + param.getQuarter());
            }
            list = iGoodsMapper.queryByOther(param);
        }
        //将List转换为Map
        Map<Long, List<GoodsReportResult>> resultMap = list.stream()
                .collect(Collectors.groupingBy(
                        GoodsReportResult::getMarketid,
                        Collectors.toList()
                ));

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

    @Override
    public AjaxResult goodscountexport(GoodsReportParam param, HttpServletRequest request) {
        try {
            String fileName = "商品交易报表_" + DateTimeUtils.getDateTime("yyyyMMdd");
            Systemmanager systemmanager = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("LOGINCODE", iCommonService.getUserLoginCode(request)));
            //平台登陆查所有    运营机构登陆
            if (systemmanager.getReletype() != 1) {
                param.setAreauserid(systemmanager.getAreauserid());
            }
            List<GoodsReportResult> list;
            if (param.getCycletype() == 0) {
                list = iGoodsMapper.queryByDate(param);
            } else {
                //周、月、季、年报表
                if (param.getCycletype() == 2) {
                    //季报表
                    param.setReckondate(param.getReckondate() + param.getQuarter());
                }
                list = iGoodsMapper.queryByOther(param);
            }
            if (CollectionUtils.isEmpty(list)) {
                return AjaxResult.error(Constants.Error_Code_Design, MessageType.QUERY_ERROR_CODE_005.getCode(), request.getHeader("Accept-Language"));
            }
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            EasyExcel.write(byteArrayOutputStream)
                    .head(GoodsReportResult.class)
                    .registerWriteHandler(new GoodsMergeStrategy())
                    .excelType(ExcelTypeEnum.XLSX)
                    .sheet(fileName)
                    .doWrite(list);
            byte[] bytes = byteArrayOutputStream.toByteArray();
            ExportResult result = ExportResult.builder().fileName(fileName).base64(Base64.getEncoder().encodeToString(bytes)).build();
            return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"), result);
        } 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 String formatDate(Integer cycletype, String cycletime, Integer quarter) {
        String rdate = null;
        if (cycletype == 0) {
            //日报表
            if (cycletime != null && !cycletime.isEmpty()) {
                try {
                    Date date = DateTimeUtils.parseDate(cycletime);
                    rdate = DateTimeUtils.format(date, DateTimeUtils.DATE_CHAR_PATTERN);
                } catch (ParseException e) {
                    log.error(e.getMessage());
                }
            }
        } else if (cycletype == 1) {
            //月 报表
            rdate = cycletime.replaceAll("-", "");
        } else if (cycletype == 2) {
            //季 报表
            rdate = cycletime.replaceAll("-", "") + quarter;
        } else if (cycletype == 3) {
            //年 报表
            rdate = cycletime.replaceAll("-", "");
        } else if (cycletype == 4) {
            //周 报表
            rdate = cycletime.replaceAll("-", "");
        } else if (cycletype == 5) {
            rdate = "0";
        }
        return rdate;
    }
}
