package com.mortals.xhx.module.pj.service.impl;

import com.mortals.framework.common.Rest;
import com.mortals.framework.model.OrderCol;
import com.mortals.framework.model.PageInfo;
import com.mortals.framework.model.Result;
import com.mortals.xhx.common.code.TimeUnitEnum;
import com.mortals.xhx.common.utils.BeanUtil;
import com.mortals.xhx.module.pj.model.PjEvaluateEntity;
import com.mortals.xhx.module.pj.model.PjEvaluateQuery;
import com.mortals.xhx.module.pj.model.PjEvaluateStatQuery;
import com.mortals.xhx.module.pj.service.PjEvaluateService;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.mortals.framework.service.impl.AbstractCRUDServiceImpl;
import com.mortals.framework.exception.AppException;
import com.mortals.framework.model.Context;
import com.mortals.xhx.module.pj.dao.PjEvaluateStatDao;
import com.mortals.xhx.module.pj.model.PjEvaluateStatEntity;
import com.mortals.xhx.module.pj.service.PjEvaluateStatService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ObjectUtils;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * PjEvaluateStatService
 * 评价汇总统计 service实现
 *
 * @author zxfei
 * @date 2024-06-24
 */
@Service("pjEvaluateStatService")
@Slf4j
public class PjEvaluateStatServiceImpl extends AbstractCRUDServiceImpl<PjEvaluateStatDao, PjEvaluateStatEntity, Long> implements PjEvaluateStatService {

    @Autowired
    private PjEvaluateService pjEvaluateService;


    @Override
    public Result<PjEvaluateStatEntity> find(PjEvaluateStatEntity entity, PageInfo pageInfo, Context context) throws AppException {
        Result<PjEvaluateStatEntity> result = new Result<>();
        PjEvaluateStatQuery query = new PjEvaluateStatQuery();
        BeanUtils.copyProperties(entity, query, BeanUtil.getNullPropertyNames(entity));
        List<PjEvaluateStatEntity> billInfos = this.getBillInfos(query, pageInfo, context);
        result.setList(billInfos);
        result.setPageInfo(pageInfo);
        return result;
    }

    @Override
    public Rest<Void> updateSitePjStat(PjEvaluateStatEntity entity, Context context) {
        //todo 统计站点评价 分站点--部门 ||窗口编号||评价选项  ==》评价数量
        //查询指定日期当前站点所有评价数量
        Calendar calendar = Calendar.getInstance();
        calendar.set(entity.getYear(), entity.getMonth() - 1, entity.getDay());

        SimpleDateFormat date = new SimpleDateFormat("yyyy-MM-dd");//yyyy-年，MM-月，dd-日，HH-时，mm-分，ss-秒
        String currentDate = date.format(calendar.getTime());

        PjEvaluateQuery pjEvaluateQuery = new PjEvaluateQuery();
        pjEvaluateQuery.setSiteId(entity.getSiteId());
        pjEvaluateQuery.setPjTimeStart(currentDate);
        pjEvaluateQuery.setPjTimeEnd(currentDate);

        List<PjEvaluateEntity> pjEvaluateEntities = pjEvaluateService.find(pjEvaluateQuery);

        log.info("更新站点评价统计数据，站点ID：{}，站点名称：{}，日期：{}，评价数量：{}", entity.getSiteId(), entity.getSiteName(), currentDate, pjEvaluateEntities.size());
        updateSitePjCount(entity, pjEvaluateEntities);

        updateSiteSectionNamePjCount(currentDate, entity, pjEvaluateEntities);

        updateSiteHallPjCount(currentDate, entity, pjEvaluateEntities);

        updateSiteWindowPjCount(currentDate, entity, pjEvaluateEntities);

        updateSiteOptionPjCount(currentDate, entity, pjEvaluateEntities);

        return Rest.ok();
    }


