package cn.iocoder.yudao.module.crm.service.crmanalysis;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.NumberUtil;
import cn.iocoder.yudao.framework.common.enums.ShopCommonEnum;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.module.crm.controller.admin.crmanalysis.vo.AchievementPageReqVO;
import cn.iocoder.yudao.module.crm.controller.admin.crmanalysis.vo.CustomerLevelVO;
import cn.iocoder.yudao.module.crm.controller.admin.crmanalysis.vo.UserRecordVO;
import cn.iocoder.yudao.module.crm.controller.admin.crmanalysis.vo.UserVolumeVO;
import cn.iocoder.yudao.module.crm.controller.admin.crmcustomer.vo.CustomerStatisticRespVO;
import cn.iocoder.yudao.module.crm.controller.admin.crmrecord.vo.RecordStatisticsRespVO;
import cn.iocoder.yudao.module.crm.controller.admin.userlivetree.vo.UserLiveTreeListVO;
import cn.iocoder.yudao.module.crm.controller.admin.userlivetree.vo.UserLiveTreePageReqVO;
import cn.iocoder.yudao.module.crm.dal.dataobject.crmcustomer.CrmCustomerDO;
import cn.iocoder.yudao.module.crm.dal.mysql.crmcustomer.CrmCustomerMapper;
import cn.iocoder.yudao.module.crm.service.crmrecord.CrmRecordService;
import cn.iocoder.yudao.module.crm.service.userlivetree.UserLiveTreeService;
import cn.iocoder.yudao.module.system.api.dict.DictDataApi;
import cn.iocoder.yudao.module.system.api.dict.dto.DictDataRespDTO;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertList;
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertMap;

/**
 * 客户分析 Service 实现类
 *
 * @author yshop
 */
@Service
@Validated
public class CustomerServiceImpl implements CustomerService {

    @Resource
    private DictDataApi dictDataApi;

    @Resource
    private CrmCustomerMapper customerMapper;

    @Resource
    private CrmRecordService recordService;

    @Resource
    private UserLiveTreeService userLiveTreeService;

    @Override
    public CustomerLevelVO getCustomerLevel() {
        List<DictDataRespDTO> list = dictDataApi.getDictDataList("customer_level").getCheckedData();
        List<Long> allCustomer = new ArrayList<>();
        List<Long> dealCustomer = new ArrayList<>();

        list.forEach(v -> {
            LambdaQueryWrapper<CrmCustomerDO> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(CrmCustomerDO::getLevel, v.getValue());
            Long all = customerMapper.selectCount(wrapper);
            wrapper.eq(CrmCustomerDO::getDealStatus, ShopCommonEnum.IS_STATUS_1.getValue());
            Long deal = customerMapper.selectCount(wrapper);
            allCustomer.add(all);
            dealCustomer.add(deal);
        });
        List<String> data = list.stream().map(DictDataRespDTO::getLabel).collect(Collectors.toList());

        return CustomerLevelVO.builder().data(data).allCustomer(allCustomer).dealCustomer(dealCustomer).build();
    }

    @Override
    public CustomerLevelVO getCustomerSource() {
        List<DictDataRespDTO> list = dictDataApi.getDictDataList("customer_source").getCheckedData();

        List<Long> allCustomer = new ArrayList<>();
        List<Long> dealCustomer = new ArrayList<>();

        list.forEach(v -> {
            LambdaQueryWrapper<CrmCustomerDO> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(CrmCustomerDO::getSource, v.getValue());
            Long all = customerMapper.selectCount(wrapper);
            wrapper.eq(CrmCustomerDO::getDealStatus, ShopCommonEnum.IS_STATUS_1.getValue());
            Long deal = customerMapper.selectCount(wrapper);
            allCustomer.add(all);
            dealCustomer.add(deal);
        });
        List<String> data = list.stream().map(DictDataRespDTO::getLabel).collect(Collectors.toList());

        return CustomerLevelVO.builder().data(data).allCustomer(allCustomer).dealCustomer(dealCustomer).build();
    }


    @Override
    public CustomerLevelVO getCustomerIndustry() {
        List<DictDataRespDTO> list = dictDataApi.getDictDataList("customer_industry").getCheckedData();
        List<Long> allCustomer = new ArrayList<>();
        List<Long> dealCustomer = new ArrayList<>();

        list.forEach(v -> {
            LambdaQueryWrapper<CrmCustomerDO> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(CrmCustomerDO::getIndustry, v.getValue());
            Long all = customerMapper.selectCount(wrapper);
            wrapper.eq(CrmCustomerDO::getDealStatus, ShopCommonEnum.IS_STATUS_1.getValue());
            Long deal = customerMapper.selectCount(wrapper);
            allCustomer.add(all);
            dealCustomer.add(deal);
        });
        List<String> data = list.stream().map(DictDataRespDTO::getLabel).collect(Collectors.toList());

        return CustomerLevelVO.builder().data(data).allCustomer(allCustomer).dealCustomer(dealCustomer).build();
    }

