package com.usky.iot.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.usky.common.core.bean.CommonPage;
import com.usky.common.core.exception.BusinessException;
import com.usky.common.security.utils.SecurityUtils;
import com.usky.iot.domain.CrmCustomInfo;
import com.usky.iot.mapper.CrmCustomInfoMapper;
import com.usky.iot.service.CrmCustomInfoService;
import com.usky.common.mybatis.core.AbstractCrudService;
import com.usky.iot.service.vo.CrmCustomInfoExportVO;
import com.usky.iot.service.vo.CrmCustomInfoRequestVO;
import com.usky.iot.service.vo.CrmCustomInfoStatisticVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * <p>
 * 客户管理信息表 服务实现类
 * </p>
 *
 * @author han
 * @since 2023-06-26
 */
@Slf4j
@Service
public class CrmCustomInfoServiceImpl extends AbstractCrudService<CrmCustomInfoMapper, CrmCustomInfo> implements CrmCustomInfoService {

    @Override
    public void add(CrmCustomInfo crmCustomInfo){
        if(checkNameUnique(crmCustomInfo)){
            throw new BusinessException("新增客户管理失败，项目名称"+crmCustomInfo.getProjectName()+"已经存在");
        }

        if(crmCustomInfo.getExpireTime().compareTo(LocalDateTime.now())<0){
            crmCustomInfo.setMaintainStatus(2);
        }else{
            crmCustomInfo.setMaintainStatus(1);
        }
        crmCustomInfo.setCreateBy(SecurityUtils.getUsername());
        crmCustomInfo.setCreateTime(LocalDateTime.now());
        crmCustomInfo.setTenantId(SecurityUtils.getTenantId());
        this.save(crmCustomInfo);

    }

    @Override
    public void edit(CrmCustomInfo crmCustomInfo){
        if(checkNameUnique(crmCustomInfo)){
            throw new BusinessException("修改客户管理信息失败，项目名称"+crmCustomInfo.getProjectName()+"已经存在");
        }
        if(crmCustomInfo.getExpireTime().compareTo(LocalDateTime.now())<0){
            crmCustomInfo.setMaintainStatus(2);
        }else{
            crmCustomInfo.setMaintainStatus(1);
        }
        crmCustomInfo.setUpdateBy(SecurityUtils.getUsername());
        crmCustomInfo.setUpdateTime(LocalDateTime.now());
        this.updateById(crmCustomInfo);
    }

    @Override
    public void remove(Integer id){
        CrmCustomInfo crmCustomInfo = this.getById(id);
        Optional.ofNullable(crmCustomInfo).orElseThrow(()->new BusinessException("客户管理信息不存在"));
        crmCustomInfo.setDeleteFlag(1);
        this.updateById(crmCustomInfo);
    }

    @Override
    public CommonPage<CrmCustomInfo> page(CrmCustomInfoRequestVO cus){
        IPage<CrmCustomInfo> page = new Page<>(cus.getCurrent(),cus.getSize());
        LambdaQueryWrapper<CrmCustomInfo> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.like(StringUtils.isNotBlank(cus.getProjectName()),CrmCustomInfo::getProjectName,cus.getProjectName())
                .like(StringUtils.isNotBlank(cus.getCompanyName()),CrmCustomInfo::getCompanyName,cus.getCompanyName())
                .eq(cus.getMaintainStatus() != null,CrmCustomInfo::getMaintainStatus,cus.getMaintainStatus())
                .between(StringUtils.isNotBlank(cus.getStartTime())&&StringUtils.isNotBlank(cus.getEndTime()),CrmCustomInfo::getExpireTime,cus.getStartTime(),cus.getEndTime())
                .eq(CrmCustomInfo::getDeleteFlag,0)
                .eq(CrmCustomInfo::getTenantId,SecurityUtils.getTenantId())
                .orderByDesc(CrmCustomInfo::getId);
        page = this.page(page,queryWrapper);

        return new CommonPage<>(page.getRecords(),page.getTotal(),cus.getSize(),cus.getCurrent());

    }