    private void updateSitePjCount(PjEvaluateStatEntity entity, List<PjEvaluateEntity> pjEvaluateEntities) {
        if (ObjectUtils.isEmpty(entity.getSiteId())) return;
        if (0L >= entity.getSiteId()) return;
        PjEvaluateStatEntity pjEvaluateStatEntity = this.selectOne(new PjEvaluateStatQuery()
                .siteId(entity.getSiteId())
                .year(entity.getYear())
                .month(entity.getMonth())
                .day(entity.getDay()));
        if (ObjectUtils.isEmpty(pjEvaluateStatEntity)) {
            //统计当前站点新增所有评价数量
            pjEvaluateStatEntity = new PjEvaluateStatEntity();
            pjEvaluateStatEntity.initAttrValue();
            pjEvaluateStatEntity.setSiteId(entity.getSiteId());
            pjEvaluateStatEntity.setSiteCode(entity.getSiteCode());
            pjEvaluateStatEntity.setSiteName(entity.getSiteName());
            pjEvaluateStatEntity.setPjCount(pjEvaluateEntities.size());
            pjEvaluateStatEntity.setYear(entity.getYear());
            pjEvaluateStatEntity.setMonth(entity.getMonth());
            pjEvaluateStatEntity.setDay(entity.getDay());
            pjEvaluateStatEntity.setCreateTime(new Date());
            pjEvaluateStatEntity.setCreateUserId(1L);
            this.save(pjEvaluateStatEntity);
        } else {
            pjEvaluateStatEntity.setPjCount(pjEvaluateEntities.size());
            pjEvaluateStatEntity.setYear(entity.getYear());
            pjEvaluateStatEntity.setMonth(entity.getMonth());
            pjEvaluateStatEntity.setDay(entity.getDay());
            pjEvaluateStatEntity.setUpdateTime(new Date());
            pjEvaluateStatEntity.setUpdateUserId(1L);
            this.update(pjEvaluateStatEntity);
        }
    }


    private void updateSiteSectionNamePjCount(String currentDate, PjEvaluateStatEntity entity, List<PjEvaluateEntity> pjEvaluateEntities) {

        Map<String, Long> collect = pjEvaluateEntities.stream().collect(Collectors.groupingBy(x -> x.getSectionName(), Collectors.counting()));
        collect.entrySet().stream().forEach(item -> {
            String sectionName = item.getKey();
            if (ObjectUtils.isEmpty(sectionName)) return;
            Long value = item.getValue();
            log.info("更新站点评价统计数据，站点名称：{}，日期：{}，部门：{}，评价数量：{}", entity.getSiteName(), currentDate, entity.getSectionName(), pjEvaluateEntities.size());
            PjEvaluateStatEntity pjEvaluateStatEntity = this.selectOne(new PjEvaluateStatQuery()
                    .siteId(entity.getSiteId())
                    .sectionName(sectionName)
                    .year(entity.getYear())
                    .month(entity.getMonth())
                    .day(entity.getDay()));
            if (ObjectUtils.isEmpty(pjEvaluateStatEntity)) {
                //统计当前站点新增所有评价数量
                pjEvaluateStatEntity = new PjEvaluateStatEntity();
                pjEvaluateStatEntity.initAttrValue();
                pjEvaluateStatEntity.setSiteId(entity.getSiteId());
                pjEvaluateStatEntity.setSiteCode(entity.getSiteCode());
                pjEvaluateStatEntity.setSiteName(entity.getSiteName());
                pjEvaluateStatEntity.setSectionName(sectionName);
                pjEvaluateStatEntity.setPjCount(value.intValue());
                pjEvaluateStatEntity.setYear(entity.getYear());
                pjEvaluateStatEntity.setMonth(entity.getMonth());
                pjEvaluateStatEntity.setDay(entity.getDay());
                pjEvaluateStatEntity.setCreateTime(new Date());
                pjEvaluateStatEntity.setCreateUserId(1L);
                this.save(pjEvaluateStatEntity);
            } else {
                pjEvaluateStatEntity.setPjCount(value.intValue());
                pjEvaluateStatEntity.setYear(entity.getYear());
                pjEvaluateStatEntity.setMonth(entity.getMonth());
                pjEvaluateStatEntity.setDay(entity.getDay());
                pjEvaluateStatEntity.setUpdateTime(new Date());
                pjEvaluateStatEntity.setUpdateUserId(1L);
                this.update(pjEvaluateStatEntity);
            }
        });
    }


