package com.ruoyi.bst.suit.service.impl;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.support.TransactionTemplate;

import com.github.pagehelper.PageHelper;
import com.ruoyi.bst.modelSuit.domain.ModelSuit;
import com.ruoyi.bst.modelSuit.service.ModelSuitService;
import com.ruoyi.bst.suit.domain.Suit;
import com.ruoyi.bst.suit.domain.SuitQuery;
import com.ruoyi.bst.suit.domain.SuitVO;
import com.ruoyi.bst.suit.mapper.SuitMapper;
import com.ruoyi.bst.suit.service.SuitService;
import com.ruoyi.bst.suit.service.SuitValidator;
import com.ruoyi.bst.suit.utils.SuitUtil;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.ServiceUtil;
import com.ruoyi.common.utils.collection.CollectionUtils;

/**
 * 套餐Service业务层处理
 *
 * @author ruoyi
 * @date 2025-03-17
 */
@Service
public class SuitServiceImpl implements SuitService
{
    @Autowired
    private SuitMapper suitMapper;

    @Autowired
    private SuitValidator suitValidator;

    @Autowired
    private TransactionTemplate transactionTemplate;

    @Autowired
    private ModelSuitService modelSuitService;

    /**
     * 查询套餐
     *
     * @param id 套餐主键
     * @return 套餐
     */
    @Override
    public SuitVO selectSuitById(Long id, boolean scope)
    {
        if (id == null) {
            return null;
        }

        SuitQuery query = new SuitQuery();
        query.setId(id);
        query.setScope(scope);
        return this.selectOne(query);
    }

    @Override
    public SuitVO selectOne(SuitQuery query) {
        PageHelper.startPage(1, 1);
        List<SuitVO> list = suitMapper.selectSuitList(query);
        return CollectionUtils.firstElement(list);
    }

    /**
     * 查询套餐列表
     *
     * @param suit 套餐
     * @return 套餐
     */
    @Override
    public List<SuitVO> selectSuitList(SuitQuery suit)
    {
        return suitMapper.selectSuitList(suit);
    }

    /**
     * 新增套餐
     *
     * @param suit 套餐
     * @return 结果
     */
    @Override
    public int insertSuit(SuitVO suit)
    {
        suit.setCreateTime(DateUtils.getNowDate());

        Integer result = transactionTemplate.execute(status -> {
            int rows = suitMapper.insertSuit(suit);
            
            if (rows > 0) {
                // 更新套餐关联
                this.updateSuitModel(suit);

                // 校验数据
                SuitVO vo = selectSuitById(suit.getId());
                suitValidator.validate(vo);

                // 计算并更新可用时长
                this.updateSuitSeconds(vo);
            }

            return rows;
        });

        return result == null ? 0 : result;
    }

    private int updateSuitSeconds(SuitVO vo) {
        if (vo == null) {
            return 0;
        }
        Suit data = new Suit();
        data.setId(vo.getId());
        data.setSeconds(SuitUtil.calcTotalTime(vo));
        return suitMapper.updateSuit(data);
    }

    /**
     * 修改套餐
     *
     * @param suit 套餐
     * @return 结果
     */
    @Override
    public int updateSuit(SuitVO suit)
    {
        Integer result = transactionTemplate.execute(status -> {
            int rows = suitMapper.updateSuit(suit);
            if (rows > 0) {
                // 更新套餐关联
                this.updateSuitModel(suit);

                // 校验数据
                SuitVO vo = selectSuitById(suit.getId());
                suitValidator.validate(vo);

                // 计算并更新可用时长
                this.updateSuitSeconds(vo);
            }

            return rows;
        });

        return result == null ? 0 : result;
    }

    private void updateSuitModel(SuitVO suit) {
        // 删除套餐关联的车型
        modelSuitService.deleteModelSuitBySuitIds(Collections.singletonList(suit.getId()));
        // 新增套餐关联的车型
        if (suit.getModelIds() != null) {
            List<ModelSuit> modelSuitList = new ArrayList<>();
            for (Long modelId : suit.getModelIds()) {
                if (modelId == null) {
                    continue;
                }
                ModelSuit modelSuit = new ModelSuit();
                modelSuit.setSuitId(suit.getId());
                modelSuit.setModelId(modelId);
                modelSuitList.add(modelSuit);
            }
            int insert = modelSuitService.batchInsert(modelSuitList);
            ServiceUtil.assertion(insert != modelSuitList.size(), "新增套餐关联的车型失败");
        }
    }

    /**
     * 批量删除套餐
     *
     * @param ids 需要删除的套餐主键
     * @return 结果
     */
    @Override
    public int deleteSuitByIds(List<Long> ids)
    {
        Integer result = transactionTemplate.execute(status -> {
            int rows = suitMapper.deleteSuitByIds(ids);
            if (rows > 0) {
                // 删除套餐关联的车型
                modelSuitService.deleteModelSuitBySuitIds(ids);
            }
            return rows;
        });

        return result == null ? 0 : result;
    }

}
