package com.zt.plat.module.base.service.base;

import cn.hutool.core.collection.CollUtil;
import com.zt.plat.framework.common.pojo.PageResult;
import com.zt.plat.framework.common.util.object.BeanUtils;
import com.zt.plat.module.base.controller.admin.base.vo.TaxPageReqVO;
import com.zt.plat.module.base.controller.admin.base.vo.TaxRespVO;
import com.zt.plat.module.base.controller.admin.base.vo.TaxSaveReqVO;
import com.zt.plat.module.base.controller.admin.base.vo.TaxStsVO;
import com.zt.plat.module.base.dal.dataobject.base.TaxDO;
import com.zt.plat.module.base.dal.mysql.base.TaxMapper;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import java.util.List;

import static com.zt.plat.framework.common.exception.util.ServiceExceptionUtil.exception;
import static com.zt.plat.module.base.enums.ErrorCodeConstants.TAX_NOT_EXISTS;

/**
 * 税码信息 Service 实现类
 *
 * @author 后台管理-1
 */
@Service
@Validated
public class TaxServiceImpl implements TaxService {

    @Resource
    private TaxMapper taxMapper;

    @Override
    public TaxRespVO createTax(TaxSaveReqVO createReqVO) {
        // 插入
        TaxDO tax = BeanUtils.toBean(createReqVO, TaxDO.class);
        taxMapper.insert(tax);
        // 返回
        return BeanUtils.toBean(tax, TaxRespVO.class);
    }

    @Override
    public void updateTax(TaxSaveReqVO updateReqVO) {
        // 校验存在
        validateTaxExists(updateReqVO.getId());
        // 更新
        TaxDO updateObj = BeanUtils.toBean(updateReqVO, TaxDO.class);
        taxMapper.updateById(updateObj);
    }

    @Override
    public void deleteTax(Long id) {
        // 校验存在
        validateTaxExists(id);
        // 删除
        taxMapper.deleteById(id);
    }

    @Override
        public void deleteTaxListByIds(List<Long> ids) {
        // 校验存在
        validateTaxExists(ids);
        // 删除
        taxMapper.deleteByIds(ids);
        }

    private void validateTaxExists(List<Long> ids) {
        List<TaxDO> list = taxMapper.selectByIds(ids);
        if (CollUtil.isEmpty(list) || list.size() != ids.size()) {
            throw exception(TAX_NOT_EXISTS);
        }
    }

    private void validateTaxExists(Long id) {
        if (taxMapper.selectById(id) == null) {
            throw exception(TAX_NOT_EXISTS);
        }
    }

    @Override
    public TaxDO getTax(Long id) {
        return taxMapper.selectById(id);
    }

    @Override
    public PageResult<TaxDO> getTaxPage(TaxPageReqVO pageReqVO) {
        return taxMapper.selectPage(pageReqVO);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void enableTaxList(List<TaxStsVO> req) {
        req.forEach(item -> {
            TaxDO tax = new TaxDO();
            tax.setId(Long.valueOf(item.getId()));
            tax.setIsEnable(item.getIsEnable());
            taxMapper.updateById(tax);
        });
    }

}