package com.hzs.report.member.controller.manage;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hzs.common.core.annotation.Log;
import com.hzs.common.core.constant.CountryConstants;
import com.hzs.common.core.constant.TableNameConstants;
import com.hzs.common.core.constant.msg.ConfigMsgConstants;
import com.hzs.common.core.domain.R;
import com.hzs.common.core.enums.*;
import com.hzs.common.core.utils.DateUtils;
import com.hzs.common.core.utils.StringUtils;
import com.hzs.common.core.utils.poi.ExcelUtil;
import com.hzs.common.core.web.controller.BaseController;
import com.hzs.common.core.web.domain.AjaxResult;
import com.hzs.common.core.web.page.TableDataInfo;
import com.hzs.common.domain.member.base.CuMember;
import com.hzs.common.domain.report.stat.CuLianchuangDataStat;
import com.hzs.common.security.utils.SecurityUtils;
import com.hzs.common.util.TransactionUtils;
import com.hzs.member.achieve.ICuMemberSettlePeriodServiceApi;
import com.hzs.member.base.IMemberServiceApi;
import com.hzs.report.member.service.ICuLianchuangDataStatService;
import com.hzs.report.member.service.MemberReportService;
import com.hzs.report.member.vo.AbroadDataStatVO;
import com.hzs.report.member.vo.CuLianchuangDataStatHistoryVO;
import com.hzs.report.member.vo.CuLianchuangDataStatVO;
import com.hzs.report.member.vo.HomeDataStatVO;
import com.hzs.system.base.ICurrencyServiceApi;
import com.hzs.system.base.dto.CurrencyDTO;
import javafx.util.Pair;
import org.apache.catalina.security.SecurityUtil;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.math.BigDecimal;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * <p>
 * 联创报表统计 前端控制器
 * </p>
 *
 * @author zhangjing
 * @since 2023-10-19
 */
@RestController
@RequestMapping("/manager/cu-lianchuang-data-stat")
public class CuLianchuangDataStatController extends BaseController {

    @Autowired
    private ICuLianchuangDataStatService lcStatService;
    @DubboReference
    private IMemberServiceApi iMemberServiceApi;
    @DubboReference
    private ICurrencyServiceApi currencyServiceApi;
    @DubboReference
    private ICuMemberSettlePeriodServiceApi cuMemberSettlePeriodService;
    @Autowired
    private MemberReportService memberReportService;


    /**
     * @description: 查询联创数据报表(优化后)
     * @author: zhang jing
     * @date: 2024/7/17 13:56
     * @param: [lcVO]
     * @return: com.hzs.common.core.web.page.TableDataInfo
     **/
    @Log(module = EOperationModule.STATISTIC_ANALYSIS, business = EOperationBusiness.LIANCHUANG_DATA_STAT, method = EOperationMethod.SELECT)
    @GetMapping("/list")
    public TableDataInfo list(CuLianchuangDataStatVO lcVO) {
        List<CuLianchuangDataStatVO> list = new ArrayList<>();
        List<CuLianchuangDataStatVO> allList = new ArrayList<>();
        Integer systemType = SecurityUtils.getSystemType();
        if (StringUtils.isEmpty(lcVO.getPayTime())) {
            Date date = DateUtils.currentDate();
            lcVO.setPayTime(DateUtils.parseDateTimeToStr(DateUtils.YYYY_MM_DD,date));
        }
        QueryWrapper<CuLianchuangDataStat> queryWrapper = new QueryWrapper<>();
        if(lcVO.getType()==null){
            lcVO.setType(ESheetType.SHEET_TYPE1.getValue());
        }
        queryWrapper.eq("TYPE", lcVO.getType());
        queryWrapper.eq("SYSTEM_TYPE", systemType);
        if (StringUtils.isNotEmpty(lcVO.getVertexCode())) {
            queryWrapper.eq("VERTEX_CODE", lcVO.getVertexCode());
        }
        queryWrapper.orderByAsc("CREATION_TIME");
        List<CuLianchuangDataStat> lcList = lcStatService.list(queryWrapper);
        if(CollectionUtil.isEmpty(lcList)){
            return getDataTable(list);
        }
        List<Long> lcMemberStr = new ArrayList<>();
            lcList.forEach(itm -> {
                if (StringUtils.isNotEmpty(itm.getAddRegion())) {
                    lcMemberStr.addAll(Arrays.stream(itm.getAddRegion().split(","))
                            .map(Long::parseLong)
                            .collect(Collectors.toList()));
                }
                if (StringUtils.isNotEmpty(itm.getReduceRegion())) {
                    lcMemberStr.addAll(Arrays.stream(itm.getReduceRegion().split(","))
                            .map(Long::parseLong)
                            .collect(Collectors.toList()));
                }
            });

        //去重lcMemberStr
        List<Long> uniqueList = new ArrayList<>(new LinkedHashSet<>(lcMemberStr));
        lcVO.setEndDate(lcVO.getPayTime());
        //查询日期月份的第一天
        lcVO.setStartDate(DateUtils.currentMonthFirstDateStr(DateUtils.parseStringToDate(lcVO.getPayTime())));
        //上个月第一天和上个月最后一天
        lcVO.setBeforeStaDate(DateUtils.beforeMonthFirstDateStr(DateUtils.parseStringToDate(lcVO.getPayTime())));
        lcVO.setBeforeEndDate(DateUtils.beforeMonthLastDateStr(DateUtils.parseStringToDate(lcVO.getPayTime())));
        lcVO.setPkCountry(SecurityUtils.getPkCountry());
        //多线程
        uniqueList.parallelStream().forEach(itm->{
            List<CuLianchuangDataStatVO> sonList = lcStatService.newLcStatListByOrdeType(lcVO,itm);
            allList.addAll(sonList);
        });
        //按照会员ID进行分组
        Map<Long, CuLianchuangDataStatVO> allListstMap = allList.stream()
                .collect(Collectors.toMap(CuLianchuangDataStatVO::getPkMember, Function.identity()));
        if(CollectionUtil.isNotEmpty(lcList)){
            lcList.forEach(item -> list.add(BeanUtil.copyProperties(item, CuLianchuangDataStatVO.class)));
            //根据匹配的规则添加业绩金额数据
            for(CuLianchuangDataStatVO clos:list){
                clos.setPayTime(lcVO.getPayTime());
                if (StringUtils.isNotEmpty(clos.getAddRegion())) {
                    List<Long> addRegionList = Arrays.stream(clos.getAddRegion().split(","))
                            .map(Long::parseLong)
                            .collect(Collectors.toList());
                    clos.setAddRegionList(addRegionList);
                }

                if (StringUtils.isNotEmpty(clos.getReduceRegion())) {
                    List<Long> reduceRegionList = Arrays.stream(clos.getReduceRegion().split(","))
                            .map(Long::parseLong)
                            .collect(Collectors.toList());
                    clos.setReduceRegionList(reduceRegionList);
                }
                calculateAmount(clos,allListstMap);
            }
        }
            if (SecurityUtils.getPkCountry().equals(CountryConstants.CHINA_COUNTRY)) {
                R<CurrencyDTO> currency = currencyServiceApi.getCurrency(SecurityUtils.getPkCountry());
                if (CollectionUtil.isNotEmpty(list)) {
                    list.forEach(itm -> {
                        BigDecimal inExchangeRate = currency.getData().getInExchangeRate();
                        itm.setFirstPurchasePv(itm.getFirstPurchasePv().multiply(inExchangeRate));
                        itm.setFirstPurchaseSumPv(itm.getFirstPurchaseSumPv().multiply(inExchangeRate));
                    });
                }
            }
        return getDataTable(list);
    }
    //根据规则计算业绩或金额
    public void calculateAmount(CuLianchuangDataStatVO clos, Map<Long, CuLianchuangDataStatVO> allListstMap) {
        //加区新增,累计,上个月,金额业绩
        BigDecimal addAm = BigDecimal.ZERO;
        BigDecimal addPv = BigDecimal.ZERO;
        BigDecimal addSumAm = BigDecimal.ZERO;
        BigDecimal addSumPv = BigDecimal.ZERO;
        BigDecimal addBfSumAm = BigDecimal.ZERO;
        BigDecimal addBfSumPv = BigDecimal.ZERO;
        //减区新增,累计,上个月,金额业绩
        BigDecimal redAm = BigDecimal.ZERO;
        BigDecimal redPv = BigDecimal.ZERO;
        BigDecimal redSumAm = BigDecimal.ZERO;
        BigDecimal redSumPv = BigDecimal.ZERO;
        BigDecimal redBfSumAm = BigDecimal.ZERO;
        BigDecimal redBfSumPv = BigDecimal.ZERO;

        //加区
        for (Long ad : clos.getAddRegionList()) {
            CuLianchuangDataStatVO data = allListstMap.get(ad);
            addAm = addAm.add(data.getFirstPurchaseMo());
            addPv = addPv.add(data.getFirstPurchasePv());
            addSumAm = addSumAm.add(data.getFirstPurchaseSumMo());
            addSumPv = addSumPv.add(data.getFirstPurchaseSumPv());
            addBfSumAm = addBfSumAm.add(data.getBeforePurchaseSumMo());
            addBfSumPv = addBfSumPv.add(data.getBeforePurchaseSumPv());
        }
        //减区
        if(CollectionUtil.isNotEmpty(clos.getReduceRegionList())){
            for (Long re : clos.getReduceRegionList()) {
                CuLianchuangDataStatVO data = allListstMap.get(re);
                redAm = redAm.add(data.getFirstPurchaseMo());
                redPv = redPv.add(data.getFirstPurchasePv());
                redSumAm = redSumAm.add(data.getFirstPurchaseSumMo());
                redSumPv = redSumPv.add(data.getFirstPurchaseSumPv());
                redBfSumAm = redBfSumAm.add(data.getBeforePurchaseSumMo());
                redBfSumPv = redBfSumPv.add(data.getBeforePurchaseSumPv());
            }
        }
        clos.setFirstPurchaseMo(addAm.subtract(redAm));
        clos.setFirstPurchasePv(addPv.subtract(redPv));
        clos.setFirstPurchaseSumMo(addSumAm.subtract(redSumAm));
        clos.setFirstPurchaseSumPv(addSumPv.subtract(redSumPv));
        clos.setBeforePurchaseSumMo(addBfSumAm.subtract(redBfSumAm));
        clos.setBeforePurchaseSumPv(addBfSumPv.subtract(redBfSumPv));
    }