    private void updateSiteHallPjCount(String currentDate, PjEvaluateStatEntity entity, List<PjEvaluateEntity> pjEvaluateEntities) {

        Map<String, Long> collect = pjEvaluateEntities.stream().collect(Collectors.groupingBy(x -> x.getHallName(), Collectors.counting()));
        collect.entrySet().stream().forEach(item -> {
            String hallName = item.getKey();

            if (ObjectUtils.isEmpty(hallName)) return;

            Long value = item.getValue();
            log.info("更新站点评价统计数据，站点名称：{}，日期：{}，部门：{}，评价数量：{}", entity.getSiteName(), currentDate, entity.getSectionName(), pjEvaluateEntities.size());
            PjEvaluateStatEntity pjEvaluateStatEntity = this.selectOne(new PjEvaluateStatQuery()
                    .siteId(entity.getSiteId())
                    .hallName(hallName)
                    .year(entity.getYear())
                    .month(entity.getMonth())
                    .day(entity.getDay()));
            if (ObjectUtils.isEmpty(pjEvaluateStatEntity)) {
                //统计当前站点新增所有评价数量
                pjEvaluateStatEntity = new PjEvaluateStatEntity();
                pjEvaluateStatEntity.initAttrValue();
                pjEvaluateStatEntity.setSiteId(entity.getSiteId());
                pjEvaluateStatEntity.setSiteCode(entity.getSiteCode());
                pjEvaluateStatEntity.setSiteName(entity.getSiteName());
                pjEvaluateStatEntity.setHallName(hallName);
                pjEvaluateStatEntity.setPjCount(value.intValue());
                pjEvaluateStatEntity.setYear(entity.getYear());
                pjEvaluateStatEntity.setMonth(entity.getMonth());
                pjEvaluateStatEntity.setDay(entity.getDay());
                pjEvaluateStatEntity.setCreateTime(new Date());
                pjEvaluateStatEntity.setCreateUserId(1L);
                this.save(pjEvaluateStatEntity);
            } else {
                pjEvaluateStatEntity.setPjCount(value.intValue());
                pjEvaluateStatEntity.setYear(entity.getYear());
                pjEvaluateStatEntity.setMonth(entity.getMonth());
                pjEvaluateStatEntity.setDay(entity.getDay());
                pjEvaluateStatEntity.setUpdateTime(new Date());
                pjEvaluateStatEntity.setUpdateUserId(1L);
                this.update(pjEvaluateStatEntity);
            }
        });
    }


    private void updateSiteWindowPjCount(String currentDate, PjEvaluateStatEntity entity, List<PjEvaluateEntity> pjEvaluateEntities) {

        Map<String, Long> collect = pjEvaluateEntities.stream().collect(Collectors.groupingBy(x -> x.getWindowFromnum(), Collectors.counting()));
        collect.entrySet().stream().forEach(item -> {
            String windowFromnum = item.getKey();
            if (ObjectUtils.isEmpty(windowFromnum)) return;
            Long value = item.getValue();
            log.info("更新站点评价统计数据，站点名称：{}，日期：{}，窗口：{}，评价数量：{}", entity.getSiteName(), currentDate, entity.getWindowFromnum(), pjEvaluateEntities.size());
            PjEvaluateStatEntity pjEvaluateStatEntity = this.selectOne(new PjEvaluateStatQuery()
                    .siteId(entity.getSiteId())
                    .windowFromnum(windowFromnum)
                    .year(entity.getYear())
                    .month(entity.getMonth())
                    .day(entity.getDay()));
            if (ObjectUtils.isEmpty(pjEvaluateStatEntity)) {
                //统计当前站点新增所有评价数量
                pjEvaluateStatEntity = new PjEvaluateStatEntity();
                pjEvaluateStatEntity.initAttrValue();
                pjEvaluateStatEntity.setSiteId(entity.getSiteId());
                pjEvaluateStatEntity.setSiteCode(entity.getSiteCode());
                pjEvaluateStatEntity.setSiteName(entity.getSiteName());
                pjEvaluateStatEntity.setWindowFromnum(windowFromnum);
                pjEvaluateStatEntity.setPjCount(value.intValue());
                pjEvaluateStatEntity.setYear(entity.getYear());
                pjEvaluateStatEntity.setMonth(entity.getMonth());
                pjEvaluateStatEntity.setDay(entity.getDay());
                pjEvaluateStatEntity.setCreateTime(new Date());
                pjEvaluateStatEntity.setCreateUserId(1L);
                this.save(pjEvaluateStatEntity);
            } else {
                pjEvaluateStatEntity.setPjCount(value.intValue());
                pjEvaluateStatEntity.setYear(entity.getYear());
                pjEvaluateStatEntity.setMonth(entity.getMonth());
                pjEvaluateStatEntity.setDay(entity.getDay());
                pjEvaluateStatEntity.setUpdateTime(new Date());
                pjEvaluateStatEntity.setUpdateUserId(1L);
                this.update(pjEvaluateStatEntity);
            }
        });
    }


