package com.upyuns.platform.rs.datacenter.biz;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.github.wxiaoqi.security.common.biz.BaseBiz;
import com.github.wxiaoqi.security.common.util.Query;
import com.github.wxiaoqi.security.common.vo.PageDataVO;
import com.github.wxiaoqi.security.common.vo.PageParam;
import com.upyuns.platform.rs.datacenter.entity.*;
import com.upyuns.platform.rs.datacenter.mapper.RscpImageCoverMapper;
import com.upyuns.platform.rs.datacenter.pojo.BgImageCoverQueryDTO;
import com.upyuns.platform.rs.datacenter.pojo.imagedata.InsertCoverDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

import static com.github.wxiaoqi.security.common.constant.CommonConstants.SYS_FALSE;
import static com.github.wxiaoqi.security.common.constant.CommonConstants.SYS_TRUE;
import static com.upyuns.platform.rs.datacenter.entity.RscpImageCover.TYPE_MONTH;
import static com.upyuns.platform.rs.datacenter.entity.RscpImageCover.TYPE_YEAR;

@Service
public class RscpImageCoverBiz extends BaseBiz<RscpImageCoverMapper, RscpImageCover> {

    @Autowired
    RscpImagePriceBiz rscpImagePriceBiz;

    @Autowired
    RscpImageDataTotalBiz rscpImageDataTotalBiz;

    @Autowired
    RscpImageStatisticsBiz rscpImageStatisticsBiz;

    @Autowired
    RscpAreaImageTotalBiz rscpAreaImageTotalBiz;

    @Autowired
    RscpAreaInfoBiz rscpAreaInfoBiz;

    public List<RscpImageCover> bgQueryDataList(BgImageCoverQueryDTO dto) {
        return mapper.bgQueryDataList(dto);
    }

    public List<RscpImageCover> queryDataList(BgImageCoverQueryDTO dto) {
        return mapper.queryDataList(dto);
    }

