package com.ruoyi.demo.service.impl;


import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.demo.entity.AttentionPool;
import com.ruoyi.demo.entity.BusinessOpportunitiesClue;
import com.ruoyi.demo.entity.FollowUpRecord;
import com.ruoyi.demo.entity.bo.AttentionPoolStatisticsBo;
import com.ruoyi.demo.entity.bo.WorkTableBo;
import com.ruoyi.demo.mapper.AttentionPoolDao;
import com.ruoyi.demo.mapper.AttentionPoolStatisticsDao;
import com.ruoyi.demo.mapper.BusinessOpportunitiesDao;
import com.ruoyi.demo.mapper.FollowUpDao;
import com.ruoyi.demo.service.DatabackService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.List;

@Service
@Transactional
public class DatabackServiceImpl implements DatabackService {
    @Autowired
    AttentionPoolStatisticsDao attentionPoolStatisticsDao;
    @Autowired
    AttentionPoolDao attentionPoolDao;
    @Autowired
    BusinessOpportunitiesDao businessOpportunitiesDao;
    @Autowired
    FollowUpDao followUpDao;

    @Override
    public AttentionPoolStatisticsBo searchAbout(String userId, WorkTableBo vo) {
        // 查询潜客数
        int attentionCount = 0;
        QueryWrapper<AttentionPool> attentionPoolQueryWrapper = new QueryWrapper<>();
        attentionPoolQueryWrapper.eq("user_id", userId);
        if (vo.getStartTime() != null)
            attentionPoolQueryWrapper.apply("DATE_FORMAT(`attention_time`,'%Y-%m-%d %H:%i:%s') >= DATE_FORMAT({0},'%Y-%m-%d %H:%i:%s')", vo.getStartTime());
        if (vo.getEndTime() != null)
            attentionPoolQueryWrapper.apply("DATE_FORMAT(`attention_time`,'%Y-%m-%d %H:%i:%s') <= DATE_FORMAT({0},'%Y-%m-%d %H:%i:%s')", vo.getEndTime());
        List<AttentionPool> attentionPools = attentionPoolDao.selectList(attentionPoolQueryWrapper);
        if (attentionPools != null)
            attentionCount = attentionPools.size();

        // 查询商机数
        int clueCount = 0;
        QueryWrapper<BusinessOpportunitiesClue> businessOpportunitiesClueQueryWrapper = new QueryWrapper<>();
        businessOpportunitiesClueQueryWrapper.eq("user_id", userId);
        if (vo.getStartTime() != null)
            businessOpportunitiesClueQueryWrapper.apply("DATE_FORMAT(`create_time`,'%Y-%m-%d %H:%i:%s') >= DATE_FORMAT({0},'%Y-%m-%d %H:%i:%s')", vo.getStartTime());
        if (vo.getEndTime() != null)
            businessOpportunitiesClueQueryWrapper.apply("DATE_FORMAT(`create_time`,'%Y-%m-%d %H:%i:%s') <= DATE_FORMAT({0},'%Y-%m-%d %H:%i:%s')", vo.getEndTime());
        List<BusinessOpportunitiesClue> businessOpportunitiesClues = businessOpportunitiesDao.selectList(businessOpportunitiesClueQueryWrapper);
        if (businessOpportunitiesClues != null)
            clueCount = businessOpportunitiesClues.size();

        // 查询线上电话数
        int onlineCount = 0;
        QueryWrapper<FollowUpRecord> followUpRecordQueryWrapper = new QueryWrapper<>();
        followUpRecordQueryWrapper.eq("user_id", userId)
            .eq("follow_way", "线上电话");
        if (vo.getStartTime() != null)
            followUpRecordQueryWrapper.apply("DATE_FORMAT(`follow_time`,'%Y-%m-%d %H:%i:%s') >= DATE_FORMAT({0},'%Y-%m-%d %H:%i:%s')", vo.getStartTime());
        if (vo.getEndTime() != null)
            followUpRecordQueryWrapper.apply("DATE_FORMAT(`follow_time`,'%Y-%m-%d %H:%i:%s') <= DATE_FORMAT({0},'%Y-%m-%d %H:%i:%s')", vo.getEndTime());
        List<FollowUpRecord> followUpRecords = followUpDao.selectList(followUpRecordQueryWrapper);
        if (followUpRecords != null)
            onlineCount = followUpRecords.size();

        // 查询实地考察数
        int offlineCount = 0;
        QueryWrapper<FollowUpRecord> followUpRecordQueryWrapper1 = new QueryWrapper<>();
        followUpRecordQueryWrapper1.eq("user_id", userId)
            .eq("follow_way", "实地考察");
        if (vo.getStartTime() != null)
            followUpRecordQueryWrapper1.apply("DATE_FORMAT(`follow_time`,'%Y-%m-%d %H:%i:%s') >= DATE_FORMAT({0},'%Y-%m-%d %H:%i:%s')", vo.getStartTime());
        if (vo.getEndTime() != null)
            followUpRecordQueryWrapper1.apply("DATE_FORMAT(`follow_time`,'%Y-%m-%d %H:%i:%s') <= DATE_FORMAT({0},'%Y-%m-%d %H:%i:%s')", vo.getEndTime());
        List<FollowUpRecord> followUpRecords1 = followUpDao.selectList(followUpRecordQueryWrapper1);
        if (followUpRecords1 != null)
            offlineCount = followUpRecords1.size();

        return new AttentionPoolStatisticsBo(attentionCount, clueCount, onlineCount, offlineCount);
    }

