package com.ruoyi.system.service.visit.impl;

import cn.hutool.core.lang.Validator;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.zqt.ZQTPageUtil;
import com.ruoyi.system.domain.system.SysOtherappAttachment;
import com.ruoyi.system.domain.system.SysOtherappAttachmentExample;
import com.ruoyi.system.domain.system.enums.AttachEnums;
import com.ruoyi.system.domain.visit.*;
import com.ruoyi.system.domain.visit.ext.VisitFreeInterviewExt;
import com.ruoyi.system.domain.visit.vo.VisitFreeInterviewSearchParam;
import com.ruoyi.system.domain.visit.vo.VisitPlanSearchParam;
import com.ruoyi.system.listener.MyBaseService;
import com.ruoyi.system.mapper.grid.GridHouseMapper;
import com.ruoyi.system.mapper.grid.GridPeopleMapper;
import com.ruoyi.system.mapper.visit.VisitFreeInterviewMapper;
import com.ruoyi.system.mapper.visit.VisitFreePlanModelMapper;
import com.ruoyi.system.service.BaseServiceImpl;
import com.ruoyi.system.service.grid.*;
import com.ruoyi.system.service.system.SysOtherappAttachmentService;
import com.ruoyi.system.service.visit.VisitFreeInterviewService;
import com.ruoyi.system.service.visit.VisitFreePlanService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

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

/**
 * VisitFreeInterviewService实现
 * Created by cesar.X on 2022/6/21.
 */
@Service
@MyBaseService
public class VisitFreeInterviewServiceImpl extends BaseServiceImpl<VisitFreeInterviewMapper, VisitFreeInterview, VisitFreeInterviewExample> implements VisitFreeInterviewService {

    private static final Logger LOGGER = LoggerFactory.getLogger(VisitFreeInterviewServiceImpl.class);

    @Autowired
    VisitFreeInterviewMapper visitFreeInterviewMapper;

    @Autowired
    SysOtherappAttachmentService sysOtherappAttachmentService;

    @Autowired
    VisitFreePlanService visitFreePlanService;

    @Autowired
    VisitFreePlanModelMapper visitFreePlanModelMapper;

    @Autowired
    GridRegionService gridRegionService;

    @Autowired
    GridCompanyService wsCompanyService;

    @Autowired
    GridShopService wsShopService;

    @Autowired
    GridHouseService wsHouseService;

    @Autowired
    GridHouseMapper wsHouseMapper;

    @Autowired
    GridPeopleService wsPeopleService;

    @Autowired
    GridPeopleMapper wsPeopleMapper;

    @Autowired
    GridRegionUserService bsWgxxUserService;

    @Autowired
    VisitAsyncServiceImpl asyncService;

    private static String comma = ",";

    @Override
    public synchronized AjaxResult addVisitFreeInterview(VisitFreeInterviewExt visitFreeInterview) {
        return asyncService.addVisitFreeInterview(visitFreeInterview);
    }

