package com.yhy.module.core.service.infoprice.impl;

import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import com.yhy.module.core.controller.admin.infoprice.vo.InfoPriceResourcePricePageReqVO;
import com.yhy.module.core.controller.admin.infoprice.vo.InfoPriceResourcePriceRespVO;
import com.yhy.module.core.controller.admin.infoprice.vo.InfoPriceResourcePriceSaveReqVO;
import com.yhy.module.core.dal.dataobject.infoprice.InfoPriceResourceDO;
import com.yhy.module.core.dal.dataobject.infoprice.InfoPriceResourcePriceDO;
import com.yhy.module.core.dal.mysql.infoprice.InfoPriceResourceMapper;
import com.yhy.module.core.dal.mysql.infoprice.InfoPriceResourcePriceMapper;
import com.yhy.module.core.service.infoprice.InfoPriceResourcePriceService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.util.List;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static com.yhy.module.core.enums.ErrorCodeConstants.*;

/**
 * 信息价工料机价格历史 Service 实现类
 *
 * @author 芋道源码
 */
@Service
@Validated
@Slf4j
public class InfoPriceResourcePriceServiceImpl implements InfoPriceResourcePriceService {

    @Resource
    private InfoPriceResourcePriceMapper infoPriceResourcePriceMapper;

    @Resource
    private InfoPriceResourceMapper infoPriceResourceMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long createResourcePrice(InfoPriceResourcePriceSaveReqVO createReqVO) {
        // 1. 校验工料机信息存在
        validateResourceExists(createReqVO.getResourceId());

        // 2. 校验时间段有效性
        validateTimeRange(createReqVO.getStartTime(), createReqVO.getEndTime());

        // 3. 校验时间段连续性
        validateTimeContinuity(createReqVO.getResourceId(), createReqVO.getStartTime());

        // 4. 插入
        InfoPriceResourcePriceDO resourcePrice = BeanUtils.toBean(createReqVO, InfoPriceResourcePriceDO.class);
        infoPriceResourcePriceMapper.insert(resourcePrice);
        return resourcePrice.getId();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateResourcePrice(InfoPriceResourcePriceSaveReqVO updateReqVO) {
        // 1. 校验存在
        validateResourcePriceExists(updateReqVO.getId());

        // 2. 校验时间段有效性
        validateTimeRange(updateReqVO.getStartTime(), updateReqVO.getEndTime());

        // 3. 更新
        InfoPriceResourcePriceDO updateObj = BeanUtils.toBean(updateReqVO, InfoPriceResourcePriceDO.class);
        infoPriceResourcePriceMapper.updateById(updateObj);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteResourcePrice(Long id) {
        // 1. 校验存在
        validateResourcePriceExists(id);

        // 2. 删除
        infoPriceResourcePriceMapper.deleteById(id);
    }

    @Override
    public InfoPriceResourcePriceRespVO getResourcePrice(Long id) {
        InfoPriceResourcePriceDO resourcePrice = infoPriceResourcePriceMapper.selectById(id);
        return BeanUtils.toBean(resourcePrice, InfoPriceResourcePriceRespVO.class);
    }

    @Override
    public List<InfoPriceResourcePriceRespVO> getResourcePriceList(Long resourceId) {
        List<InfoPriceResourcePriceDO> list = infoPriceResourcePriceMapper.selectListByResourceId(resourceId);
        return BeanUtils.toBean(list, InfoPriceResourcePriceRespVO.class);
    }

    @Override
    public PageResult<InfoPriceResourcePriceRespVO> getResourcePricePage(InfoPriceResourcePricePageReqVO pageReqVO) {
        PageResult<InfoPriceResourcePriceDO> pageResult = infoPriceResourcePriceMapper.selectPage(pageReqVO);
        return BeanUtils.toBean(pageResult, InfoPriceResourcePriceRespVO.class);
    }

    // ==================== 私有方法 ====================

    private InfoPriceResourcePriceDO validateResourcePriceExists(Long id) {
        InfoPriceResourcePriceDO resourcePrice = infoPriceResourcePriceMapper.selectById(id);
        if (resourcePrice == null) {
            throw exception(INFO_PRICE_RESOURCE_PRICE_NOT_EXISTS);
        }
        return resourcePrice;
    }

    private void validateResourceExists(Long resourceId) {
        InfoPriceResourceDO resource = infoPriceResourceMapper.selectById(resourceId);
        if (resource == null) {
            throw exception(INFO_PRICE_RESOURCE_NOT_EXISTS);
        }
    }

    private void validateTimeRange(LocalDate startTime, LocalDate endTime) {
        if (endTime.isBefore(startTime)) {
            throw exception(INFO_PRICE_RESOURCE_PRICE_TIME_INVALID);
        }
    }

    private void validateTimeContinuity(Long resourceId, LocalDate startTime) {
        // 查询最后一条价格记录
        InfoPriceResourcePriceDO lastPrice = infoPriceResourcePriceMapper.selectLastByResourceId(resourceId);
        
        if (lastPrice != null) {
            // 计算期望的开始时间（前一条结束时间 + 1天）
            LocalDate expectedStartTime = lastPrice.getEndTime().plusDays(1);
            
            // 验证时间连续性
            if (!startTime.equals(expectedStartTime)) {
                throw exception(INFO_PRICE_RESOURCE_PRICE_TIME_NOT_CONTINUOUS,
                        expectedStartTime.toString());
            }
        }
    }

}