    @Override
    public List<AttentionPoolStatisticsBo> searchTrand(String userId, String condition) {
        List<AttentionPoolStatisticsBo> list = new ArrayList<>();
        if (condition.equals("day")) { // 时间粒度：天
            List<String> days = new ArrayList<>();
            for (int i = 1; i <= 30; i++)
                // days.add(LocalDateTime.now(ZoneId.of("Asia/Shanghai")).plusDays(-i).format(DateTimeFormatter.ofPattern("yyyy-MM-dd")).toString());
                days.add(DateUtil.offsetDay(new Date(), -i).toString("yyyy-MM-dd"));

            list = attentionPoolStatisticsDao.selectAllByUserIdAndDay(userId, days);
            // 补齐空数据
            list.forEach(bo -> days.remove(bo.getTime()));
            if (!days.isEmpty())
                for (String day : days)
                    list.add(new AttentionPoolStatisticsBo(day));
        } else if (condition.equals("year")) { // 时间粒度：年
            List<String> years = new ArrayList<>();
            for (int i = 0; i < 5; i++)
                // years.add(LocalDateTime.now(ZoneId.of("Asia/Shanghai")).plusYears(-i).format(DateTimeFormatter.ofPattern("yyyy")).toString());
                years.add(DateUtil.offset(DateUtil.date(), DateField.YEAR, -i).toString("yyyy"));

            list = attentionPoolStatisticsDao.selectAllByUserIdAndYear(userId, years);
            // 补齐数据
            list.forEach(bo -> years.remove(bo.getTime()));
            if (!years.isEmpty())
                for (String year : years)
                    list.add(new AttentionPoolStatisticsBo(year));
        } else { // 时间粒度：月
            List<String> months = new ArrayList<>();
            for (int i = 0; i < 12; i++)
                // months.add(LocalDateTime.now(ZoneId.of("Asia/Shanghai")).plusMonths(-i).format(DateTimeFormatter.ofPattern("yyyy-MM")).toString());
                months.add(DateUtil.offsetMonth(new Date(), -i).toString("yyyy-MM"));

            list = attentionPoolStatisticsDao.selectAllByUserIdAndMonth(userId, months);
            // 补齐空数据
            list.forEach(bo -> months.remove(bo.getTime()));
            if (!months.isEmpty())
                for (String month : months)
                    list.add(new AttentionPoolStatisticsBo(month));
        }
        // 排序
        list.sort(new Comparator<AttentionPoolStatisticsBo>() {
            @Override
            public int compare(AttentionPoolStatisticsBo bo1, AttentionPoolStatisticsBo bo2) {
                return bo1.getTime().compareTo(bo2.getTime());
            }
        });
        return list;
    }
}
