package cn.iocoder.yudao.module.supplier.service.product;

import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.framework.security.core.LoginUser;
import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
import cn.iocoder.yudao.module.supplier.controller.admin.product.vo.ConnectRecordPageReqVO;
import cn.iocoder.yudao.module.supplier.controller.admin.product.vo.ConnectRecordSaveReqVO;
import cn.iocoder.yudao.module.supplier.dal.dataobject.product.ConnectRecordDO;
import cn.iocoder.yudao.module.supplier.dal.mysql.product.ConnectRecordMapper;
import cn.iocoder.yudao.module.supplier.enums.ErrorCodeConstant;
import cn.iocoder.yudao.module.system.dal.dataobject.user.AdminUserDO;
import cn.iocoder.yudao.module.system.service.user.AdminUserService;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;

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

/**
 * 供应商联系记录 Service 实现类
 *
 * @author 芋道源码
 */
@Service
@Validated
public class ConnectRecordServiceImpl implements ConnectRecordService {

    @Resource
    private ConnectRecordMapper connectRecordMapper;
    @Resource
    private AdminUserService adminUserService;

    @Override
    public Long createConnectRecord(ConnectRecordSaveReqVO createReqVO) {
        // 插入
        ConnectRecordDO connectRecord = BeanUtils.toBean(createReqVO, ConnectRecordDO.class);
        LoginUser loginUser = SecurityFrameworkUtils.getLoginUser();
        Long id = loginUser.getId();
        AdminUserDO user = adminUserService.getUser(id);
        connectRecord.setUserId(id);
        connectRecord.setUsername(user.getNickname());
        connectRecordMapper.insert(connectRecord);
        // 返回
        return connectRecord.getId();
    }

    @Override
    public void updateConnectRecord(ConnectRecordSaveReqVO updateReqVO) {
        // 校验存在
        validateConnectRecordExists(updateReqVO.getId());
        // 更新
        ConnectRecordDO updateObj = BeanUtils.toBean(updateReqVO, ConnectRecordDO.class);
        connectRecordMapper.updateById(updateObj);
    }

    @Override
    public void deleteConnectRecord(Long id) {
        // 校验存在
        validateConnectRecordExists(id);
        // 删除
        connectRecordMapper.deleteById(id);
    }

    private void validateConnectRecordExists(Long id) {
        if (connectRecordMapper.selectById(id) == null) {
            throw exception(ErrorCodeConstant.NOT_EXISTS);
        }
    }

    @Override
    public ConnectRecordDO getConnectRecord(Long id) {
        return connectRecordMapper.selectById(id);
    }

    @Override
    public PageResult<ConnectRecordDO> getConnectRecordPage(ConnectRecordPageReqVO pageReqVO) {
        return connectRecordMapper.selectPage(pageReqVO);
    }

}
