package com.yc.ship.module.marketing.service.column;

import cn.hutool.core.util.IdUtil;
import com.yc.ship.framework.common.pojo.PageResult;
import com.yc.ship.framework.common.util.object.BeanUtils;
import com.yc.ship.module.marketing.controller.admin.column.vo.ColumnPageReqVO;
import com.yc.ship.module.marketing.controller.admin.column.vo.ColumnSaveReqVO;
import com.yc.ship.module.marketing.dal.dataobject.column.ColumnDO;
import com.yc.ship.module.marketing.dal.mysql.column.ColumnMapper;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;

import static com.yc.ship.framework.common.exception.util.ServiceExceptionUtil.exception;
import static com.yc.ship.module.marketing.enums.ErrorCodeConstants.COLUMN_NOT_EXISTS;

/**
 * 小程序-栏目管理 Service 实现类
 *
 * @author lfy
 */
@Service
@Validated
public class ColumnServiceImpl implements ColumnService {

    @Resource
    private ColumnMapper columnMapper;

    @Override
    public String createColumn(ColumnSaveReqVO createReqVO) {
        // 插入
        ColumnDO column = BeanUtils.toBean(createReqVO, ColumnDO.class);
        column.setId(IdUtil.getSnowflakeNextIdStr());
        columnMapper.insert(column);
        // 返回
        return column.getId();
    }

    @Override
    public void updateColumn(ColumnSaveReqVO updateReqVO) {
        // 校验存在
        validateColumnExists(updateReqVO.getId());
        // 更新
        ColumnDO updateObj = BeanUtils.toBean(updateReqVO, ColumnDO.class);
        columnMapper.updateById(updateObj);
    }

    @Override
    public void deleteColumn(String id) {
        // 校验存在
        validateColumnExists(id);
        // 删除
        columnMapper.deleteById(id);
    }

    private void validateColumnExists(String id) {
        if (columnMapper.selectById(id) == null) {
            throw exception(COLUMN_NOT_EXISTS);
        }
    }

    @Override
    public ColumnDO getColumn(String id) {
        return columnMapper.selectById(id);
    }

    @Override
    public PageResult<ColumnDO> getColumnPage(ColumnPageReqVO pageReqVO) {
        return columnMapper.selectPage(pageReqVO);
    }

}