package com.iotechn.unimall.admin.api.sys;


import com.iotechn.unimall.core.exception.AdminServiceException;
import com.iotechn.unimall.core.exception.ExceptionDefinition;
import com.iotechn.unimall.core.exception.ServiceException;
import com.iotechn.unimall.data.model.Page;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.iotechn.unimall.data.domain.CountryDO;
import com.iotechn.unimall.data.dto.CountryDTO;
import com.iotechn.unimall.data.mapper.CountryMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.BeanUtils;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;

/**
 * Generate Code By Unimall
 */
@Service
public class CountryServiceImpl implements CountryService {

    @Autowired
    private CountryMapper countryMapper;

    @Override
    public boolean delete(Long id) throws ServiceException {
        return countryMapper.deleteById(id) > 0;
    }

    @Override
    public Page<CountryDO> list(CountryDTO selectDTO, Integer page, Integer limit) throws ServiceException {
        Wrapper<CountryDO> wrapper = new EntityWrapper<CountryDO>();
        if(!StringUtils.isEmpty(selectDTO.getCountry())){
            wrapper.eq("country",selectDTO.getCountry());
        }
        List<CountryDO> list = countryMapper.selectPage(new RowBounds((page - 1) * limit, limit), wrapper);
        Integer count = countryMapper.selectCount(wrapper);
        return new Page<CountryDO>(list, page, limit, count);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public CountryDO create(CountryDTO insertDTO) throws ServiceException {
         Date now = new Date();
         CountryDO insertDO = new CountryDO();
         BeanUtils.copyProperties(insertDTO, insertDO);
         insertDO.setGmtUpdate(now);
         insertDO.setGmtCreate(now);
         if (countryMapper.insert(insertDO) > 0) {
             return insertDO;
         }
         throw new AdminServiceException(ExceptionDefinition.ADMIN_UNKNOWN_EXCEPTION);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String edit(CountryDTO editDTO) throws ServiceException {
         Date now = new Date();
         CountryDO updateDO = new CountryDO();
         BeanUtils.copyProperties(editDTO, updateDO);
         updateDO.setGmtUpdate(now);
         if (countryMapper.updateById(updateDO) > 0) {
             return "ok";
         }
         throw new AdminServiceException(ExceptionDefinition.ADMIN_UNKNOWN_EXCEPTION);
    }

}
