package shop.alien.store.service.impl;

import com.alibaba.fastjson2.util.DateUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import shop.alien.entity.store.LifeGroupBuyCount;
import shop.alien.entity.store.LifeGroupBuyMain;
import shop.alien.entity.store.LifeUserOrder;
import shop.alien.entity.store.vo.LifeGroupBuyCountDateVo;
import shop.alien.entity.store.vo.LifeGroupBuyCountVo;
import shop.alien.mapper.LifeGroupBuyCountMapper;
import shop.alien.mapper.LifeGroupBuyMainMapper;
import shop.alien.mapper.LifeUserOrderMapper;
import shop.alien.store.service.LifeGroupBuyCountService;

import java.math.BigDecimal;
import java.math.MathContext;
import java.math.RoundingMode;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 团购统计
 */
@Service
@RequiredArgsConstructor
public class LifeGroupBuyCountServiceImpl extends ServiceImpl<LifeGroupBuyCountMapper, LifeGroupBuyCount> implements LifeGroupBuyCountService {

    @Autowired
    private LifeGroupBuyCountMapper lifeGroupBuyCountMapper;

    @Autowired
    private LifeUserOrderMapper lifeUserOrderMapper;

    @Autowired
    private LifeGroupBuyMainMapper lifeGroupBuyMainMapper;

    @Override
    public void insertGroupBuyCount(Integer storeId, Integer groupId, Integer userId, String countType) {
        LambdaQueryWrapper<LifeGroupBuyCount> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(LifeGroupBuyCount::getCountType, countType)
                .eq(LifeGroupBuyCount::getStoreId, storeId)
                .eq(LifeGroupBuyCount::getGroupId, groupId)
                .eq(LifeGroupBuyCount::getUserId, userId)
                .eq(LifeGroupBuyCount::getCountDate, DateUtils.format(new Date(), "yyyy-MM-dd"));
        Integer count = lifeGroupBuyCountMapper.selectCount(queryWrapper);
        if (count > 0) {
            List<LifeGroupBuyCount> lifeGroupBuyCounts = lifeGroupBuyCountMapper.selectList(queryWrapper);
            LambdaUpdateWrapper<LifeGroupBuyCount> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(LifeGroupBuyCount::getCountType, countType)
                    .eq(LifeGroupBuyCount::getStoreId, storeId)
                    .eq(LifeGroupBuyCount::getGroupId, groupId)
                    .eq(LifeGroupBuyCount::getUserId, userId)
                    .eq(LifeGroupBuyCount::getCountDate, DateUtils.format(new Date(), "yyyy-MM-dd"))
                    .set(LifeGroupBuyCount::getCountNum, lifeGroupBuyCounts.get(0).getCountNum() + 1);
            lifeGroupBuyCountMapper.update(null, updateWrapper);
        } else {
            LifeGroupBuyCount lifeGroupBuyCount = new LifeGroupBuyCount();
            lifeGroupBuyCount.setCountDate(new Date());
            lifeGroupBuyCount.setCountType(countType);
            lifeGroupBuyCount.setStoreId(storeId);
            lifeGroupBuyCount.setGroupId(groupId);
            lifeGroupBuyCount.setUserId(userId);
            lifeGroupBuyCount.setCountNum(1);
            lifeGroupBuyCountMapper.insert(lifeGroupBuyCount);
        }
    }

