package com.xhpc.activity.service.impl;

import com.xhpc.activity.domain.XhpcActivityDiscountDomain;
import com.xhpc.activity.domain.XhpcActivityTemplateDomain;
import com.xhpc.activity.mapper.XhpcActivityDiscountMapper;
import com.xhpc.activity.mapper.XhpcActivityTemplateMapper;
import com.xhpc.activity.service.XhpcActivityTemplateService;
import com.xhpc.common.core.exception.CustomException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;


@Service
@Transactional
public class XhpcActivityTemplateServiceImpl implements XhpcActivityTemplateService {

    @Resource
    XhpcActivityTemplateMapper templateMapper;


    @Resource
    XhpcActivityDiscountMapper discountMapper;


    @Override
    public List<XhpcActivityTemplateDomain> getPage(Map<String, Object> params){
        return templateMapper.selectByParams(params);
    }


    @Override
    public List<Map<String, Object>> getNameList(Map<String, Object> params){
        return templateMapper.selectNameMapList(params);
    }


    @Override
    public XhpcActivityTemplateDomain getDomainByPk(Integer templateId) {
        return templateMapper.selectByPrimaryKey(templateId);
    }


    @Override
    public boolean insertDomain(XhpcActivityTemplateDomain domain){
        return templateMapper.insert(domain) > 0;
    }


    @Override
    public boolean updateDomain(XhpcActivityTemplateDomain domain){
        return templateMapper.updateByPrimaryKey(domain) > 0;
    }


    @Override
    public boolean updateDomainStatus(XhpcActivityTemplateDomain domain){
        if(domain.getStatus() == 2){
            List<XhpcActivityDiscountDomain> domainList = discountMapper.selectByTemplateIdAndStatus(domain.getActivityTemplateId(), 3);
            if(domainList.size() > 0){
                throw new CustomException("存在生效的折扣活动，请先失效使用该模版的折扣活动");
            }
            discountMapper.updateByTemplateIdAndUncheck(domain.getActivityTemplateId());
        }

        return templateMapper.updateStatusByPrimaryKey(domain) > 0;
    }

    @Override
    public boolean deleteByPk(Integer templateId){
        List<XhpcActivityDiscountDomain> domainList = discountMapper.selectByTemplateIdAndDelflag(templateId, 0);
        if(domainList.size() > 0){
            throw new CustomException("存在尚未删除的折扣活动，请先删除使用该模版的折扣活动");
        }

        return templateMapper.deleteLogicByPrimaryKey(templateId) > 0;
    }
}
