package cn.cslg.pas.service.impl;

import cn.cslg.pas.common.JsonPage;
import cn.cslg.pas.common.model.PersonnelVO;
import cn.cslg.pas.common.model.dto.ProductMarketDataAddNewDTO;
import cn.cslg.pas.common.model.dto.ProductMarketDataDTO;
import cn.cslg.pas.common.model.dto.ProductMarketDataQueryPageDTO;
import cn.cslg.pas.common.model.dto.ProductMarketDataUpdateDTO;
import cn.cslg.pas.common.model.vo.ProductMarketDataTrendVO;
import cn.cslg.pas.common.model.vo.ProductMarketDataVO;
import cn.cslg.pas.common.utils.CacheUtils;
import cn.cslg.pas.common.utils.SecurityUtils.LoginUtils;
import cn.cslg.pas.domain.ProductMarketData;
import cn.cslg.pas.exception.XiaoShiException;
import cn.cslg.pas.mapper.ProductMapper;
import cn.cslg.pas.mapper.ProductMarketDataMapper;
import cn.cslg.pas.service.IProductMarketDataService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;


import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 产品营销数据的Service层接口实现类
 *
 * @Author chenyu
 * @Date 2023/3/9
 */
@RequiredArgsConstructor
@Slf4j
@Service
public class ProductMarketDataServiceImpl extends ServiceImpl<ProductMarketDataMapper, ProductMarketData> implements IProductMarketDataService {
    private final ProductMarketDataMapper productMarketDataMapper;
    private final ProductMapper productMapper;
    private final CacheUtils cacheUtils;
    private final LoginUtils loginUtils;

    /**
     * 新增产品营销数据
     *
     * @param productMarketDataAddNewDTO 产品营销数据DTO对象
     */
    @Override
    public void addNew(ProductMarketDataAddNewDTO productMarketDataAddNewDTO) {
        log.info("开始处理【新增产品营销数据】的业务，参数为：{}", productMarketDataAddNewDTO);

        //检查该产品在该地区的该月份是否已有营销数据
        Integer productId = productMarketDataAddNewDTO.getProductId();
        String saleArea = productMarketDataAddNewDTO.getSaleArea();
        String saleTime = productMarketDataAddNewDTO.getSaleTime();

        log.info("检查该产品在该地区的该月份是否已有营销数据");
        int count = productMarketDataMapper.countByProductIdSaleAreaSaleTime(productId, saleArea, saleTime);
        if (count > 0) {
            String message = "新增产品营销数据失败，该产品在该地区的该月份已有营销数据!";
            log.info("{}", message);
            throw new XiaoShiException(message);
        }

        //新增产品营销数据的DTO对象赋值给实体类
        ProductMarketData productMarketData = new ProductMarketData();
        BeanUtils.copyProperties(productMarketDataAddNewDTO, productMarketData);

        //获取当前登录人信息
        PersonnelVO personnelVO = cacheUtils.getLoginUser(loginUtils.getId());
        productMarketData
                .setCreatePersonId(personnelVO.getId())
                .setCreatePersonName(personnelVO.getName());

        //数据入产品营销数据表
        log.info("数据入产品营销数据表");
        int rows = productMarketDataMapper.insert(productMarketData);
        if (rows != 1) {
            String message = "新增产品营销数据失败，服务器忙请稍后再次尝试!";
            log.info("{}", message);
            throw new XiaoShiException(message);
        }

        log.info("新增产品营销数据完成");

    }