    /**
     * @description: 查询联创数据报表(历史数据)
     * @author: zhang jing
     * @date: 2024/5/31 17:00
     * @param: [lcVO]
     * @return: com.hzs.common.core.web.page.TableDataInfo
     **/
    @Log(module = EOperationModule.STATISTIC_ANALYSIS, business = EOperationBusiness.LIANCHUANG_DATA_STAT, method = EOperationMethod.SELECT)
    @GetMapping("/listHistory")
    public TableDataInfo listHistory(CuLianchuangDataStatVO lcVO) {
        List<CuLianchuangDataStatVO> list = new ArrayList<>();
        if (StringUtils.isEmpty(lcVO.getPayTime())) {
            return getDataTable(list);
        }
        Integer systemType = SecurityUtils.getSystemType();
        lcVO.setEndDate(lcVO.getPayTime());
        //获取前一天
        lcVO.setBeforeDate(DateUtils.beforeDateStr(1, ChronoUnit.DAYS, DateUtils.YYYY_MM_DD,lcVO.getPayTime()) );
        //查询日期月份的第一天
        lcVO.setStartDate(DateUtils.currentMonthFirstDateStr(DateUtils.parseStringToDate(lcVO.getPayTime())));
        //上个月最后一天
        lcVO.setBeforeEndDate(DateUtils.beforeMonthLastDateStr(DateUtils.parseStringToDate(lcVO.getPayTime())));
        //上上个月最后一天
        lcVO.setBeforeStaDate(DateUtils.beforeMonthLastDateStr(DateUtils.parseStringToDate(lcVO.getBeforeEndDate())));

        lcVO.setPkCountry(SecurityUtils.getPkCountry());
        //设置表名和期数
        setTableNames(lcVO);
        //表不存在则创建表
        if (memberReportService.selectExistTable(lcVO.getAchieveTableNameBeforeSta()) == 0) {
            memberReportService.createCuMemberAmountBoxTable(lcVO.getAchieveTableNameBeforeSta());
        }
        QueryWrapper<CuLianchuangDataStat> queryWrapper = new QueryWrapper<>();
        if(lcVO.getType()==null){
            lcVO.setType(ESheetType.SHEET_TYPE1.getValue());
        }
        queryWrapper.eq("TYPE", lcVO.getType());
        queryWrapper.eq("SYSTEM_TYPE", systemType);
        if (StringUtils.isNotEmpty(lcVO.getVertexCode())) {
            queryWrapper.eq("VERTEX_CODE", lcVO.getVertexCode());
        }
        queryWrapper.orderByAsc("CREATION_TIME");
        List<CuLianchuangDataStat> lcList = lcStatService.list(queryWrapper);
        if(CollectionUtil.isNotEmpty(lcList)){
            R<CurrencyDTO> currency = currencyServiceApi.getCurrency(SecurityUtils.getPkCountry());
            BigDecimal inExchangeRate = currency.getData().getInExchangeRate();
            List<CuLianchuangDataStatVO> finalList = list;
            lcList.forEach(item -> finalList.add(BeanUtil.copyProperties(item, CuLianchuangDataStatVO.class)));
            finalList.forEach(itm -> {
                List<Long> addRegionList = new ArrayList<>();
                List<Long> reduceRegionList = new ArrayList<>();
                if (StringUtils.isNotEmpty(itm.getAddRegion())) {
                    addRegionList.addAll(Arrays.stream(itm.getAddRegion().split(","))
                            .map(Long::parseLong)
                            .collect(Collectors.toList()));
                    itm.setAddRegionList(addRegionList);
                }
                if (StringUtils.isNotEmpty(itm.getReduceRegion())) {
                    reduceRegionList.addAll(Arrays.stream(itm.getReduceRegion().split(","))
                            .map(Long::parseLong)
                            .collect(Collectors.toList()));
                    itm.setReduceRegionList(reduceRegionList);
                }
                CuLianchuangDataStatVO clds=  lcStatService.getLianchuangDifference(lcVO,itm);
                itm.setFirstPurchaseMo(clds.getFirstPurchaseMo());
                itm.setFirstPurchaseSumMo(clds.getFirstPurchaseSumMo());
                itm.setBeforePurchaseSumMo(clds.getBeforePurchaseSumMo());
                if (SecurityUtils.getPkCountry().equals(CountryConstants.CHINA_COUNTRY)) {
                    itm.setFirstPurchasePv(clds.getFirstPurchasePv().multiply(inExchangeRate));
                    itm.setFirstPurchaseSumPv(clds.getFirstPurchaseSumPv().multiply(inExchangeRate));
                    itm.setBeforePurchaseSumPv(clds.getBeforePurchaseSumPv().multiply(inExchangeRate));
                }
            });
            return getDataTable(finalList);
        }
        return getDataTable(list);
    }

