package com.xindazhou.business.service.agreement;

import com.xindazhou.framework.common.pojo.PageResult;
import com.xindazhou.business.controller.admin.agreement.vo.AgreementPageReqVO;
import com.xindazhou.business.controller.admin.agreement.vo.AgreementSaveReqVO;
import com.xindazhou.business.convert.agreement.AgreementConvert;
import com.xindazhou.business.dal.dataobject.agreement.AgreementDO;
import com.xindazhou.business.dal.mysql.agreement.AgreementMapper;
import com.xindazhou.framework.common.util.object.BeanUtils;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import static com.xindazhou.framework.common.exception.util.ServiceExceptionUtil.exception;
import static com.xindazhou.business.enums.ErrorCodeConstants.*;

/**
 * APP协议管理 Service 实现类
 *
 * @author xindazhou
 */
@Service
@Slf4j
@Validated
public class AgreementServiceImpl implements AgreementService {

    @Resource
    private AgreementMapper agreementMapper;

    @Override
    public Long createAgreement(AgreementSaveReqVO createReqVO) {
        // 插入协议
        AgreementDO agreement = AgreementConvert.INSTANCE.convert(createReqVO);
        // 生成协议编号
        agreement.setAgreementId(generateAgreementId());
        agreementMapper.insert(agreement);
        return agreement.getId();
    }

    @Override
    public void updateAgreement(AgreementSaveReqVO updateReqVO) {
        // 校验协议存在
        validateAgreementExists(updateReqVO.getId());

        // 更新协议
        AgreementDO updateObj = AgreementConvert.INSTANCE.convert(updateReqVO);
        agreementMapper.updateById(updateObj);
    }

    @Override
    public void deleteAgreement(Long id) {
        // 校验协议存在
        validateAgreementExists(id);
        // 删除
        agreementMapper.deleteById(id);
    }

    @Override
    public AgreementDO getAgreement(Long id) {
        return agreementMapper.selectById(id);
    }

    @Override
    public PageResult<AgreementDO> getAgreementPage(AgreementPageReqVO pageReqVO) {
        return agreementMapper.selectPage(pageReqVO);
    }

    private AgreementDO validateAgreementExists(Long id) {
        AgreementDO agreement = agreementMapper.selectById(id);
        if (agreement == null) {
            throw exception(AGREEMENT_NOT_EXISTS);
        }
        return agreement;
    }

    /**
     * 生成协议编号
     */
    private String generateAgreementId() {
        return "AGR" + System.currentTimeMillis();
    }

}

