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

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

import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import com.yhy.module.core.controller.admin.workbench.vo.progresspayment.ProgressPaymentModeCreateReqVO;
import com.yhy.module.core.controller.admin.workbench.vo.progresspayment.ProgressPaymentModeRespVO;
import com.yhy.module.core.controller.admin.workbench.vo.progresspayment.ProgressPaymentModeUpdateReqVO;
import com.yhy.module.core.dal.dataobject.workbench.ProgressPaymentModeDO;
import com.yhy.module.core.dal.mysql.workbench.ProgressPaymentModeMapper;
import com.yhy.module.core.service.workbench.ProgressPaymentModeService;

import java.util.LinkedList;
import java.util.List;
import javax.annotation.Resource;
import javax.validation.Valid;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

/**
 * 进度款模式 Service 实现类
 *
 * @author yhy
 */
@Service
@Validated
public class ProgressPaymentModeServiceImpl implements ProgressPaymentModeService {

    @Resource
    private ProgressPaymentModeMapper progressPaymentModeMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long createProgressPaymentMode(@Valid ProgressPaymentModeCreateReqVO createReqVO) {
        Long projectId = createReqVO.getProjectId();
        Long targetId = createReqVO.getTargetId();
        String insertPosition = createReqVO.getInsertPosition();
        
        // 查询项目下所有数据（按periodNumber排序）
        List<ProgressPaymentModeDO> list = progressPaymentModeMapper.selectListByProjectId(projectId);
        
        // 创建新记录
        ProgressPaymentModeDO newMode = new ProgressPaymentModeDO();
        newMode.setProjectId(projectId);
        newMode.setName(createReqVO.getName());
        newMode.setStartDate(createReqVO.getStartDate());
        newMode.setEndDate(createReqVO.getEndDate());
        newMode.setTotalCost(createReqVO.getTotalCost());
        newMode.setCurrentPeriodValue(createReqVO.getCurrentPeriodValue());
        newMode.setCompletedValue(createReqVO.getCompletedValue());
        newMode.setCompletedRatio(createReqVO.getCompletedRatio());
        newMode.setPaymentRatio(createReqVO.getPaymentRatio());
        newMode.setPaymentAmount(createReqVO.getPaymentAmount());
        newMode.setMaterialAdjustment(createReqVO.getMaterialAdjustment());
        newMode.setRemark(createReqVO.getRemark());
        
        // 计算插入位置
        int insertIndex;
        if (targetId != null && insertPosition != null) {
            // 指定插入位置：找到目标行的索引
            int targetIndex = -1;
            for (int i = 0; i < list.size(); i++) {
                if (list.get(i).getId().equals(targetId)) {
                    targetIndex = i;
                    break;
                }
            }
            if (targetIndex == -1) {
                throw exception(PROGRESS_PAYMENT_MODE_NOT_EXISTS);
            }
            
            if ("above".equalsIgnoreCase(insertPosition)) {
                insertIndex = targetIndex;
            } else {
                insertIndex = targetIndex + 1;
            }
        } else {
            // 默认：追加到末尾
            insertIndex = list.size();
        }
        
        // 插入新记录到列表
        list.add(insertIndex, newMode);
        
        // 先插入新记录到数据库（获取ID）
        progressPaymentModeMapper.insert(newMode);
        
        // 重新编号整个列表：1, 2, 3...N
        List<ProgressPaymentModeDO> updateList = new LinkedList<>();
        for (int i = 0; i < list.size(); i++) {
            ProgressPaymentModeDO item = list.get(i);
            int newPeriodNumber = i + 1;
            // 只收集periodNumber变化的记录
            if (!Integer.valueOf(newPeriodNumber).equals(item.getPeriodNumber())) {
                item.setPeriodNumber(newPeriodNumber);
                updateList.add(item);
            }
        }
//        // 设置name（如果为空则自动生成）
//        String name = createReqVO.getName();
//        if (name == null || name.trim().isEmpty()) {
//            name = "第" + newMode.getPeriodNumber() + "期";
//        }
//        newMode.setName("第" + newMode.getPeriodNumber() + "期");
        
        // 批量更新（newMode 已在 updateList 中，name 会一起更新）
        if (!updateList.isEmpty()) {
            progressPaymentModeMapper.updateBatch(updateList);
        }
        
        return newMode.getId();
    }