    /**
     * @description: 导出联创数据报表(历史数据)
     * @author: zhang jing
     * @date: 2023/10/19 16:08
     * @param: [response, lcVO]
     * @return: void
     **/
    @Log(module = EOperationModule.STATISTIC_ANALYSIS, business = EOperationBusiness.LIANCHUANG_DATA_STAT, method = EOperationMethod.EXPORT)
    @PostMapping("/exportHistory")
    public void exportHistory(HttpServletResponse response, CuLianchuangDataStatVO lcVO) {
        List<CuLianchuangDataStatVO> list = new ArrayList<>();
        if (StringUtils.isEmpty(lcVO.getPayTime())) {
            return;
        }
        Integer systemType = SecurityUtils.getSystemType();
        lcVO.setEndDate(lcVO.getPayTime());
        //获取前一天
        lcVO.setBeforeDate(DateUtils.beforeDateStr(1, ChronoUnit.DAYS, DateUtils.YYYY_MM_DD,lcVO.getPayTime()) );
        //查询日期月份的第一天
        lcVO.setStartDate(DateUtils.currentMonthFirstDateStr(DateUtils.parseStringToDate(lcVO.getPayTime())));
        //上个月最后一天
        lcVO.setBeforeEndDate(DateUtils.beforeMonthLastDateStr(DateUtils.parseStringToDate(lcVO.getPayTime())));
        //上上个月最后一天
        lcVO.setBeforeStaDate(DateUtils.beforeMonthLastDateStr(DateUtils.parseStringToDate(lcVO.getBeforeEndDate())));

        lcVO.setPkCountry(SecurityUtils.getPkCountry());
        //设置表名和期数
        setTableNames(lcVO);
        //表不存在则创建表
        if (memberReportService.selectExistTable(lcVO.getAchieveTableNameBeforeSta()) == 0) {
            memberReportService.createCuMemberAmountBoxTable(lcVO.getAchieveTableNameBeforeSta());
        }
        QueryWrapper<CuLianchuangDataStat> queryWrapper = new QueryWrapper<>();
        if(lcVO.getType()==null){
            lcVO.setType(ESheetType.SHEET_TYPE1.getValue());
        }
        queryWrapper.eq("TYPE", lcVO.getType());
        queryWrapper.eq("SYSTEM_TYPE", systemType);
        if (StringUtils.isNotEmpty(lcVO.getVertexCode())) {
            queryWrapper.eq("VERTEX_CODE", lcVO.getVertexCode());
        }
        queryWrapper.orderByAsc("CREATION_TIME");
        List<CuLianchuangDataStat> lcList = lcStatService.list(queryWrapper);
        if(CollectionUtil.isNotEmpty(lcList)){
            R<CurrencyDTO> currency = currencyServiceApi.getCurrency(SecurityUtils.getPkCountry());
            BigDecimal inExchangeRate = currency.getData().getInExchangeRate();
            List<CuLianchuangDataStatVO> finalList = list;
            lcList.forEach(item -> finalList.add(BeanUtil.copyProperties(item, CuLianchuangDataStatVO.class)));
            finalList.forEach(itm -> {
                List<Long> addRegionList = new ArrayList<>();
                List<Long> reduceRegionList = new ArrayList<>();
                if (StringUtils.isNotEmpty(itm.getAddRegion())) {
                    addRegionList.addAll(Arrays.stream(itm.getAddRegion().split(","))
                            .map(Long::parseLong)
                            .collect(Collectors.toList()));
                    itm.setAddRegionList(addRegionList);
                }
                if (StringUtils.isNotEmpty(itm.getReduceRegion())) {
                    reduceRegionList.addAll(Arrays.stream(itm.getReduceRegion().split(","))
                            .map(Long::parseLong)
                            .collect(Collectors.toList()));
                    itm.setReduceRegionList(reduceRegionList);
                }
                CuLianchuangDataStatVO clds=  lcStatService.getLianchuangDifference(lcVO,itm);
                itm.setFirstPurchaseMo(clds.getFirstPurchaseMo());
                itm.setFirstPurchaseSumMo(clds.getFirstPurchaseSumMo());
                itm.setBeforePurchaseSumMo(clds.getBeforePurchaseSumMo());
                if (SecurityUtils.getPkCountry().equals(CountryConstants.CHINA_COUNTRY)) {
                    itm.setFirstPurchasePv(clds.getFirstPurchasePv().multiply(inExchangeRate));
                    itm.setFirstPurchaseSumPv(clds.getFirstPurchaseSumPv().multiply(inExchangeRate));
                    itm.setBeforePurchaseSumPv(clds.getBeforePurchaseSumPv().multiply(inExchangeRate));
                }
            });
            ExcelUtil<CuLianchuangDataStatVO> util = new ExcelUtil<>(CuLianchuangDataStatVO.class);
            util.exportExcel(response, finalList, "联创数据报表");
        }
        return;
    }

    // 辅助方法，用于从列表中获取某个属性的汇总值（例如，如果列表为空，则返回0或null）
    private <T, R> R getStatistic(List<T> list, Function<T, R> extractor) {
        if (CollectionUtil.isEmpty(list)) {
            return null; // 或者根据具体情况返回0或其他默认值
        }
        // 假设我们只需要列表中的第一个元素的值（例如，所有元素的值都应该是相同的）
        // 或者，您可能需要根据具体需求实现更复杂的聚合逻辑
        return extractor.apply(list.get(0));
    }