    public void coverTask() {
        Date now = new Date();
        Long count= rscpImageDataTotalBiz.selectCount(new RscpImageDataTotal(){{
            setCoverStatistics(0);
        }});

        long cirle = 1;

        if(count > 500L) {
            cirle = (count/500L) + 1;

            if(count%500L > 0) {
                cirle += 1;
            }
        }

        for (int i = 0; i < cirle; i++) {
            PageDataVO<RscpImageDataTotal> vos = PageDataVO.pageInfo(new Query(new PageParam(){{
                setPage(1);
                setLimit(500);
            }}), () -> rscpImageDataTotalBiz.selectByWeekend(w -> {
                w.andEqualTo(RscpImageDataTotal::getCoverStatistics, 0);
                w.andIsNotNull(RscpImageDataTotal::getImageProvince);
                w.andNotEqualTo(RscpImageDataTotal::getImageProvince, "");
                return w;
            }, " image_province asc, image_take_time asc"));

            if(CollUtil.isNotEmpty(vos.getData())) {
                List<Long> ids = vos.getData().parallelStream().map(RscpImageDataTotal::getId).collect(Collectors.toList());
                Map<Long, RscpImageDataTotal> map = vos.getData().parallelStream().collect(Collectors.toMap(RscpImageDataTotal::getId, Function.identity()));

                //根据id查询区域信息
                List<RscpAreaImageTotal> areas = rscpAreaImageTotalBiz.selectByWeekend(w -> {
                    w.andIn(RscpAreaImageTotal::getDataId, ids);
                    return w;
                });

                Map<String, List<RscpAreaImageTotal>> areaMap = areas.parallelStream().collect(Collectors.groupingBy(RscpAreaImageTotal::getAreaNo));

                areaMap.forEach((k,v) -> {
                    //根据月份 处理覆盖率
                    Integer areaCode = Integer.valueOf(k);
                    RscpAreaInfo rscpAreaInfo = rscpAreaInfoBiz.queryAreaInfoByAreaId(k);
                    //按月份
                    Map<String, List<RscpAreaImageTotal>> monthMap = v.parallelStream().collect(Collectors.groupingBy(a->{
                        DateTime dateTime = DateUtil.parseDate(a.getBeginTime());
                        return DateUtil.format(dateTime, "yyyy-MM");
                    }));

                    //按年份
                    Map<String, List<RscpAreaImageTotal>> yearMap = v.parallelStream().collect(Collectors.groupingBy(a->{
                        DateTime dateTime = DateUtil.parseDate(a.getBeginTime());
                        return DateUtil.format(dateTime, "yyyy");
                    }));

                    //处理月份融合
                    monthMap.forEach((mk,mv) -> {
                        String[] mks = mk.split("-");
                        String yearMk = mks[0];
                        String monthMk = mks[1];

                        //查询旧数据
                        List<RscpImageCover> list = selectList(new RscpImageCover(){{
                            setDateMonth(monthMk);
                            setDateYear(yearMk);
                            setIsDel(SYS_FALSE);
                            setAreaCode(areaCode);
                            setType(TYPE_MONTH);
                        }});

                        List<Long> dataIds = mv.parallelStream().map(RscpAreaImageTotal::getDataId).collect(Collectors.toList());

                        InsertCoverDTO insertCoverDTO = new InsertCoverDTO();
                        if(CollUtil.isNotEmpty(list)) {
                            Integer oldId = list.get(0).getId();
                            updateSelectiveById(new RscpImageCover(){{
                                setId(oldId);
                                setIsDel(SYS_TRUE);
                            }});
                            insertCoverDTO.setOldId(oldId);
                            insertCoverDTO.setImageNum(dataIds.size() + list.get(0).getImageNum());
                        }else {
                            insertCoverDTO.setImageNum(dataIds.size());
                        }

                        insertCoverDTO.setName(mk+""+rscpAreaInfo.getName());
                        insertCoverDTO.setDataIds(dataIds);
                        insertCoverDTO.setAreaCode(areaCode);
                        insertCoverDTO.setAreaName(rscpAreaInfo.getName());
                        insertCoverDTO.setCrtTime(now.getTime());
                        insertCoverDTO.setUpdTime(now.getTime());
                        insertCoverDTO.setDateMonth(monthMk);
                        insertCoverDTO.setDateYear(yearMk);
                        insertCoverDTO.setType(TYPE_MONTH);
                        mapper.coverInsert(insertCoverDTO);
                    });

                    //处理年份融合
                    yearMap.forEach((mk,mv) -> {
                        String yearMk = mk;

                        //查询旧数据
                        List<RscpImageCover> list = selectList(new RscpImageCover(){{
                            setDateYear(yearMk);
                            setIsDel(SYS_FALSE);
                            setAreaCode(areaCode);
                            setType(TYPE_YEAR);
                        }});

                        List<Long> dataIds = mv.parallelStream().map(RscpAreaImageTotal::getDataId).collect(Collectors.toList());

                        InsertCoverDTO insertCoverDTO = new InsertCoverDTO();
                        if(CollUtil.isNotEmpty(list)) {
                            Integer oldId = list.get(0).getId();
                            updateSelectiveById(new RscpImageCover(){{
                                setId(oldId);
                                setIsDel(SYS_TRUE);
                            }});
                            insertCoverDTO.setOldId(oldId);
                            insertCoverDTO.setImageNum(dataIds.size() + list.get(0).getImageNum());
                        }else {
                            insertCoverDTO.setImageNum(dataIds.size());
                        }

                        insertCoverDTO.setName(mk+""+rscpAreaInfo.getName());
                        insertCoverDTO.setDataIds(dataIds);
                        insertCoverDTO.setAreaCode(areaCode);
                        insertCoverDTO.setAreaName(rscpAreaInfo.getName());
                        insertCoverDTO.setCrtTime(now.getTime());
                        insertCoverDTO.setUpdTime(now.getTime());
                        insertCoverDTO.setDateYear(yearMk);
                        insertCoverDTO.setType(TYPE_YEAR);
                        mapper.coverInsert(insertCoverDTO);
                    });

                });

                rscpImageDataTotalBiz.updateByWeekendSelective(new RscpImageDataTotal(){{
                    setCoverStatistics(SYS_TRUE);
                }}, w -> {
                    w.andIn(RscpImageDataTotal::getId, ids);
                    return w;
                });
            }
        }

    }
}