    @Override
    public PageInfo<VisitFreeInterviewExt> freeInterviewPage(String visitType, int pageNum, int pageSize,
                                                             List<String> wgCodes, String startTime, String endTime, String type,
                                                             String planModelId, String wgCode) {
        VisitFreeInterviewExample example = new VisitFreeInterviewExample();
        VisitFreeInterviewExample.Criteria criteria = example.createCriteria();
        criteria.andIsValidEqualTo("1");

        if (!CollectionUtils.isEmpty(wgCodes)) {
            criteria.andWgCodeIn(wgCodes);
        }
        if (org.apache.commons.lang3.StringUtils.isNotBlank(wgCode)) {
            criteria.andWgCodeLike(wgCode + "%");
        }
        if (org.apache.commons.lang3.StringUtils.isNotBlank(startTime)) {
            criteria.andInterviewTimeGreaterThanOrEqualTo(startTime);
        }
        if (org.apache.commons.lang3.StringUtils.isNotBlank(endTime)) {
            criteria.andInterviewTimeLessThanOrEqualTo(endTime);
        }
        if (org.apache.commons.lang3.StringUtils.isNotBlank(type)) {
            criteria.andTypeEqualTo(type);
        }
        if (org.apache.commons.lang3.StringUtils.isNotBlank(planModelId)) {
            criteria.andModelIdEqualTo(planModelId);
        }

        PageHelper.startPage(pageNum, pageSize);
        List<VisitFreeInterview> visitFreeInterviews = visitFreeInterviewMapper.selectByExampleWithBLOBs(example);
        int count = (int) visitFreeInterviewMapper.countByExample(example);

        List<VisitFreeInterviewExt> interviewExts = new ArrayList<>();
        if (!CollectionUtils.isEmpty(visitFreeInterviews)) {
            List<String> interviewIds = visitFreeInterviews.stream().map(o -> o.getId()).collect(Collectors.toList());

            SysOtherappAttachmentExample attachmentExample = new SysOtherappAttachmentExample();
            attachmentExample.createCriteria().andBusinessIdIn(interviewIds)
                    .andAttachTypeEqualTo(AttachEnums.AttachType.FREE_PLAN_INTERVIEW.name());
            List<SysOtherappAttachment> wsOtherappAttachments = sysOtherappAttachmentService.selectByExample(attachmentExample);

            visitFreeInterviews.forEach(visitFreeInterview -> {
                VisitFreeInterviewExt interviewExt = new VisitFreeInterviewExt();
                BeanUtils.copyProperties(visitFreeInterview, interviewExt);
                interviewExt.setOtherappAttachments(wsOtherappAttachments.stream()
                        .filter(o -> visitFreeInterview.getId().equals(o.getBusinessId())).collect(Collectors.toList()));
                interviewExts.add(interviewExt);
            });
        }

        PageInfo<VisitFreeInterviewExt> pageInfo = new PageInfo<>(interviewExts);
        return ZQTPageUtil.build(pageInfo, pageNum, pageSize, count);
    }

    @Override
    public List<VisitFreeInterview> interviewList(String visitType, String wgCode, String startTime, String endTime) {
        VisitFreeInterviewExample example = new VisitFreeInterviewExample();
        VisitFreeInterviewExample.Criteria criteria = example.createCriteria();
        criteria.andIsValidEqualTo("1");

        if (org.apache.commons.lang3.StringUtils.isNotBlank(wgCode)) {
            criteria.andWgCodeLike(wgCode + "%");
        }
        if (org.apache.commons.lang3.StringUtils.isNotBlank(startTime)) {
            criteria.andInterviewTimeGreaterThanOrEqualTo(startTime);
        }
        if (org.apache.commons.lang3.StringUtils.isNotBlank(endTime)) {
            criteria.andInterviewTimeLessThanOrEqualTo(endTime);
        }
        if (org.apache.commons.lang3.StringUtils.isNotBlank(visitType)) {
            criteria.andVisitTypeEqualTo(visitType);
        }
        return visitFreeInterviewMapper.selectByExampleWithBLOBs(example);
    }