    //设置表名和期数
    private void setTableNames(CuLianchuangDataStatVO lcVO) {
        //当前日期月第一期
        Integer periodSta= cuMemberSettlePeriodService.getCuMemberSettlePeriodByDate(
                DateUtils.parseDateToStr(lcVO.getStartDate())).getData().getPkId();
        //当前时间期数
        Integer periodEnd= cuMemberSettlePeriodService.getCuMemberSettlePeriodByDate(
                DateUtils.parseDateToStr(lcVO.getEndDate())).getData().getPkId();
        Integer periodBef= cuMemberSettlePeriodService.getCuMemberSettlePeriodByDate(
                DateUtils.parseDateToStr(lcVO.getBeforeDate())).getData().getPkId();
        //上上个月最后一期
        Integer periodBeforeSta= cuMemberSettlePeriodService.getCuMemberSettlePeriodByDate(
                DateUtils.parseDateToStr(lcVO.getBeforeStaDate())).getData().getPkId();
        //上个月最后一期
        Integer periodBeforeEnd= cuMemberSettlePeriodService.getCuMemberSettlePeriodByDate(
                DateUtils.parseDateToStr(lcVO.getBeforeEndDate())).getData().getPkId();

        lcVO.setAchieveTableNameSta(TableNameConstants.CU_MEMBER_AMOUNT_BOX + periodSta);
        lcVO.setAchieveTableNameEnd(TableNameConstants.CU_MEMBER_AMOUNT_BOX + periodEnd);
        lcVO.setAchieveTableNameBef(TableNameConstants.CU_MEMBER_AMOUNT_BOX + periodBef);
        lcVO.setAchieveTableNameBeforeSta(TableNameConstants.CU_MEMBER_AMOUNT_BOX + periodBeforeSta);
        lcVO.setAchieveTableNameBeforeEnd(TableNameConstants.CU_MEMBER_AMOUNT_BOX + periodBeforeEnd);
    }

    //设置加区和减区
    private void processRegions(CuLianchuangDataStat itm) {
        if (StringUtils.isNotEmpty(itm.getAddRegion())) {
            List<Integer> addRegionList = Arrays.stream(itm.getAddRegion().split(","))
                    .map(Integer::parseInt)
                    .collect(Collectors.toList());
            itm.setAddRegionList(addRegionList);
        }

        if (StringUtils.isNotEmpty(itm.getReduceRegion())) {
            List<Integer> reduceRegionList = Arrays.stream(itm.getReduceRegion().split(","))
                    .map(Integer::parseInt)
                    .collect(Collectors.toList());
            itm.setReduceRegionList(reduceRegionList);
        }
    }


    /**
     * @description: 查询国内联创数据报表
     * @author: zhang jing
     * @date: 2023/10/19 16:02
     * @param: [lcVO]
     * @return: com.hzs.common.core.web.page.TableDataInfo
     **/
    @Log(module = EOperationModule.STATISTIC_ANALYSIS, business = EOperationBusiness.LIANCHUANG_HOME_DATA_STAT, method = EOperationMethod.SELECT)
    @GetMapping("/home-list")
    public TableDataInfo homeList(CuLianchuangDataStatVO lcVO) {
        List<CuLianchuangDataStatVO> list = new ArrayList<>();
        Date date = DateUtils.currentDate();
        if (StringUtils.isEmpty(lcVO.getPayTime())) {
            lcVO.setPayTime(DateUtils.parseDateTimeToStr(DateUtils.YYYY_MM_DD, DateUtils.beforeDate(1, ChronoUnit.DAYS, date)));
        }

        //查询联创数据报表条件表
        QueryWrapper<CuLianchuangDataStat> queryWrapper = new QueryWrapper();
        if(lcVO.getType()==null){
            lcVO.setType(ESheetType.SHEET_TYPE1.getValue());
        }
        queryWrapper.eq("TYPE", lcVO.getType());
        queryWrapper.orderByAsc("PK_ID");
        List<CuLianchuangDataStat> lcList = lcStatService.list(queryWrapper);
        if (CollectionUtil.isNotEmpty(lcList)) {
            List<CuLianchuangDataStatVO> finalList = list;
            lcList.forEach(itm -> {
                itm.setEndDate(lcVO.getPayTime());
                itm.setStartDate(DateUtils.currentMonthFirstDateStr(DateUtils.parseStringToDate(lcVO.getPayTime())));
                if (StringUtils.isNotEmpty(itm.getAddRegion())) {
                    List<Integer> addRegionList = Arrays.stream(itm.getAddRegion().split(","))
                            .map(Integer::parseInt)
                            .collect(Collectors.toList());
                    itm.setAddRegionList(addRegionList);
                }
                List<CuLianchuangDataStatVO> sonList = lcStatService.lcStatList(Arrays.asList(itm));
                finalList.addAll(sonList);
            });
            if (SecurityUtils.getPkCountry().equals(CountryConstants.CHINA_COUNTRY)) {
                R<CurrencyDTO> currency = currencyServiceApi.getCurrency(SecurityUtils.getPkCountry());
                if (CollectionUtil.isNotEmpty(list)) {
                    list.forEach(itm -> {
                        itm.setFirstPurchasePv(itm.getFirstPurchasePv().multiply(currency.getData().getInExchangeRate()));
                        itm.setFirstPurchaseSumPv(itm.getFirstPurchaseSumPv().multiply(currency.getData().getInExchangeRate()));
                    });
                }
            }
        }
        return getDataTable(list);
    }