    @Override
    public void updateProgressPaymentMode(@Valid ProgressPaymentModeUpdateReqVO updateReqVO) {
        // 校验存在
        ProgressPaymentModeDO existProgressPaymentMode = progressPaymentModeMapper.selectById(updateReqVO.getId());
        if (existProgressPaymentMode == null) {
            throw exception(PROGRESS_PAYMENT_MODE_NOT_EXISTS);
        }
        
        // 更新进度款模式
        ProgressPaymentModeDO updateObj = new ProgressPaymentModeDO();
        updateObj.setId(updateReqVO.getId());
        updateObj.setName(updateReqVO.getName());
        updateObj.setPeriodNumber(updateReqVO.getPeriodNumber());
        updateObj.setStartDate(updateReqVO.getStartDate());
        updateObj.setEndDate(updateReqVO.getEndDate());
        updateObj.setTotalCost(updateReqVO.getTotalCost());
        updateObj.setCurrentPeriodValue(updateReqVO.getCurrentPeriodValue());
        updateObj.setCompletedValue(updateReqVO.getCompletedValue());
        updateObj.setCompletedRatio(updateReqVO.getCompletedRatio());
        updateObj.setPaymentRatio(updateReqVO.getPaymentRatio());
        updateObj.setPaymentAmount(updateReqVO.getPaymentAmount());
        updateObj.setMaterialAdjustment(updateReqVO.getMaterialAdjustment());
        updateObj.setRemark(updateReqVO.getRemark());
        progressPaymentModeMapper.updateById(updateObj);
    }

    @Override
    public void deleteProgressPaymentMode(Long id) {
        // 校验存在
        ProgressPaymentModeDO existProgressPaymentMode = progressPaymentModeMapper.selectById(id);
        if (existProgressPaymentMode == null) {
            throw exception(PROGRESS_PAYMENT_MODE_NOT_EXISTS);
        }
        
        // 删除进度款模式
        progressPaymentModeMapper.deleteById(id);
    }

    @Override
    public ProgressPaymentModeRespVO getProgressPaymentMode(Long id) {
        ProgressPaymentModeDO progressPaymentMode = progressPaymentModeMapper.selectById(id);
        if (progressPaymentMode == null) {
            return null;
        }
        return convertToRespVO(progressPaymentMode);
    }

    @Override
    public List<ProgressPaymentModeRespVO> getProgressPaymentModeList(Long projectId) {
        List<ProgressPaymentModeDO> list = progressPaymentModeMapper.selectListByProjectId(projectId);
        return convertToRespVOList(list);
    }

    /**
     * 转换为 Response VO
     */
    private ProgressPaymentModeRespVO convertToRespVO(ProgressPaymentModeDO progressPaymentMode) {
        ProgressPaymentModeRespVO respVO = new ProgressPaymentModeRespVO();
        respVO.setId(progressPaymentMode.getId());
        respVO.setProjectId(progressPaymentMode.getProjectId());
        respVO.setName(progressPaymentMode.getName());
        respVO.setPeriodNumber(progressPaymentMode.getPeriodNumber());
        respVO.setStartDate(progressPaymentMode.getStartDate());
        respVO.setEndDate(progressPaymentMode.getEndDate());
        respVO.setTotalCost(progressPaymentMode.getTotalCost());
        respVO.setCurrentPeriodValue(progressPaymentMode.getCurrentPeriodValue());
        respVO.setCompletedValue(progressPaymentMode.getCompletedValue());
        respVO.setCompletedRatio(progressPaymentMode.getCompletedRatio());
        respVO.setPaymentRatio(progressPaymentMode.getPaymentRatio());
        respVO.setPaymentAmount(progressPaymentMode.getPaymentAmount());
        respVO.setMaterialAdjustment(progressPaymentMode.getMaterialAdjustment());
        respVO.setRemark(progressPaymentMode.getRemark());
        respVO.setCreateTime(progressPaymentMode.getCreateTime());
        respVO.setUpdateTime(progressPaymentMode.getUpdateTime());
        return respVO;
    }

    /**
     * 转换为 Response VO 列表
     */
    private List<ProgressPaymentModeRespVO> convertToRespVOList(List<ProgressPaymentModeDO> list) {
        return list.stream().map(this::convertToRespVO).collect(java.util.stream.Collectors.toList());
    }
}