    private void updateSiteOptionPjCount(String currentDate, PjEvaluateStatEntity entity, List<PjEvaluateEntity> pjEvaluateEntities) {

        Map<String, Long> collect = pjEvaluateEntities.stream().collect(Collectors.groupingBy(x -> x.getPjOption(), Collectors.counting()));
        collect.entrySet().stream().forEach(item -> {
            String pjOption = item.getKey();
            if (ObjectUtils.isEmpty(pjOption)) return;
            Long value = item.getValue();
            log.info("更新站点评价统计数据，站点名称：{}，日期：{}，窗口：{}，评价数量：{}", entity.getSiteName(), currentDate, entity.getWindowFromnum(), pjEvaluateEntities.size());
            PjEvaluateStatEntity pjEvaluateStatEntity = this.selectOne(new PjEvaluateStatQuery()
                    .siteId(entity.getSiteId())
                    .pjOption(pjOption)
                    .year(entity.getYear())
                    .month(entity.getMonth())
                    .day(entity.getDay()));
            if (ObjectUtils.isEmpty(pjEvaluateStatEntity)) {
                //统计当前站点新增所有评价数量
                pjEvaluateStatEntity = new PjEvaluateStatEntity();
                pjEvaluateStatEntity.initAttrValue();
                pjEvaluateStatEntity.setSiteId(entity.getSiteId());
                pjEvaluateStatEntity.setSiteCode(entity.getSiteCode());
                pjEvaluateStatEntity.setSiteName(entity.getSiteName());
                pjEvaluateStatEntity.setPjOption(pjOption);
                pjEvaluateStatEntity.setPjCount(value.intValue());
                pjEvaluateStatEntity.setYear(entity.getYear());
                pjEvaluateStatEntity.setMonth(entity.getMonth());
                pjEvaluateStatEntity.setDay(entity.getDay());
                pjEvaluateStatEntity.setCreateTime(new Date());
                pjEvaluateStatEntity.setCreateUserId(1L);
                this.save(pjEvaluateStatEntity);
            } else {
                pjEvaluateStatEntity.setPjCount(value.intValue());
                pjEvaluateStatEntity.setYear(entity.getYear());
                pjEvaluateStatEntity.setMonth(entity.getMonth());
                pjEvaluateStatEntity.setDay(entity.getDay());
                pjEvaluateStatEntity.setUpdateTime(new Date());
                pjEvaluateStatEntity.setUpdateUserId(1L);
                this.update(pjEvaluateStatEntity);
            }
        });
    }


    @Override
    public List<PjEvaluateStatEntity> getBillInfos(PjEvaluateStatQuery query, PageInfo pageInfo, Context context) {
        if (!ObjectUtils.isEmpty(query.getGroupList())) {
            //针对groupList分组 进行排序
            if (query.getGroupList().contains("year") && query.getGroupList().contains("month") && query.getGroupList().contains("day")) {
                query.setOrderColList(Arrays.asList(new OrderCol("year", OrderCol.DESCENDING), new OrderCol("month", OrderCol.DESCENDING), new OrderCol("day", OrderCol.DESCENDING), new OrderCol("createTime")));
            } else if (query.getGroupList().contains("year") && query.getGroupList().contains("month")) {
                query.setOrderColList(Arrays.asList(new OrderCol("year", OrderCol.DESCENDING), new OrderCol("month", OrderCol.DESCENDING), new OrderCol("createTime")));
            } else if (query.getGroupList().contains("year")) {
                query.setOrderColList(Arrays.asList(new OrderCol("year", OrderCol.DESCENDING), new OrderCol("createTime")));
            }
        }
        return this.getDao().getStatList(query, pageInfo);
    }
}