    /**
     * @description: 查询国外联创数据报表
     * @author: zhang jing
     * @date: 2023/12/4 10:07
     * @param: [lcVO]
     * @return: com.hzs.common.core.web.page.TableDataInfo
     **/
    @Log(module = EOperationModule.STATISTIC_ANALYSIS, business = EOperationBusiness.LIANCHUANG_ABROAD_DATA_STAT, method = EOperationMethod.SELECT)
    @GetMapping("/abroad-list")
    public TableDataInfo abroadList(CuLianchuangDataStatVO lcVO) {
        Date date = DateUtils.currentDate();
        if (StringUtils.isEmpty(lcVO.getPayTime())) {
            lcVO.setPayTime(DateUtils.parseDateTimeToStr(DateUtils.YYYY_MM_DD, DateUtils.beforeDate(1, ChronoUnit.DAYS, date)));
        }
        lcVO.setStartDate(DateUtils.currentMonthFirstDateStr(DateUtils.parseStringToDate(lcVO.getPayTime())));
        lcVO.setEndDate(lcVO.getPayTime());
        //查询国家列表
        List<CuLianchuangDataStatVO> pkCountryList = lcStatService.countryList();
        startPage();
        List<AbroadDataStatVO> list = lcStatService.abroadStatList(pkCountryList, lcVO.getStartDate(), lcVO.getEndDate());
        //中国汇率
        if (SecurityUtils.getPkCountry().equals(CountryConstants.CHINA_COUNTRY)) {
            R<CurrencyDTO> currency = currencyServiceApi.getCurrency(CountryConstants.CHINA_COUNTRY);
            if (CollectionUtil.isNotEmpty(list)) {
                list.forEach(itm -> {
                    pkCountryList.forEach(itmm -> {
                        //国外金额换算成RMB
                        if (itm.getPkCountry().equals(itmm.getPkCountry())) {
                            itm.setRegisterPurchaseMo(itm.getRegisterPurchaseMo().multiply(currency.getData().getInExchangeRate()).divide(itmm.getRate(), 2, BigDecimal.ROUND_HALF_UP));
                            itm.setUpgradePurchaseMo(itm.getUpgradePurchaseMo().multiply(currency.getData().getInExchangeRate()).divide(itmm.getRate(), 2, BigDecimal.ROUND_HALF_UP));
                            itm.setFirstPurchaseMo(itm.getFirstPurchaseMo().multiply(currency.getData().getInExchangeRate()).divide(itmm.getRate(), 2, BigDecimal.ROUND_HALF_UP));
                            itm.setRepurchaseMo(itm.getRepurchaseMo().multiply(currency.getData().getInExchangeRate()).divide(itmm.getRate(), 2, BigDecimal.ROUND_HALF_UP));
                            itm.setRegisterPurchaseSumMo(itm.getRegisterPurchaseSumMo().multiply(currency.getData().getInExchangeRate()).divide(itmm.getRate(), 2, BigDecimal.ROUND_HALF_UP));
                            itm.setUpgradePurchaseSumMo(itm.getUpgradePurchaseSumMo().multiply(currency.getData().getInExchangeRate()).divide(itmm.getRate(), 2, BigDecimal.ROUND_HALF_UP));
                            itm.setFirstPurchaseSumMo(itm.getFirstPurchaseSumMo().multiply(currency.getData().getInExchangeRate()).divide(itmm.getRate(), 2, BigDecimal.ROUND_HALF_UP));
                            itm.setRepurchaseSumMo(itm.getRepurchaseSumMo().multiply(currency.getData().getInExchangeRate()).divide(itmm.getRate(), 2, BigDecimal.ROUND_HALF_UP));
                        }
                    });
                    itm.setRegisterPurchasePv(itm.getRegisterPurchasePv().multiply(currency.getData().getInExchangeRate()));
                    itm.setUpgradePurchasePv(itm.getUpgradePurchasePv().multiply(currency.getData().getInExchangeRate()));
                    itm.setRegisterPurchaseSumPv(itm.getRegisterPurchaseSumPv().multiply(currency.getData().getInExchangeRate()));
                    itm.setUpgradePurchaseSumPv(itm.getUpgradePurchaseSumPv().multiply(currency.getData().getInExchangeRate()));
                    itm.setFirstPurchasePv(itm.getFirstPurchasePv().multiply(currency.getData().getInExchangeRate()));
                    itm.setRepurchasePv(itm.getRepurchasePv().multiply(currency.getData().getInExchangeRate()));
                    itm.setFirstPurchaseSumPv(itm.getFirstPurchaseSumPv().multiply(currency.getData().getInExchangeRate()));
                    itm.setRepurchaseSumPv(itm.getRepurchaseSumPv().multiply(currency.getData().getInExchangeRate()));
                });
            }
        }
        return getDataTable(list);
    }


