package cn.iocoder.yudao.module.system.service.carteen;

import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
import cn.iocoder.yudao.module.system.controller.admin.carteen.vo.CarteenPageReqVO;
import cn.iocoder.yudao.module.system.controller.admin.carteen.vo.CarteenSaveReqVO;
import cn.iocoder.yudao.module.system.dal.dataobject.carteen.CarteenDO;
import cn.iocoder.yudao.module.system.dal.mysql.carteen.CarteenMapper;
import cn.iocoder.yudao.module.system.enums.ErrorCodeConstants;
import cn.iocoder.yudao.module.system.service.permission.PermissionService;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.Set;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;

/**
 * 门店管理 Service 实现类
 *
 * @author 开发账号
 */
@Service
@Validated
public class CarteenServiceImpl implements CarteenService {

    @Resource
    private CarteenMapper carteenMapper;
    @Resource
    private PermissionService permissionService;
    @Override
    public Long createCarteen(CarteenSaveReqVO createReqVO) {
        // 插入
        CarteenDO carteen = BeanUtils.toBean(createReqVO, CarteenDO.class);
        carteen.setDeleted(Boolean.FALSE);
        carteen.setMultipleManage(Boolean.FALSE);
        carteen.setAccountOrder(Boolean.FALSE);
        carteen.setDeleted(Boolean.FALSE);
        Set<Long> set = permissionService.getUserRoleIdListByUserId(SecurityFrameworkUtils.getLoginUserId());
        carteen.setSerialNumber(Arrays.toString(set.toArray()));
        carteenMapper.insert(carteen);
        // 返回
        return carteen.getId();
    }
    @Override
    public void updateCarteen(CarteenSaveReqVO updateReqVO) {
        // 校验存在
        validateCarteenExists(updateReqVO.getId());
        // 更新
        CarteenDO updateObj = BeanUtils.toBean(updateReqVO, CarteenDO.class);
        carteenMapper.updateById(updateObj);
    }

    @Override
    public void deleteCarteen(Long id) {
        // 校验存在
        validateCarteenExists(id);
        // 删除
        carteenMapper.deleteById(id);
    }

    private void validateCarteenExists(Long id) {
        if (carteenMapper.selectById(id) == null) {
            throw exception(ErrorCodeConstants.CARTEEN_NOT_EXISt);
        }
    }

    @Override
    public CarteenDO getCarteen(Long id) {
        return carteenMapper.selectById(id);
    }

    @Override
    public PageResult<CarteenDO> getCarteenPage(CarteenPageReqVO pageReqVO) {
        return carteenMapper.selectPage(pageReqVO);
    }

}