    @Override
    public Map<String, Long> freePlanInterviewStatistic(String planModelId, List<String> wgCodes, String wgCode) {

        Validator.validateNotEmpty(planModelId, "自由走访id未传");

        Map<String, Long> result = new HashMap<>();
        result.put("all", 0L);
        result.put("allDone", 0L);

        VisitFreePlanModel planModel = visitFreePlanModelMapper.selectByPrimaryKey(planModelId);

        result.put("unlimited", Long.valueOf(planModel.getUnlimited()));
        result.put("com", 0L);
        result.put("shop", 0L);
        result.put("house", 0L);
        result.put("people", 0L);
        result.put("comDone", 0L);
        result.put("shopDone", 0L);
        result.put("houseDone", 0L);
        result.put("peopleDone", 0L);

        VisitFreePlanExample freePlanExample = new VisitFreePlanExample();
        VisitFreePlanExample.Criteria freePlanExampleCriteria = freePlanExample.createCriteria();
        freePlanExampleCriteria.andIsValidEqualTo("1");
        freePlanExampleCriteria.andPlanModelIdEqualTo(planModelId);

        if (!CollectionUtils.isEmpty(wgCodes)) {
            freePlanExampleCriteria.andWgCodeIn(wgCodes);
        }
        if (!StringUtils.isEmpty(wgCode)) {
            freePlanExampleCriteria.andWgCodeLike(wgCode + "%");
        }

        List<VisitFreePlan> freePlans = visitFreePlanService.selectByExample(freePlanExample);

        if (CollectionUtils.isEmpty(freePlans)) {
            return result;
        }

        Long all = 0L, com = 0L, shop = 0L, house = 0L, people = 0L;
        for (VisitFreePlan freePlan : freePlans) {
            all = all + freePlan.getPlanTotal();
            com = com + freePlan.getPlanComNum();
            shop = shop + freePlan.getPlanShopNum();
            house = house + freePlan.getPlanHouseNum();
            people = people + freePlan.getPlanPeopleNum();
        }

        result.put("all", all);
        result.put("com", com);
        result.put("shop", shop);
        result.put("house", house);
        result.put("people", people);

        VisitFreeInterviewExample example = new VisitFreeInterviewExample();
        VisitFreeInterviewExample.Criteria criteria = example.createCriteria();
        criteria.andIsValidEqualTo("1");

        criteria.andModelIdEqualTo(planModelId);

        if (!CollectionUtils.isEmpty(wgCodes)) {
            criteria.andWgyCodeIn(wgCodes);
        }
        if (!StringUtils.isEmpty(wgCode)) {
            criteria.andWgyCodeLike(wgCode + "%");
        }

        List<VisitFreeInterview> visitFreeInterviews = visitFreeInterviewMapper.selectByExample(example);

        if (!CollectionUtils.isEmpty(visitFreeInterviews)) {
            result.put("comDone", visitFreeInterviews.stream().filter(o -> "1".equals(o.getType())).count());
            result.put("shopDone", visitFreeInterviews.stream().filter(o -> "2".equals(o.getType())).count());
            result.put("houseDone", visitFreeInterviews.stream().filter(o -> "3".equals(o.getType())).count());
            result.put("peopleDone", visitFreeInterviews.stream().filter(o -> "4".equals(o.getType())).count());

            result.put("allDone", result.get("comDone") + result.get("shopDone") + result.get("houseDone") + result.get("peopleDone"));
        }

        return result;
    }

    @Override
    public Map<String, Long> interviewCountStatistic(String visitType) {
        List<Map<String, Object>> visitFreeInterviewsList = visitFreeInterviewMapper.freeVisitStatistics(visitType);

        Map<String, Long> result = new HashMap<>();
        result.put("com", 0L);
        result.put("shop", 0L);
        result.put("house", 0L);
        result.put("people", 0L);

        if (CollectionUtils.isEmpty(visitFreeInterviewsList)) {
            return result;
        }
        for(Map<String, Object> map : visitFreeInterviewsList){
            if(map.get("type").equals("1")){
                result.put("com", (Long) map.get("count"));
            }else if(map.get("type").equals("2")){
                result.put("shop", (Long) map.get("count"));
            }else if(map.get("type").equals("3")){
                result.put("house", (Long) map.get("count"));
            } else if(map.get("type").equals("4")){
                result.put("people", (Long) map.get("count"));
            }
        }

        return result;
    }