    @Override
    public List<CrmCustomInfoStatisticVO> statistic(CrmCustomInfoRequestVO cus){
        List<CrmCustomInfoStatisticVO> list = new ArrayList<>();
        QueryWrapper<CrmCustomInfo> queryWrapper = Wrappers.query();
        queryWrapper.select("SUM(maintain_amount) as maintainAmount","COUNT(*) as maintainNum","SUM(maintain_status=1) as maintainUsingNum","SUM(maintain_status=2) as maintainExpireNum")
                .between("expire_time",cus.getStartTime(),cus.getEndTime())
                .eq("delete_flag",0)
                .eq("tenant_id",SecurityUtils.getTenantId());
        List<Map<String,Object>> maps = this.listMaps(queryWrapper);
        if(maps.size() > 0){
            for (int i = 0; i < maps.size(); i++) {
                CrmCustomInfoStatisticVO statisticVO = new CrmCustomInfoStatisticVO();
                if(Objects.nonNull(maps.get(i).get("maintainAmount"))){
                    statisticVO.setMaintainAmount(Double.parseDouble(maps.get(i).get("maintainAmount").toString()));
                }else{
                    statisticVO.setMaintainAmount(Double.parseDouble("0"));
                }

                statisticVO.setMaintainNum(Integer.parseInt(maps.get(i).get("maintainNum").toString()));

                if(Objects.nonNull(maps.get(i).get("maintainUsingNum"))){
                    statisticVO.setMaintainUsingNum(Integer.parseInt(maps.get(i).get("maintainUsingNum").toString()));
                }else{
                    statisticVO.setMaintainUsingNum(0);
                }
                if(Objects.nonNull(maps.get(i).get("maintainExpireNum"))){
                    statisticVO.setMaintainExpireNum(Integer.parseInt(maps.get(i).get("maintainExpireNum").toString()));
                }else{
                    statisticVO.setMaintainExpireNum(0);
                }
                list.add(statisticVO);
            }
        }

        return list;
    }

    @Override
    public List<CrmCustomInfoExportVO> recordListExport(CrmCustomInfoRequestVO cus){
        List<CrmCustomInfoExportVO> list = new ArrayList<>();
        LambdaQueryWrapper<CrmCustomInfo> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.like(StringUtils.isNotBlank(cus.getProjectName()),CrmCustomInfo::getProjectName,cus.getProjectName())
                .like(StringUtils.isNotBlank(cus.getCompanyName()),CrmCustomInfo::getCompanyName,cus.getCompanyName())
                .eq(cus.getMaintainStatus() != null,CrmCustomInfo::getMaintainStatus,cus.getMaintainStatus())
                .between(StringUtils.isNotBlank(cus.getStartTime())&&StringUtils.isNotBlank(cus.getEndTime()),CrmCustomInfo::getExpireTime,cus.getStartTime(),cus.getEndTime())
                .eq(CrmCustomInfo::getDeleteFlag,0)
                .eq(CrmCustomInfo::getTenantId,SecurityUtils.getTenantId())
                .orderByDesc(CrmCustomInfo::getId);
        List<CrmCustomInfo> list1 = this.list(queryWrapper);
        if(CollectionUtils.isNotEmpty(list1)){
            for(int i=0;i<list1.size();i++){
                CrmCustomInfoExportVO exportVO = new CrmCustomInfoExportVO();
                exportVO.setProjectId(list1.get(i).getProjectId());
                exportVO.setProjectName(list1.get(i).getProjectName());
                exportVO.setCompanyName(list1.get(i).getCompanyName());
                exportVO.setCustomPerson(list1.get(i).getCustomPerson());
                exportVO.setPhone(list1.get(i).getPhone());
                exportVO.setMaintainAmount(list1.get(i).getMaintainAmount());
                exportVO.setEmail(list1.get(i).getEmail());
                exportVO.setSalePerson(list1.get(i).getSalePerson());
                exportVO.setMaintainStatus(list1.get(i).getMaintainStatus());
                exportVO.setExpireTime(list1.get(i).getExpireTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
                exportVO.setCustomAddress(list1.get(i).getCustomAddress());

                list.add(exportVO);
            }
        }
        return list;
    }

    @Override
    public boolean checkNameUnique(CrmCustomInfo crmCustomInfo){
        Integer id = null == crmCustomInfo.getId()?-1:crmCustomInfo.getId();
        LambdaQueryWrapper<CrmCustomInfo> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(CrmCustomInfo::getProjectName,crmCustomInfo.getProjectName())
                    .eq(CrmCustomInfo::getDeleteFlag,0)
                .eq(CrmCustomInfo::getTenantId,SecurityUtils.getTenantId());
        CrmCustomInfo one = this.getOne(queryWrapper);
        return null != one && !Objects.equals(one.getId(),id);

    }

    @Override
    public void updateStatus(){
        log.info("同步客户信息状态 start");
        LambdaQueryWrapper<CrmCustomInfo> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(CrmCustomInfo::getDeleteFlag,0);
        List<CrmCustomInfo> list = this.list(queryWrapper);
        if(CollectionUtils.isNotEmpty(list)){
            for(int i=0;i<list.size();i++){
                CrmCustomInfo info = list.get(i);
                if(list.get(i).getExpireTime().compareTo(LocalDateTime.now())<0){
                    if(info.getMaintainStatus()!=2){
                        info.setMaintainStatus(2);
                        this.updateById(info);
                    }
                }else{
                    if(info.getMaintainStatus()!=1){
                        info.setMaintainStatus(1);
                        this.updateById(info);
                    }
                }
            }
        }
        log.info("同步客户信息状态 end");

    }

}
