package com.storlead.trade.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.storlead.trade.dto.MarketingCampaignDTO;
import com.storlead.trade.entity.CustomerAnalysisResultEntity;
import com.storlead.trade.entity.CustomerBaseEntity;
import com.storlead.trade.entity.MarketingCampaignEntity;
import com.storlead.trade.mapper.MarketingCampaignEntityMapper;
import com.storlead.trade.service.CustomerAnalysisResultEntityService;
import com.storlead.trade.service.CustomerBaseEntityService;
import com.storlead.trade.service.MarketingCampaignEntityService;
import com.storlead.trade.vo.MarketingCampaignVO;
import com.storlead.framework.common.constant.CommonConstant;
import com.storlead.framework.common.result.Result;
import com.storlead.framework.mybatis.service.impl.MyBaseServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;


import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class MarketingCampaignEntityServiceImpl
        extends MyBaseServiceImpl<MarketingCampaignEntityMapper, MarketingCampaignEntity>
        implements MarketingCampaignEntityService {

    @Resource
    private CustomerBaseEntityService customerBaseEntityService;
    @Resource
    private CustomerAnalysisResultEntityService customerAnalysisResultEntityService;
    @Override
    public Result<Object> getList(MarketingCampaignDTO marketingCampaignDTO) {
        IPage<MarketingCampaignVO> pageVO = new Page<>(marketingCampaignDTO.getPageIndex(), marketingCampaignDTO.getPageSize());
        IPage<MarketingCampaignEntity> page = new Page<>(marketingCampaignDTO.getPageIndex(), marketingCampaignDTO.getPageSize());
        LambdaQueryWrapper<MarketingCampaignEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(MarketingCampaignEntity::getIsDelete, CommonConstant.DEL_FLAG_0);
        IPage<MarketingCampaignEntity> pageList = this.page(page, queryWrapper);
        if (CollectionUtils.isEmpty(pageList.getRecords())){
            return Result.result(pageVO);
        }

        //        List<MarketingCampaignEntity> list = this.list(queryWrapper);
        // 手动转换 page（避免 Java 17 下 Orika 的 InaccessibleObjectException）
        IPage<MarketingCampaignVO> pageVo = new Page<>(page.getCurrent(), page.getSize());
        pageVo.setTotal(pageList.getTotal());
        if (!CollectionUtils.isEmpty(pageList.getRecords())) {
            List<MarketingCampaignVO> voList = new ArrayList<>();
            for (MarketingCampaignEntity entity : pageList.getRecords()) {
                MarketingCampaignVO vo = new MarketingCampaignVO();
                BeanUtils.copyProperties(entity, vo);
                voList.add(vo);
            }
            pageVo.setRecords(voList);
        }
        pageVO = pageVo;

        List<MarketingCampaignVO> marketingCampaignVOList = pageVO.getRecords();

        List<Long> marketingCampaignIdList = marketingCampaignVOList.stream().map(MarketingCampaignVO::getId).collect(Collectors.toList());
        LambdaQueryWrapper<CustomerBaseEntity> customerBaseEntityLambdaQueryWrapper = new LambdaQueryWrapper<>();
        customerBaseEntityLambdaQueryWrapper.in(CustomerBaseEntity::getMarketingCampaignId, marketingCampaignIdList);
        customerBaseEntityLambdaQueryWrapper.eq(CustomerBaseEntity::getIsDelete, CommonConstant.DEL_FLAG_0);
        List<CustomerBaseEntity> customerBaseEntityList = customerBaseEntityService.list(customerBaseEntityLambdaQueryWrapper);
        //获取全部的关联客户id
        List<Long> customerAnalysisIdList = customerBaseEntityList.stream().map(CustomerBaseEntity::getCustomerAnalysisId).collect(Collectors.toList());
        LambdaQueryWrapper<CustomerAnalysisResultEntity> customerAnalysisEntityQueryWrapper = new LambdaQueryWrapper<>();
        customerAnalysisEntityQueryWrapper.eq(CustomerAnalysisResultEntity::getIsDelete, CommonConstant.DEL_FLAG_0);
        customerAnalysisEntityQueryWrapper.in(!CollectionUtils.isEmpty(customerAnalysisIdList),CustomerAnalysisResultEntity::getId, customerAnalysisIdList);
        List<CustomerAnalysisResultEntity> customerAnalysisResultEntityList = customerAnalysisResultEntityService.list(customerAnalysisEntityQueryWrapper);
        //将customerAnalysisResultEntityList按照customerBaseEntityList对应的id写入pageVO的customerList中

        for (int i = 0; i < marketingCampaignVOList.size(); i++) {
            int finalI = i;
            List<CustomerBaseEntity> customerBaseList = customerBaseEntityList.stream().filter(customerBaseEntity -> customerBaseEntity.getCustomerAnalysisId().equals(customerAnalysisResultEntityList.get(finalI).getId())).collect(Collectors.toList());
            List<Long> customerAnalysisResultIdList = customerBaseList.stream().filter(e -> e.getMarketingCampaignId().equals(marketingCampaignVOList.get(finalI).getId())).map(CustomerBaseEntity::getCustomerAnalysisId).collect(Collectors.toList());
            List<CustomerAnalysisResultEntity> customerAnalysisResultEntityListI = customerAnalysisResultEntityList.stream().filter(customerAnalysisResultEntity -> customerAnalysisResultIdList.contains(customerAnalysisResultEntity.getId())).collect(Collectors.toList());
            marketingCampaignVOList.get(i).setCustomerList(customerAnalysisResultEntityListI);
        }

        return Result.result(pageVO);
    }

    @Override
    public Result<Object> addMarket(MarketingCampaignDTO marketingCampaignDTO) {
        MarketingCampaignEntity marketingCampaignEntity = new MarketingCampaignEntity();
        BeanUtils.copyProperties(marketingCampaignDTO, marketingCampaignEntity);
        boolean isOk = this.save(marketingCampaignEntity);
        if (!isOk) {

            return Result.error("添加失败");
        }
        //添加关联客户
        List<Long> customerIdList = marketingCampaignDTO.getCustomerAnalysisIdList();
        if (!CollectionUtils.isEmpty(customerIdList)) {
            List<CustomerBaseEntity> customerBaseEntityList = new ArrayList<>();
            for (Long customerId : customerIdList) {
                CustomerBaseEntity customerBaseEntity = new CustomerBaseEntity();
                customerBaseEntity.setCustomerAnalysisId(customerId);
                customerBaseEntity.setMarketingCampaignId(marketingCampaignEntity.getId());
                customerBaseEntityList.add(customerBaseEntity);
            }
            boolean saveOk =customerBaseEntityService.saveBatch(customerBaseEntityList);
            if (!saveOk){
                return Result.error("添加失败");
            }
        }
        return Result.ok();
    }

    @Override
    public Result<Object> editMarket(MarketingCampaignDTO marketingCampaignDTO) {
        MarketingCampaignEntity marketingCampaignEntity = new MarketingCampaignEntity();
        BeanUtils.copyProperties(marketingCampaignDTO, marketingCampaignEntity);
        boolean isOk = this.updateById(marketingCampaignEntity);
        if (!isOk) {
            return Result.error("修改失败");
        }
        //添加关联客户
        List<Long> customerIdList = marketingCampaignDTO.getCustomerAnalysisIdList();
        LambdaUpdateWrapper<CustomerBaseEntity> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(CustomerBaseEntity::getMarketingCampaignId, marketingCampaignEntity.getId());
        customerBaseEntityService.remove(updateWrapper);
        if (!CollectionUtils.isEmpty(customerIdList)) {
            List<CustomerBaseEntity> customerBaseEntityList = new ArrayList<>();
            for (Long customerId : customerIdList) {
                CustomerBaseEntity customerBaseEntity = new CustomerBaseEntity();
                customerBaseEntity.setCustomerAnalysisId(customerId);
                customerBaseEntity.setMarketingCampaignId(marketingCampaignEntity.getId());
                customerBaseEntityList.add(customerBaseEntity);
            }
            boolean saveOk =customerBaseEntityService.saveBatch(customerBaseEntityList);
            if (!saveOk){
                return Result.error("修改失败");
            }
        }
        return Result.ok();
    }
}
