package com.qmth.sop.business.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qmth.sop.business.bean.dto.DataPermissionDto;
import com.qmth.sop.business.bean.result.CrmAnalyseResult;
import com.qmth.sop.business.bean.result.TBCrmResult;
import com.qmth.sop.business.bean.result.UserArchivesAllocationResult;
import com.qmth.sop.business.entity.SysUser;
import com.qmth.sop.business.entity.TBCrm;
import com.qmth.sop.business.mapper.CrmAnalyseMapper;
import com.qmth.sop.business.mapper.ServiceAnalyseMapper;
import com.qmth.sop.business.service.CrmAnalyseService;
import com.qmth.sop.business.service.SysUserService;
import com.qmth.sop.common.enums.ProductTypeEnum;
import com.qmth.sop.common.util.ServletUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;


/**
 * @author dhshu
 * @date:
 */
@Service
public class CrmAnalyseServiceImpl extends ServiceImpl<CrmAnalyseMapper, TBCrm> implements CrmAnalyseService {

    @Resource
    private SysUserService sysUserService;

    @Override
    public Map<String, Object> countCustomType(Long startTime, Long endTime) {
        SysUser requestUser = (SysUser) ServletUtil.getRequestUser();
        DataPermissionDto dpr = sysUserService.buildUserDataPermission(requestUser.getId());
        return this.baseMapper.countCustomType(startTime, endTime, dpr);
    }

    @Override
    public IPage<TBCrmResult> customTypeDetail(Page<Object> iPage, Long startTime, Long endTime, ProductTypeEnum type) {
        SysUser requestUser = (SysUser) ServletUtil.getRequestUser();
        DataPermissionDto dpr = sysUserService.buildUserDataPermission(requestUser.getId());
        return this.baseMapper.crmDetail(iPage, startTime, endTime, Objects.nonNull(type) ? type.name() : null, dpr);
    }

    @Override
    public Map<String, List<Map<String, Object>>> monthly(Long startTime, Long endTime, ProductTypeEnum type) {
        SysUser requestUser = (SysUser) ServletUtil.getRequestUser();
        DataPermissionDto dpr = sysUserService.buildUserDataPermission(requestUser.getId());
        Map<String, List<Map<String, Object>>> map = new HashMap<>();
        map.put("year", this.baseMapper.monthly(startTime, endTime, Objects.nonNull(type) ? type.name() : null, dpr));
        map.put("lastYear", this.baseMapper.monthly(startTime - 365 * 24 * 60 * 60 * 1000L, endTime - 365 * 24 * 60 * 60 * 1000L, Objects.nonNull(type) ? type.name() : null, dpr));
        return map;
    }

    @Override
    public IPage<TBCrmResult> monthlyDetail(Page<Object> iPage, String year, String month, ProductTypeEnum type, Long startTime, Long endTime) {
        SysUser requestUser = (SysUser) ServletUtil.getRequestUser();
        DataPermissionDto dpr = sysUserService.buildUserDataPermission(requestUser.getId());
        return this.baseMapper.crmDetail(iPage, year, month, Objects.nonNull(type) ? type.name() : null,startTime,endTime, dpr);
    }

    @Override
    public List<CrmAnalyseResult> supplier(Long startTime, Long endTime) {
        SysUser requestUser = (SysUser) ServletUtil.getRequestUser();
        DataPermissionDto dpr = sysUserService.buildUserDataPermission(requestUser.getId());
        return this.baseMapper.supplier(startTime, endTime, dpr);
    }

    @Override
    public IPage<TBCrmResult> supplierDetail(Page<Object> iPage, Long startTime, Long endTime, Long supplierId) {
        SysUser requestUser = (SysUser) ServletUtil.getRequestUser();
        DataPermissionDto dpr = sysUserService.buildUserDataPermission(requestUser.getId());
        return this.baseMapper.crmDetailSupplier(iPage, startTime, endTime, supplierId, dpr);
    }