    /**
     * 修改产品营销数据
     *
     * @param productMarketDataUpdateDTO 产品营销数据DTO对象
     */
    @Override
    public void update(ProductMarketDataUpdateDTO productMarketDataUpdateDTO) {
        log.info("开始处理【修改产品营销数据】的业务，参数为：{}", productMarketDataUpdateDTO);

        Integer id = productMarketDataUpdateDTO.getId();
        Integer productId = productMarketDataUpdateDTO.getProductId();
        String saleArea = productMarketDataUpdateDTO.getSaleArea();
        String saleTime = productMarketDataUpdateDTO.getSaleTime();

        //检查尝试修改的数据是否存在
        log.info("检查尝试修改的数据是否存在");
        int count = productMarketDataMapper.countById(id);
        if (count == 0) {
            String message = "修改产品营销数据失败，尝试访问的数据已不存在";
            log.info("{}", message);
            throw new XiaoShiException(message);
        }

        //DTO对象赋值给实体类
        ProductMarketData productMarketData = new ProductMarketData();
        BeanUtils.copyProperties(productMarketDataUpdateDTO, productMarketData);

        //产品营销数据表修改数据
        log.info("产品营销数据表修改数据");
        int rows = productMarketDataMapper.update(productMarketData);
        if (rows != 1) {
            String message = "修改产品营销数据失败，服务器忙请稍后再次尝试!";
            log.info("{}", message);
            throw new XiaoShiException(message);
        }

        log.info("修改产品营销数据完成");

    }

    /**
     * 分页查询产品营销数据
     *
     * @param productMarketDataQueryPageDTO 分页信息
     * @return 返回查询到的数据
     */
    @Override
    public JsonPage query(ProductMarketDataQueryPageDTO productMarketDataQueryPageDTO) {
        log.info("开始处理【分页查询产品营销数据】的业务，参数为：{}", productMarketDataQueryPageDTO);
        String orderBy = productMarketDataQueryPageDTO.getOrderBy();
        if (orderBy != null) {
            String regex = "[A-Z]+";
            Pattern pattern = Pattern.compile(regex);
            Matcher matcher = pattern.matcher(orderBy);
            while (matcher.find()) {
                orderBy = orderBy.replaceFirst(matcher.group(), "_" + matcher.group().toLowerCase());
            }
            productMarketDataQueryPageDTO.setOrderBy(orderBy);
        }
        Integer current = productMarketDataQueryPageDTO.getCurrent();
        Integer size = productMarketDataQueryPageDTO.getSize();
        if (current != null && size != null) {
            PageHelper.startPage(current, size);
        }
        List<ProductMarketDataVO> queryResults = productMarketDataMapper.query(productMarketDataQueryPageDTO);
        return JsonPage.restPage(new PageInfo<>(queryResults));
    }

    /**
     * 删除产品营销数据
     *
     * @param id 产品营销数据id
     */
    @Override
    public void delete(Integer id) {
        log.info("开始处理【删除产品营销数据】的业务，参数为：{}", id);

        //检查尝试删除的数据是否存在
        log.info("检查尝试删除的数据是否存在");
        int count = productMarketDataMapper.countById(id);
        if (count == 0) {
            String message = "删除产品营销数据失败，尝试访问的数据已不存在";
            log.info("{}", message);
            throw new XiaoShiException(message);
        }

        //产品营销数据表删除数据
        log.info("产品营销数据表删除数据");
        int rows = productMarketDataMapper.deleteById(id);
        if (rows != 1) {
            String message = "删除产品营销数据失败，服务器忙请稍后再次尝试!";
            log.info("{}", message);
            throw new XiaoShiException(message);
        }

        log.info("删除产品营销数据完成");

    }

    /**
     * 根据productId查询productName
     * @param productId
     */
    @Override
    public String queryNameByProductId(Integer productId){
        int id = productId;
        String ProductName = productMapper.queryNameById(id);
        return ProductName;
    }

    /**
     * 查询产品趋势图
     *
     * @param dto
     * @return
     */
    @Override
    public List<ProductMarketDataTrendVO> showTrend(ProductMarketDataDTO dto) {
        if(dto.getTimeUnit() == 2){//按照年份返回营销数据
            List<ProductMarketDataTrendVO> list= productMarketDataMapper.queryByYear(dto.getProductId(), dto.getSaleArea());
            return list;
        }else if(dto.getTimeUnit() == 1 ){//按照季度返回营销数据
            List<ProductMarketDataTrendVO> list= productMarketDataMapper.queryBySeason(dto.getProductId(), dto.getSaleArea());
            return list;
        }else if(dto.getTimeUnit() == null||dto.getTimeUnit() == 0 ){//按照月份返回营销数据
            List<ProductMarketDataTrendVO> list= productMarketDataMapper.queryByMonth(dto.getProductId(), dto.getSaleArea());
            return list;
        }else{
            return null;
        }
    }



}