    /**
     * @description: 导出联创数据报表
     * @author: zhang jing
     * @date: 2023/10/19 16:08
     * @param: [response, lcVO]
     * @return: void
     **/
    @Log(module = EOperationModule.STATISTIC_ANALYSIS, business = EOperationBusiness.LIANCHUANG_DATA_STAT, method = EOperationMethod.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, CuLianchuangDataStatVO lcVO) {
        List<CuLianchuangDataStatVO> list = new ArrayList<>();
        List<CuLianchuangDataStatVO> allList = new ArrayList<>();
        if (StringUtils.isEmpty(lcVO.getPayTime())) {
            Date date = DateUtils.currentDate();
            lcVO.setPayTime(DateUtils.parseDateTimeToStr(DateUtils.YYYY_MM_DD, DateUtils.beforeDate(1, ChronoUnit.DAYS, date)));
        }
        Integer systemType = SecurityUtils.getSystemType();
        QueryWrapper<CuLianchuangDataStat> queryWrapper = new QueryWrapper<>();
        if(lcVO.getType()==null){
            lcVO.setType(ESheetType.SHEET_TYPE1.getValue());
        }
        queryWrapper.eq("TYPE", lcVO.getType());
        queryWrapper.eq("SYSTEM_TYPE", systemType);
        if (StringUtils.isNotEmpty(lcVO.getVertexCode())) {
            queryWrapper.eq("VERTEX_CODE", lcVO.getVertexCode());
        }
        queryWrapper.orderByAsc("CREATION_TIME");
        List<CuLianchuangDataStat> lcList = lcStatService.list(queryWrapper);
        List<Long> lcMemberStr = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(lcList)) {
            lcList.forEach(itm -> {
                if (StringUtils.isNotEmpty(itm.getAddRegion())) {
                    lcMemberStr.addAll(Arrays.stream(itm.getAddRegion().split(","))
                            .map(Long::parseLong)
                            .collect(Collectors.toList()));
                }
                if (StringUtils.isNotEmpty(itm.getReduceRegion())) {
                    lcMemberStr.addAll(Arrays.stream(itm.getReduceRegion().split(","))
                            .map(Long::parseLong)
                            .collect(Collectors.toList()));
                }
            });
        }
        //去重lcMemberStr
        List<Long> uniqueList = new ArrayList<>(new LinkedHashSet<>(lcMemberStr));
        lcVO.setEndDate(lcVO.getPayTime());
        lcVO.setStartDate(DateUtils.currentMonthFirstDateStr(DateUtils.parseStringToDate(lcVO.getPayTime())));
        lcVO.setPkCountry(SecurityUtils.getPkCountry());
        //多线程
        uniqueList.parallelStream().forEach(itm->{
            List<CuLianchuangDataStatVO> sonList = lcStatService.newLcStatListByOrdeType(lcVO,itm);
            allList.addAll(sonList);
        });
        //按照会员ID进行分组
        Map<Long, CuLianchuangDataStatVO> allListstMap = allList.stream()
                .collect(Collectors.toMap(CuLianchuangDataStatVO::getPkMember, Function.identity()));
        if(CollectionUtil.isNotEmpty(lcList)){
            lcList.forEach(item -> list.add(BeanUtil.copyProperties(item, CuLianchuangDataStatVO.class)));
            //根据匹配的规则添加业绩金额数据
            for(CuLianchuangDataStatVO clos:list){
                clos.setPayTime(lcVO.getPayTime());
                if (StringUtils.isNotEmpty(clos.getAddRegion())) {
                    List<Long> addRegionList = Arrays.stream(clos.getAddRegion().split(","))
                            .map(Long::parseLong)
                            .collect(Collectors.toList());
                    clos.setAddRegionList(addRegionList);
                }

                if (StringUtils.isNotEmpty(clos.getReduceRegion())) {
                    List<Long> reduceRegionList = Arrays.stream(clos.getReduceRegion().split(","))
                            .map(Long::parseLong)
                            .collect(Collectors.toList());
                    clos.setReduceRegionList(reduceRegionList);
                }
                calculateAmount(clos,allListstMap);
            }
        }
        if (SecurityUtils.getPkCountry().equals(CountryConstants.CHINA_COUNTRY)) {
            R<CurrencyDTO> currency = currencyServiceApi.getCurrency(SecurityUtils.getPkCountry());
            if (CollectionUtil.isNotEmpty(list)) {
                list.forEach(itm -> {
                    BigDecimal inExchangeRate = currency.getData().getInExchangeRate();
                    itm.setFirstPurchasePv(itm.getFirstPurchasePv().multiply(inExchangeRate));
                    itm.setFirstPurchaseSumPv(itm.getFirstPurchaseSumPv().multiply(inExchangeRate));
                });
            }
        }
        ExcelUtil<CuLianchuangDataStatVO> util = new ExcelUtil<>(CuLianchuangDataStatVO.class);
        util.exportExcel(response, list, "联创数据报表");
    }

    /**
     * @description: 导出国内联创数据报表
     * @author: zhang jing
     * @date: 2023/10/19 16:08
     * @param: [response, lcVO]
     * @return: void
     **/
    @Log(module = EOperationModule.STATISTIC_ANALYSIS, business = EOperationBusiness.LIANCHUANG_HOME_DATA_STAT, method = EOperationMethod.EXPORT)
    @PostMapping("/home-export")
    public void homeExport(HttpServletResponse response, CuLianchuangDataStatVO lcVO) {
        List<CuLianchuangDataStatVO> list = new ArrayList<>();
        if (StringUtils.isEmpty(lcVO.getPayTime())) {
            Date date = DateUtils.currentDate();
            lcVO.setPayTime(DateUtils.parseDateTimeToStr(DateUtils.YYYY_MM_DD, DateUtils.beforeDate(1, ChronoUnit.DAYS, date)));
        }

        //查询联创数据报表条件表
        QueryWrapper<CuLianchuangDataStat> queryWrapper = new QueryWrapper();
        if(lcVO.getType()==null){
            lcVO.setType(ESheetType.SHEET_TYPE1.getValue());
        }
        queryWrapper.eq("TYPE", lcVO.getType());
        queryWrapper.orderByAsc("PK_ID");
        List<CuLianchuangDataStat> lcList = lcStatService.list(queryWrapper);
        if (CollectionUtil.isNotEmpty(lcList)) {
            List<CuLianchuangDataStatVO> finalList = list;
            lcList.forEach(itm -> {
                itm.setEndDate(lcVO.getPayTime());
                itm.setStartDate(DateUtils.currentMonthFirstDateStr(DateUtils.parseStringToDate(lcVO.getPayTime())));
                if (StringUtils.isNotEmpty(itm.getAddRegion())) {
                    List<Integer> addRegionList = Arrays.stream(itm.getAddRegion().split(","))
                            .map(Integer::parseInt)
                            .collect(Collectors.toList());
                    itm.setAddRegionList(addRegionList);
                }
                List<CuLianchuangDataStatVO> sonList = lcStatService.lcStatList(Arrays.asList(itm));
                finalList.addAll(sonList);
            });

        }
        if (SecurityUtils.getPkCountry().equals(CountryConstants.CHINA_COUNTRY)) {
            R<CurrencyDTO> currency = currencyServiceApi.getCurrency(SecurityUtils.getPkCountry());
            if (CollectionUtil.isNotEmpty(list)) {
                list.forEach(itm -> {
                    itm.setFirstPurchasePv(itm.getFirstPurchasePv().multiply(currency.getData().getInExchangeRate()));
                    itm.setFirstPurchaseSumPv(itm.getFirstPurchaseSumPv().multiply(currency.getData().getInExchangeRate()));
                });
            }
        }
        List<HomeDataStatVO> list1 = new ArrayList<>();
        list.forEach(item -> list1.add(BeanUtil.copyProperties(item, HomeDataStatVO.class)));
        ExcelUtil<HomeDataStatVO> util = new ExcelUtil<>(HomeDataStatVO.class);
        util.exportExcel(response, list1, "国内数据报表");
    }

    /**
     * @description: 导出国外联创数据报表
     * @author: zhang jing
     * @date: 2023/12/4 10:13
     * @param: [response, lcVO]
     * @return: void
     **/
    @Log(module = EOperationModule.STATISTIC_ANALYSIS, business = EOperationBusiness.LIANCHUANG_ABROAD_DATA_STAT, method = EOperationMethod.EXPORT)
    @PostMapping("/abroad-export")
    public void abroadExport(HttpServletResponse response, CuLianchuangDataStatVO lcVO) {
        if (StringUtils.isEmpty(lcVO.getPayTime())) {
            Date date = DateUtils.currentDate();
            lcVO.setPayTime(DateUtils.parseDateTimeToStr(DateUtils.YYYY_MM_DD, date));
        }

        lcVO.setStartDate(DateUtils.currentMonthFirstDateStr(DateUtils.parseStringToDate(lcVO.getPayTime())));
        lcVO.setEndDate(lcVO.getPayTime());
        //查询国家列表
        List<CuLianchuangDataStatVO> pkCountryList = lcStatService.countryList();
        List<AbroadDataStatVO> list = lcStatService.abroadStatList(pkCountryList, lcVO.getStartDate(), lcVO.getEndDate());
        if (SecurityUtils.getPkCountry().equals(CountryConstants.CHINA_COUNTRY)) {
            //中国汇率
            R<CurrencyDTO> currency = currencyServiceApi.getCurrency(CountryConstants.CHINA_COUNTRY);
            if (CollectionUtil.isNotEmpty(list)) {
                list.forEach(itm -> {
                    pkCountryList.forEach(itmm -> {
                        //国外金额换算成RMB
                        if (itm.getPkCountry().equals(itmm.getPkCountry())) {
                            itm.setRegisterPurchaseMo(itm.getRegisterPurchaseMo().multiply(currency.getData().getInExchangeRate()).divide(itmm.getRate(), 2, BigDecimal.ROUND_HALF_UP));
                            itm.setUpgradePurchaseMo(itm.getUpgradePurchaseMo().multiply(currency.getData().getInExchangeRate()).divide(itmm.getRate(), 2, BigDecimal.ROUND_HALF_UP));
                            itm.setFirstPurchaseMo(itm.getFirstPurchaseMo().multiply(currency.getData().getInExchangeRate()).divide(itmm.getRate(), 2, BigDecimal.ROUND_HALF_UP));
                            itm.setRepurchaseMo(itm.getRepurchaseMo().multiply(currency.getData().getInExchangeRate()).divide(itmm.getRate(), 2, BigDecimal.ROUND_HALF_UP));
                            itm.setRegisterPurchaseSumMo(itm.getRegisterPurchaseSumMo().multiply(currency.getData().getInExchangeRate()).divide(itmm.getRate(), 2, BigDecimal.ROUND_HALF_UP));
                            itm.setUpgradePurchaseSumMo(itm.getUpgradePurchaseSumMo().multiply(currency.getData().getInExchangeRate()).divide(itmm.getRate(), 2, BigDecimal.ROUND_HALF_UP));
                            itm.setFirstPurchaseSumMo(itm.getFirstPurchaseSumMo().multiply(currency.getData().getInExchangeRate()).divide(itmm.getRate(), 2, BigDecimal.ROUND_HALF_UP));
                            itm.setRepurchaseSumMo(itm.getRepurchaseSumMo().multiply(currency.getData().getInExchangeRate()).divide(itmm.getRate(), 2, BigDecimal.ROUND_HALF_UP));
                        }
                    });
                    itm.setRegisterPurchasePv(itm.getRegisterPurchasePv().multiply(currency.getData().getInExchangeRate()));
                    itm.setUpgradePurchasePv(itm.getUpgradePurchasePv().multiply(currency.getData().getInExchangeRate()));
                    itm.setRegisterPurchaseSumPv(itm.getRegisterPurchaseSumPv().multiply(currency.getData().getInExchangeRate()));
                    itm.setUpgradePurchaseSumPv(itm.getUpgradePurchaseSumPv().multiply(currency.getData().getInExchangeRate()));
                    itm.setFirstPurchasePv(itm.getFirstPurchasePv().multiply(currency.getData().getInExchangeRate()));
                    itm.setRepurchasePv(itm.getRepurchasePv().multiply(currency.getData().getInExchangeRate()));
                    itm.setFirstPurchaseSumPv(itm.getFirstPurchaseSumPv().multiply(currency.getData().getInExchangeRate()));
                    itm.setRepurchaseSumPv(itm.getRepurchaseSumPv().multiply(currency.getData().getInExchangeRate()));
                });
            }
        }
        ExcelUtil<AbroadDataStatVO> util = new ExcelUtil<>(AbroadDataStatVO.class);
        util.exportExcel(response, list, "国外数据报表");
    }

    /**
     * @description: 新增联创查询条件
     * @author: zhang jing
     * @date: 2023/10/19 16:17
     * @param: [lcVO]
     * @return: com.hzs.common.core.web.domain.AjaxResult
     **/
    @Log(module = EOperationModule.LEVEL_CONFIG, business = EOperationBusiness.LIANCHUANG_DATA_STAT, method = EOperationMethod.INSERT)
    @PostMapping("/save")
    public AjaxResult save(@RequestBody CuLianchuangDataStatVO lcVO) {
        if(StringUtils.isEmpty(lcVO.getVertexCode())){
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.LIANCHUANG_STAT_CODE));
        }
        if(StringUtils.isEmpty(lcVO.getVertexName())){
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.LIANCHUANG_STAT_NAME));
        }
        if(lcVO.getType()==null){
            lcVO.setType(ESheetType.SHEET_TYPE1.getValue());
        }
        Integer pkCountry = SecurityUtils.getPkCountry();
        Integer systemType = SecurityUtils.getSystemType();
        Long userId = SecurityUtils.getUserId();
        Date date = DateUtils.currentDate();
        String addRegion = "";
        String reduceRegion = "";
        if (StringUtils.isNotEmpty(lcVO.getAddRegion())) {
            String[] addCodeArray = lcVO.getAddRegion().split(",");
            if (addCodeArray.length > 0) {
                for (int i = 0; i < addCodeArray.length; i++) {
                    R<CuMember> member = iMemberServiceApi.getMember(addCodeArray[i]);
                    addRegion = addRegion + member.getData().getPkId() + ",";
                }
            }
            lcVO.setAddRegion(addRegion);
        }
        if (StringUtils.isNotEmpty(lcVO.getReduceRegion())) {
            String[] reduceCodeArray = lcVO.getReduceRegion().split(",");
            if (reduceCodeArray.length > 0) {
                for (int i = 0; i < reduceCodeArray.length; i++) {
                    R<CuMember> member = iMemberServiceApi.getMember(reduceCodeArray[i]);
                    reduceRegion = reduceRegion + member.getData().getPkId() + ",";
                }
            }
            lcVO.setReduceRegion(reduceRegion);
        }
        lcVO.setPkCountry(pkCountry);
        lcVO.setPkCreator(userId);
        lcVO.setCreationTime(date);
        lcVO.setSystemType(systemType);
        CuLianchuangDataStat cld = BeanUtil.copyProperties(lcVO, CuLianchuangDataStat.class);
        return AjaxResult.success(lcStatService.save(cld));
    }

    /**
     * @description: 国内数据报表查询
     * @author: zhang jing
     * @date: 2023/12/4 9:57
     * @param: [lcVO]
     * @return: com.hzs.common.core.web.domain.AjaxResult
     **/
    @Log(module = EOperationModule.LEVEL_CONFIG, business = EOperationBusiness.LIANCHUANG_HOME_DATA_STAT, method = EOperationMethod.INSERT)
    @PostMapping("/home-save")
    public AjaxResult homeSave(@RequestBody CuLianchuangDataStatVO lcVO) {
        Integer pkCountry = SecurityUtils.getPkCountry();
        Long userId = SecurityUtils.getUserId();
        Date date = DateUtils.currentDate();
        if(lcVO.getType()==null){
            lcVO.setType(ESheetType.SHEET_TYPE1.getValue());
        }
        String addRegion = "";
        if (StringUtils.isEmpty(lcVO.getVertexCode())) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.LIANCHUANG_STAT_CODE));
        }
        if (StringUtils.isEmpty(lcVO.getVertexName())) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.LIANCHUANG_STAT_NAME));
        }
        if (StringUtils.isEmpty(lcVO.getAddRegion())) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.LIANCHUANG_STAT_ADD_REGION));
        }
        if (StringUtils.isNotEmpty(lcVO.getAddRegion())) {
            String[] addCodeArray = lcVO.getAddRegion().split(",");
            if (addCodeArray.length > 0) {
                for (int i = 0; i < addCodeArray.length; i++) {
                    R<CuMember> member = iMemberServiceApi.getMember(addCodeArray[i]);
                    addRegion = addRegion + member.getData().getPkId() + ",";
                }
            }
            lcVO.setAddRegion(addRegion);
        }
        lcVO.setPkCountry(pkCountry);
        lcVO.setPkCreator(userId);
        lcVO.setCreationTime(date);
        CuLianchuangDataStat cld = BeanUtil.copyProperties(lcVO, CuLianchuangDataStat.class);
        return AjaxResult.success(lcStatService.save(cld));
    }


    /**
     * @description: 修改联创数据报表查询条件
     * @author: zhang jing
     * @date: 2023/10/19 17:03
     * @param: [lcVO]
     * @return: com.hzs.common.core.web.domain.AjaxResult
     **/
    @Log(module = EOperationModule.STATISTIC_ANALYSIS, business = EOperationBusiness.LIANCHUANG_DATA_STAT, method = EOperationMethod.UPDATE)
    @PostMapping("/update")
    public AjaxResult update(@RequestBody CuLianchuangDataStatVO lcVO) {
        Integer pkCountry = SecurityUtils.getPkCountry();
        Integer systemType = SecurityUtils.getSystemType();
        lcVO.setSystemType(systemType);
        Long userId = SecurityUtils.getUserId();
        Date date = DateUtils.currentDate();
        if(lcVO.getType()==null){
            lcVO.setType(ESheetType.SHEET_TYPE1.getValue());
        }
        String addRegion = "";
        String reduceRegion = "";
        if (StringUtils.isEmpty(lcVO.getVertexCode())) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.LIANCHUANG_STAT_CODE));
        }
        if (StringUtils.isEmpty(lcVO.getVertexName())) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.LIANCHUANG_STAT_NAME));
        }
        if (StringUtils.isEmpty(lcVO.getAddRegion())) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.LIANCHUANG_STAT_ADD_REGION));
        }
        if (StringUtils.isNotEmpty(lcVO.getAddRegion())) {
            String[] addCodeArray = lcVO.getAddRegion().split(",");
            if (addCodeArray.length > 0) {
                for (int i = 0; i < addCodeArray.length; i++) {
                    R<CuMember> member = iMemberServiceApi.getMember(addCodeArray[i]);
                    addRegion = addRegion + member.getData().getPkId() + ",";
                }
            }
            lcVO.setAddRegion(addRegion);
        } else {
            lcVO.setAddRegion(addRegion);
        }
        if (StringUtils.isNotEmpty(lcVO.getReduceRegion())) {
            String[] reduceCodeArray = lcVO.getReduceRegion().split(",");
            if (reduceCodeArray.length > 0) {
                for (int i = 0; i < reduceCodeArray.length; i++) {
                    R<CuMember> member = iMemberServiceApi.getMember(reduceCodeArray[i]);
                    reduceRegion = reduceRegion + member.getData().getPkId() + ",";
                }
            }
            lcVO.setReduceRegion(reduceRegion);
        } else {
            lcVO.setReduceRegion(reduceRegion);
        }
        lcVO.setPkCountry(pkCountry);
        lcVO.setPkModified(userId);
        lcVO.setModifiedTime(date);
        CuLianchuangDataStat cld = BeanUtil.copyProperties(lcVO, CuLianchuangDataStat.class);
        return AjaxResult.success(lcStatService.updateById(cld));
    }

    /**
     * @description:修改国内联创数据报表查询条件
     * @author: zhang jing
     * @date: 2023/12/4 9:59
     * @param: [lcVO]
     * @return: com.hzs.common.core.web.domain.AjaxResult
     **/
    @Log(module = EOperationModule.STATISTIC_ANALYSIS, business = EOperationBusiness.LIANCHUANG_HOME_DATA_STAT, method = EOperationMethod.UPDATE)
    @PostMapping("/home-update")
    public AjaxResult homeUpdate(@RequestBody CuLianchuangDataStatVO lcVO) {
        Integer pkCountry = SecurityUtils.getPkCountry();
        Integer systemType = SecurityUtils.getSystemType();
        lcVO.setSystemType(systemType);
        Long userId = SecurityUtils.getUserId();
        Date date = DateUtils.currentDate();
        if(lcVO.getType()==null){
            lcVO.setType(ESheetType.SHEET_TYPE1.getValue());
        }
        String addRegion = "";
        if (StringUtils.isNotEmpty(lcVO.getAddRegion())) {
            String[] addCodeArray = lcVO.getAddRegion().split(",");
            if (addCodeArray.length > 0) {
                for (int i = 0; i < addCodeArray.length; i++) {
                    R<CuMember> member = iMemberServiceApi.getMember(addCodeArray[i]);
                    addRegion = addRegion + member.getData().getPkId() + ",";
                }
            }
            lcVO.setAddRegion(addRegion);
        } else {
            lcVO.setAddRegion(addRegion);
        }
        lcVO.setPkCountry(pkCountry);
        lcVO.setPkModified(userId);
        lcVO.setModifiedTime(date);
        CuLianchuangDataStat cld = BeanUtil.copyProperties(lcVO, CuLianchuangDataStat.class);
        return AjaxResult.success(lcStatService.updateById(cld));
    }


    /**
     * @description: 查询单条联创数据报表查询条件
     * @author: zhang jing
     * @date: 2023/10/19 17:18
     * @param: [pkId]
     * @return: com.hzs.common.core.web.domain.AjaxResult
     **/
    @Log(module = EOperationModule.STATISTIC_ANALYSIS, business = EOperationBusiness.LIANCHUANG_DATA_STAT, method = EOperationMethod.SELECT)
    @GetMapping("/getOne/{pkId}")
    public AjaxResult getOne(@PathVariable Long pkId) {
        CuLianchuangDataStat cld = lcStatService.getById(pkId);
        CuLianchuangDataStatVO lcVO = BeanUtil.copyProperties(cld, CuLianchuangDataStatVO.class);
        String addRegion = "";
        String reduceRegion = "";
        if (StringUtils.isNotEmpty(lcVO.getAddRegion())) {
            String[] addCodeArray = lcVO.getAddRegion().split(",");
            if (addCodeArray.length > 0) {
                for (int i = 0; i < addCodeArray.length; i++) {
                    int pkMember = Integer.parseInt(addCodeArray[i]);
                    R<CuMember> member = iMemberServiceApi.getMember((long) pkMember);
                    addRegion = addRegion + member.getData().getMemberCode() + ",";
                }
            }
            lcVO.setAddRegion(addRegion);
        }
        if (StringUtils.isNotEmpty(lcVO.getReduceRegion())) {
            String[] reduceCodeArray = lcVO.getReduceRegion().split(",");
            if (reduceCodeArray.length > 0) {
                for (int i = 0; i < reduceCodeArray.length; i++) {
                    int pkMember = Integer.parseInt(reduceCodeArray[i]);
                    R<CuMember> member = iMemberServiceApi.getMember((long) pkMember);
                    reduceRegion = reduceRegion + member.getData().getMemberCode() + ",";
                }
            }
            lcVO.setReduceRegion(reduceRegion);
        }
        return AjaxResult.success(lcVO);
    }


    /**
     * @description: 删除联创数据报表查询条件
     * @author: zhang jing
     * @date: 2023/10/19 17:02
     * @param: [pkId]
     * @return: com.hzs.common.core.web.domain.AjaxResult
     **/
    @Log(module = EOperationModule.STATISTIC_ANALYSIS, business = EOperationBusiness.LIANCHUANG_DATA_STAT, method = EOperationMethod.DELETE)
    @PostMapping("/delete-lcStat")
    public AjaxResult delete(@RequestBody CuLianchuangDataStatVO lcVO) {
        if (CollectionUtil.isNotEmpty(lcVO.getPkIdList())) {
            lcStatService.deleteLcStat(lcVO.getPkIdList());
        }
        return AjaxResult.success();
    }

}
