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.CustomerInfoDO;
import com.iotechn.unimall.data.dto.CustomerInfoDTO;
import com.iotechn.unimall.data.mapper.CustomerInfoMapper;
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 java.util.Date;
import java.util.List;

/**
 * Generate Code By Unimall
 */
@Service
public class CustomerInfoServiceImpl implements CustomerInfoService {

    @Autowired
    private CustomerInfoMapper customerInfoMapper;

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

    @Override
    public Page<CustomerInfoDO> list(CustomerInfoDTO selectDTO, Integer page, Integer limit, Long adminId) throws ServiceException {
        Wrapper<CustomerInfoDO> wrapper = new EntityWrapper<CustomerInfoDO>();
        List<CustomerInfoDO> list = customerInfoMapper.selectPage(new RowBounds((page - 1) * limit, limit), wrapper);
        Integer count = customerInfoMapper.selectCount(wrapper);
        return new Page<CustomerInfoDO>(list, page, limit, count);
    }

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

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

}