    @Override
    public Map<String, LifeGroupBuyCountVo> getJysj(String storeId) {
        String today = DateUtils.format(new Date(), "yyyy-MM-dd");
        String yesterday = DateUtils.format(shop.alien.util.common.DateUtils.calcDays(new Date(), -1), "yyyy-MM-dd");

        List<LifeGroupBuyCountVo> todayList = lifeGroupBuyCountMapper.selectJysjListByStoreId(storeId, today);
        List<LifeGroupBuyCountVo> yesterdayList = lifeGroupBuyCountMapper.selectJysjListByStoreId(storeId, yesterday);
        if (ObjectUtils.isNotEmpty(todayList)) {
            for (LifeGroupBuyCountVo lifeGroupBuyCountVo : todayList) {
                //昨天数据
                if (yesterdayList.stream().map(LifeGroupBuyCount::getCountType).collect(Collectors.toList()).contains(lifeGroupBuyCountVo.getCountType())) {
                    yesterdayList.stream().filter(item -> item.getCountType().equals(lifeGroupBuyCountVo.getCountType())).findFirst().ifPresent(item -> lifeGroupBuyCountVo.setYesCountNum(item.getCountNum().toString()));
                }
            }
        }

        List<LifeGroupBuyCountVo> collect = todayList.stream().filter(item -> "0".equals(item.getCountType())).collect(Collectors.toList());
        if (ObjectUtils.isNotEmpty(collect)) {
            LifeGroupBuyCountVo lifeGroupBuyCountVo = collect.get(0);

            LifeGroupBuyCountVo countVo = new LifeGroupBuyCountVo();
            //访客
            countVo.setCountType("1");
            countVo.setCountNum(Integer.valueOf(lifeGroupBuyCountVo.getPersonNum()));
            //昨天的访客人数
            yesterdayList.stream().filter(item -> "0".equals(item.getCountType())).findFirst().ifPresent(item -> countVo.setYesCountNum(item.getPersonNum()));
            todayList.add(countVo);
        }

        LambdaQueryWrapper<LifeUserOrder> orderLambdaQueryWrapper = new LambdaQueryWrapper<>();
        orderLambdaQueryWrapper.eq(LifeUserOrder::getStoreId, storeId)
                .eq(LifeUserOrder::getStatus, "7")
                .like(LifeUserOrder::getFinishTime, today);
        Integer todayOrderNum = lifeUserOrderMapper.selectCount(orderLambdaQueryWrapper);

        LambdaQueryWrapper<LifeUserOrder> orderLambdaQueryWrapper1 = new LambdaQueryWrapper<>();
        orderLambdaQueryWrapper1.eq(LifeUserOrder::getStoreId, storeId)
                .eq(LifeUserOrder::getStatus, "7")
                .like(LifeUserOrder::getFinishTime, yesterday);
        Integer yesterdayOrderNum = lifeUserOrderMapper.selectCount(orderLambdaQueryWrapper1);
        LifeGroupBuyCountVo countVo = new LifeGroupBuyCountVo();
        countVo.setCountType("4");
        countVo.setCountNum(todayOrderNum);
        countVo.setYesCountNum(yesterdayOrderNum.toString());
        todayList.add(countVo);
        bfb(todayList);

        Map<String, LifeGroupBuyCountVo> map = new HashMap<>();
        LifeGroupBuyCountVo tcfwl = new LifeGroupBuyCountVo();
        tcfwl.setCountType("0");
        LifeGroupBuyCountVo tcfks = new LifeGroupBuyCountVo();
        tcfks.setCountType("1");
        LifeGroupBuyCountVo sjtcs = new LifeGroupBuyCountVo();
        sjtcs.setCountType("2");
        LifeGroupBuyCountVo xjtcs = new LifeGroupBuyCountVo();
        xjtcs.setCountType("3");
        LifeGroupBuyCountVo sfrs = new LifeGroupBuyCountVo();
        sfrs.setCountType("4");
        map.put("tcfwl", tcfwl);
        map.put("tcfks", tcfks);
        map.put("sjtcs", sjtcs);
        map.put("xjtcs", xjtcs);
        map.put("sfrs", sfrs);
        todayList.stream().filter(item -> "0".equals(item.getCountType())).findFirst().ifPresent(item -> map.put("tcfwl", item));
        todayList.stream().filter(item -> "1".equals(item.getCountType())).findFirst().ifPresent(item -> map.put("tcfks", item));
        todayList.stream().filter(item -> "2".equals(item.getCountType())).findFirst().ifPresent(item -> map.put("sjtcs", item));
        todayList.stream().filter(item -> "3".equals(item.getCountType())).findFirst().ifPresent(item -> map.put("xjtcs", item));
        todayList.stream().filter(item -> "4".equals(item.getCountType())).findFirst().ifPresent(item -> map.put("sfrs", item));
        return map;
    }

    @Override
    public List<LifeGroupBuyCountDateVo> getSphxzb(String storeId) {
        List<LifeGroupBuyCountDateVo> lifeGroupBuyCountDateVos = lifeGroupBuyCountMapper.selectSphxzbListByStoreId(storeId, DateUtils.format(shop.alien.util.common.DateUtils.calcDays(new Date(), -6), "yyyy-MM-dd"), DateUtils.format(new Date(), "yyyy-MM-dd"));
        lifeGroupBuyCountDateVos.forEach(i -> i.setCountDate(DateUtils.format(DateUtils.parseDate(i.getCountDate()), "MM-dd")));
        return lifeGroupBuyCountDateVos;
    }