    @Override
    public List<CrmAnalyseResult> region(Long startTime, Long endTime, ProductTypeEnum type) {
        SysUser requestUser = (SysUser) ServletUtil.getRequestUser();
        DataPermissionDto dpr = sysUserService.buildUserDataPermission(requestUser.getId());
        List<CrmAnalyseResult> region = this.baseMapper.region(startTime, endTime, Objects.nonNull(type) ? type.name() : null, dpr);
        List<CrmAnalyseResult> region1 = this.baseMapper.region(startTime - 24 * 60 * 60 * 1000L, endTime - 24 * 60 * 60 * 1000L, Objects.nonNull(type) ? type.name() : null, dpr);

        return  region.stream().map(map->{
            CrmAnalyseResult crmAnalyseResult = region1.stream().filter(map1 -> map1.getName().equals(map.getName())).findFirst().orElse(new CrmAnalyseResult());
            map.setCompare(map.getCount()-crmAnalyseResult.getCount());
            map.setRate(String.format("%.2f", Double.parseDouble(String.valueOf(map.getCount()-crmAnalyseResult.getCount()))*100 /map.getCount()) + "%");
            return map;
        }).collect(Collectors.toList());
    }

    @Override
    public IPage<TBCrmResult> regionDetail(Page<Object> iPage, Long startTime, Long endTime, String province, ProductTypeEnum type) {
        SysUser requestUser = (SysUser) ServletUtil.getRequestUser();
        DataPermissionDto dpr = sysUserService.buildUserDataPermission(requestUser.getId());
        return this.baseMapper.crmDetail(iPage, startTime, endTime, province, Objects.nonNull(type) ? type.name() : null, dpr);
    }

    @Override
    public List<CrmAnalyseResult> project(Long startTime, Long endTime) {
        SysUser requestUser = (SysUser) ServletUtil.getRequestUser();
        DataPermissionDto dpr = sysUserService.buildUserDataPermission(requestUser.getId());
        List<Map<String, Object>> project = this.baseMapper.project(startTime, endTime, dpr);
        List<CrmAnalyseResult> list=new ArrayList<>();

        project.stream().collect(Collectors.groupingBy(map -> map.get("name"))).forEach((k, v) -> {
            CrmAnalyseResult crmAnalyseResult = new CrmAnalyseResult();
            crmAnalyseResult.setName((String) k);
            crmAnalyseResult.setId(Long.valueOf(v.get(0).get("id").toString()));
            int crmNum=v.stream().collect(Collectors.groupingBy(map -> map.get("crm_no"))).size();
            final int[] finish = {0};
            v.stream().collect(Collectors.groupingBy(map -> map.get("crm_no")))
                    .forEach((k1, v1) -> {
                        if (v1.stream().anyMatch(map2 -> map2.get("sop_no") != null) &&v1.stream().filter(map2 -> map2.get("sop_no") != null).count() == v1.stream().filter(map2 -> "FINISH".equals(map2.get("status"))).count()) {
                            finish[0] = finish[0] + 1;
                        }
                    });
            crmAnalyseResult.setRate(finish[0] *100/crmNum+"%");
            list.add(crmAnalyseResult);
        });
        //list 按字符串Rate升序排列
        list.sort(Comparator.comparingDouble(o -> Double.parseDouble(o.getRate().replace("%", ""))));
        return list;



    }

    @Override
    public IPage<TBCrmResult> projectDetail(Page<Object> iPage, Long startTime, Long endTime, Long serviceId) {
        return this.baseMapper.crmDetail(iPage, serviceId, startTime, endTime, null);
    }

    @Override
    public Map<String, Object> projectCount(Long startTime, Long endTime) {
        SysUser requestUser = (SysUser) ServletUtil.getRequestUser();
        DataPermissionDto dpr = sysUserService.buildUserDataPermission(requestUser.getId());
        Map<String, Object> map = this.baseMapper.projectCount(startTime, endTime, dpr);
        Integer allocation = this.baseMapper.findAllocation(startTime, endTime, dpr);
        map.put("person",allocation);
        return map;
    }
}
