package com.agileboot.domain.collaboration.record.model;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.agileboot.common.exception.ApiException;
import com.agileboot.common.exception.error.ErrorCode;
import com.agileboot.domain.collaboration.record.command.AddCollaborationRecordCommand;
import com.agileboot.domain.collaboration.record.command.UpdateCollaborationRecordCommand;
import com.agileboot.domain.collaboration.record.db.CollaborationRecordEntity;
import com.agileboot.domain.collaboration.record.db.CollaborationRecordService;
import lombok.NoArgsConstructor;

/**
 * @author codex
 */
@NoArgsConstructor
public class CollaborationRecordModel extends CollaborationRecordEntity {

    private CollaborationRecordService recordService;

    public CollaborationRecordModel(CollaborationRecordService recordService) {
        this.recordService = recordService;
    }

    public CollaborationRecordModel(CollaborationRecordEntity entity, CollaborationRecordService recordService) {
        if (entity != null) {
            BeanUtil.copyProperties(entity, this);
        }
        this.recordService = recordService;
    }

    public void loadFromAddCommand(AddCollaborationRecordCommand command) {
        if (command == null) {
            return;
        }
        BeanUtil.copyProperties(command, this, "recordId", "completeDate");
        loadDefaultValues();
    }

    public void loadFromUpdateCommand(UpdateCollaborationRecordCommand command) {
        if (command == null) {
            return;
        }
        loadFromAddCommand(command);
    }

    public void checkRequiredFields() {
        if (StrUtil.isBlank(getBrand())) {
            throw new ApiException(ErrorCode.FAILED);
        }
        if (StrUtil.isBlank(getGoods())) {
            throw new ApiException(ErrorCode.FAILED);
        }
    }

    public void saveRecord() {
        recordService.save(this);
    }

    public void updateRecord() {
        recordService.updateById(this);
    }

    private void loadDefaultValues() {
        if (getImageReturnNum() == null) {
            setImageReturnNum(1);
        }
        if (StrUtil.isBlank(getRetainedMethod())) {
            setRetainedMethod("寄拍");
        }
        if (StrUtil.isBlank(getCooperatedMethod())) {
            setCooperatedMethod("水下");
        }
        if (StrUtil.isBlank(getPurchaseMethod())) {
            setPurchaseMethod("拍单");
        }
    }

}