    @Override
    public Map<String, Long> interviewStatistic(String wgCode, String visitType, String startDate, String endDate) {

        Map<String, Long> result = new HashMap<>();
        result.put("all", 0L);
        result.put("allDone", 0L);

        VisitPlanSearchParam param = new VisitPlanSearchParam();
        param.setVisitType(visitType);
        param.setWgCodeLikes(Arrays.asList(wgCode.split(",")));
        param.setStartDate(startDate);
        param.setEndDate(endDate);
        List<VisitFreePlan> freePlans = visitFreePlanService.listByParams(param);
        if (CollectionUtils.isEmpty(freePlans)) {
            return result;
        }

        Long all = 0L;
        for (VisitFreePlan freePlan : freePlans) {
            all = all + freePlan.getPlanTotal();
        }

        result.put("all", all);

        VisitFreeInterviewSearchParam interviewSearchParam = new VisitFreeInterviewSearchParam();
        interviewSearchParam.setStartDate(startDate);
        interviewSearchParam.setEndDate(endDate);
        interviewSearchParam.setVisitType(visitType);
        interviewSearchParam.setWgCodeLikes(Arrays.asList(wgCode.split(",")));
        List<VisitFreeInterview> visitFreeInterviews = visitFreeInterviewMapper.listByParams(interviewSearchParam);

        if (!CollectionUtils.isEmpty(visitFreeInterviews)) {
            Map<String, List<VisitFreeInterview>> map = visitFreeInterviews.stream().filter(o -> !StringUtils.isEmpty(o.getPlanId()))
                    .collect(Collectors.groupingBy(o -> o.getPlanId() + o.getObjId() + o.getType()));
            result.put("allDone", Long.valueOf(map.size()));
        }

        return result;
    }

    //    本周走访工单数--最新的一个走访自由走访的数量（总数）
//    企业，商铺，住宅，人口--最新的一个走访自由走访的对象数量（总数）
//    完成情况--最新一个走访周期的自由走访的网格完成情况
    @Override
    public Map<String, Object> freeInterviewStatistic(String visitType) {
        VisitFreePlanModelExample freePlanModelParam = new VisitFreePlanModelExample();
        freePlanModelParam.createCriteria().andIsValidEqualTo("1").andVisitTypeEqualTo(visitType);
        List<VisitFreePlanModel> planModels = visitFreePlanModelMapper.selectByExample(freePlanModelParam);

        Map<String, Object> result = new HashMap<>();
        if (CollectionUtils.isEmpty(planModels)) {
            result.put("all", 0L);
            result.put("allDone", 0L);
            result.put("com", 0L);
            result.put("shop", 0L);
            result.put("house", 0L);
            result.put("people", 0L);
            result.put("comDone", 0L);
            result.put("shopDone", 0L);
            result.put("houseDone", 0L);
            result.put("peopleDone", 0L);
            result.put("wgDoneNum", 0L);
            result.put("wgNum", 0L);
            result.put("title", "");
            result.put("startTime", "");
            result.put("endTime", "");
        } else {
            Optional<VisitFreePlanModel> op = planModels.stream().sorted(Comparator.comparing(VisitFreePlanModel::getCreateTime, Comparator.reverseOrder())).findFirst();
            if (op.isPresent()) {
                VisitFreePlanModel planModel = op.get();
                Map<String, Long> temp = this.freePlanInterviewStatistic(planModel.getId(), null, null);
                for (String key : temp.keySet()) {
                    result.put(key, temp.get(key));
                }

                VisitFreePlanExample planExample = new VisitFreePlanExample();
                planExample.createCriteria().andPlanModelIdEqualTo(planModel.getId()).andIsValidEqualTo("1");
                List<VisitFreePlan> freePlans = visitFreePlanService.selectByExample(planExample);
                Long doneNum = freePlans.stream().filter(o -> "4".equals(o.getHasDone())).count();

                result.put("wgDoneNum", doneNum);
                result.put("wgNum", Long.valueOf(String.valueOf(freePlans.size())));
                result.put("title", planModel.getPlanTitle());
                result.put("startTime", planModel.getStartTime());
                result.put("endTime", planModel.getEndTime());
            }
        }

        return result;
    }


}