    @Override
    public List<LifeGroupBuyCountDateVo> getDpzbpm(String storeId) {
        List<LifeGroupBuyCountDateVo> lifeGroupBuyCountDateVos = lifeGroupBuyCountMapper.selectDpzbpmListByStoreId(storeId);
        for (LifeGroupBuyCountDateVo lifeGroupBuyCountDateVo : lifeGroupBuyCountDateVos) {
            lifeGroupBuyCountDateVo.setRjfws(StringUtils.isNotEmpty(lifeGroupBuyCountDateVo.getSpfks()) ? (new BigDecimal(lifeGroupBuyCountDateVo.getSpfwl()).divide(new BigDecimal(lifeGroupBuyCountDateVo.getSpfks()), 0, RoundingMode.HALF_UP)).toString() : "0");
            lifeGroupBuyCountDateVo.setScl(StringUtils.isNotEmpty(lifeGroupBuyCountDateVo.getSpfks()) ? new BigDecimal(lifeGroupBuyCountDateVo.getSpscl()).divide(new BigDecimal(lifeGroupBuyCountDateVo.getSpfks()), 4, RoundingMode.HALF_UP).multiply(new BigDecimal(100)).setScale(2, RoundingMode.HALF_UP) + "%" : "0.0%");
        }
        return lifeGroupBuyCountDateVos;
    }

    @Override
    public void test() {
        List<LifeGroupBuyCount> list = new ArrayList<>();
        LambdaQueryWrapper<LifeGroupBuyMain> sjQuery = new LambdaQueryWrapper<>();
        sjQuery.eq(LifeGroupBuyMain::getStatus, "5").eq(LifeGroupBuyMain::getDeleteFlag, 0).eq(LifeGroupBuyMain::getGroupType, 1);
        Map<String, List<LifeGroupBuyMain>> sjCollect = lifeGroupBuyMainMapper.selectList(sjQuery).stream().collect(Collectors.groupingBy(LifeGroupBuyMain::getStoreId));
        for (String s : sjCollect.keySet()) {
            LifeGroupBuyCount sj = new LifeGroupBuyCount();
            sj.setStoreId(Integer.valueOf(sjCollect.get(s).get(0).getStoreId()));
            sj.setCountType("2");
            sj.setCountNum(sjCollect.get(s).size());
            sj.setCountDate(new Date());
            list.add(sj);
        }

        LambdaQueryWrapper<LifeGroupBuyMain> xjQuery = new LambdaQueryWrapper<>();
        xjQuery.in(LifeGroupBuyMain::getStatus, "7", "8").eq(LifeGroupBuyMain::getDeleteFlag, 0).eq(LifeGroupBuyMain::getGroupType, 1);
        Map<String, List<LifeGroupBuyMain>> xjCollect = lifeGroupBuyMainMapper.selectList(xjQuery).stream().collect(Collectors.groupingBy(LifeGroupBuyMain::getStoreId));
        for (String s : xjCollect.keySet()) {
            LifeGroupBuyCount xj = new LifeGroupBuyCount();
            xj.setStoreId(Integer.valueOf(xjCollect.get(s).get(0).getStoreId()));
            xj.setCountType("3");
            xj.setCountNum(xjCollect.get(s).size());
            xj.setCountDate(new Date());
            list.add(xj);
        }
        if (ObjectUtils.isNotEmpty(list)) {
            lifeGroupBuyCountMapper.insertList(list);
        }
    }

    private void bfb(List<LifeGroupBuyCountVo> list) {
        for (LifeGroupBuyCountVo item : list) {
            item.setJqrBfb(StringUtils.isNotEmpty(item.getYesCountNum()) && !"0".equals(item.getYesCountNum()) ? new BigDecimal(item.getYesCountNum()).subtract(new BigDecimal(item.getCountNum())).divide(new BigDecimal(item.getYesCountNum()), 4, RoundingMode.HALF_UP).multiply(new BigDecimal(100)).setScale(2, RoundingMode.HALF_UP) + "%" : "0.00%");
        }
    }
}