    @Override
    public PageResult<UserVolumeVO> getCustomerVolume(AchievementPageReqVO pageReqVO) {

        // 获取销售角色 分页列表
        PageResult<UserLiveTreeListVO> pageResult = userLiveTreeService.getUserLiveTreePage(new UserLiveTreePageReqVO());
        List<UserVolumeVO> volumeVOS = pageResult.getList().stream()
                .map(v -> new UserVolumeVO()
                        .setId(v.getUserId())
                        .setNickname(v.getNickname()))
                .collect(Collectors.toList());

        PageResult<UserVolumeVO> pageResult1 = new PageResult<>(volumeVOS, pageResult.getTotal());
        if (CollectionUtil.isNotEmpty(pageResult1.getList())) {

            List<Long> userIds = convertList(pageResult1.getList(), UserVolumeVO::getId);
            // 获取所有用户的客户统计列表
            List<CustomerStatisticRespVO> statisticRespVOS = this.getCustomerStatistic(userIds, pageReqVO.getCreateTime());
            Map<Long, CustomerStatisticRespVO> customerMap = convertMap(statisticRespVOS, CustomerStatisticRespVO::getOwnerUserId);

            pageResult1.getList().forEach(v -> {

                String per = "0.00";
                if (customerMap.get(v.getId()) == null) {
                    v.setCustomerCount(0L);
                    v.setSuccessCount(0L);
                    v.setSuccessPer(per);
                } else {
                    v.setCustomerCount(Long.valueOf(customerMap.get(v.getId()).getCount()));
                    v.setSuccessCount(Long.valueOf(customerMap.get(v.getId()).getDealsCount()));

                    if (v.getCustomerCount() > 0) {
                        per = NumberUtil.round(NumberUtil.div(v.getSuccessCount(), v.getCustomerCount()), 2)
                                .multiply(new BigDecimal("100")).toString();
                    }
                    v.setSuccessPer(per);
                }
            });
        }

        return pageResult1;
    }

    @Override
    public PageResult<UserRecordVO> getRecord(AchievementPageReqVO pageReqVO) {

        // 获取销售角色 分页列表
        PageResult<UserLiveTreeListVO> pageResult = userLiveTreeService.getUserLiveTreePage(new UserLiveTreePageReqVO());
        List<UserRecordVO> recordVOS = pageResult.getList().stream()
                .map(v -> new UserRecordVO()
                        .setId(v.getUserId())
                        .setNickname(v.getNickname()))
                .collect(Collectors.toList());
        PageResult<UserRecordVO> pageResult1 = new PageResult<>(recordVOS, pageResult.getTotal());

        if (CollectionUtil.isNotEmpty(pageResult1.getList())) {
            // 获取所有用户跟进统计列表
            List<Long> userIds = convertList(pageResult1.getList(), UserRecordVO::getId);
            List<RecordStatisticsRespVO> respVOS = recordService.getRecordStatistics(userIds, pageReqVO.getCreateTime());
            Map<String, RecordStatisticsRespVO> recordMap = convertMap(respVOS, RecordStatisticsRespVO::getCreator);
            pageResult1.getList().forEach(v -> {
                RecordStatisticsRespVO respVO = recordMap.get(v.getId().toString());
                if (respVO == null) {
                    // 设置跟进总数量
                    v.setTotalCount(0L);
                    // 设置跟进客户数量
                    v.setCustomerCount(0L);
                    // 设置跟进商机数量
                    v.setBusinessCount(0L);
                    // 设置跟进线索数量
                    v.setCluesCount(0L);
                } else {
                    // 设置跟进总数量
                    v.setTotalCount(Long.valueOf(respVO.getCount()));
                    // 设置跟进客户数量
                    v.setCustomerCount(Long.valueOf(respVO.getCustomerCount()));
                    // 设置跟进商机数量
                    v.setBusinessCount(Long.valueOf(respVO.getBusinessCount()));
                    // 设置跟进线索数量
                    v.setCluesCount(Long.valueOf(respVO.getCluesCount()));
                }
            });
        }
        return pageResult1;
    }

    @Override
    public List<CustomerStatisticRespVO> getCustomerStatistic(List<Long> userIds, LocalDateTime[] createTime) {

        return customerMapper.selectStatistic(userIds, createTime);
    }
}
