package cn.com.poc.agent_application.service.impl;

import cn.com.poc.agent_application.constant.AgentApplicationConstants;
import cn.com.poc.agent_application.query.PublishAgentApplicationQueryCondition;
import cn.com.poc.agent_application.query.PublishAgentApplicationQueryItem;
import cn.com.poc.agent_application.service.BizAgentApplicationMallService;
import cn.com.poc.common.constant.CommonConstant;
import cn.com.poc.common.utils.JsonUtils;
import cn.com.yict.framemax.core.i18n.I18nMessageException;
import cn.com.yict.framemax.core.service.impl.BaseServiceImpl;
import cn.com.poc.agent_application.service.BizAgentApplicationPublishService;
import cn.com.poc.agent_application.model.BizAgentApplicationPublishModel;
import cn.com.poc.agent_application.entity.BizAgentApplicationPublishEntity;
import cn.com.poc.agent_application.convert.BizAgentApplicationPublishConvert;
import cn.com.poc.agent_application.repository.BizAgentApplicationPublishRepository;
import cn.com.yict.framemax.data.model.PagingInfo;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import org.apache.commons.collections4.CollectionUtils;

import java.util.ArrayList;
import java.util.stream.Collectors;
import java.util.List;
import javax.annotation.Resource;

import org.springframework.util.Assert;

@Service
public class BizAgentApplicationPublishServiceImpl extends BaseServiceImpl
        implements BizAgentApplicationPublishService {

    @Resource
    private BizAgentApplicationPublishRepository repository;

    @Resource
    private BizAgentApplicationMallService bizAgentApplicationMallService;

    public BizAgentApplicationPublishEntity get(java.lang.Integer id) throws Exception {
        Assert.notNull(id);
        BizAgentApplicationPublishModel model = this.repository.get(id);
        if (model == null) {
            return null;
        }
        if ("Y".equals(model.getIsDeleted())) {
            return null;
        }
        return BizAgentApplicationPublishConvert.modelToEntity(model);
    }

    @Override
    public BizAgentApplicationPublishEntity getByAgentId(String agentId) {
        Assert.notNull(agentId);
        BizAgentApplicationPublishModel model = new BizAgentApplicationPublishModel();
        model.setAgentId(agentId);
        model.setIsDeleted(CommonConstant.IsDeleted.N);
        List<BizAgentApplicationPublishModel> models = this.repository.findByExample(model);
        if (CollectionUtils.isEmpty(models)) {
            return null;
        }
        return BizAgentApplicationPublishConvert.modelToEntity(models.get(0));
    }

    public List<BizAgentApplicationPublishEntity> findByExample(BizAgentApplicationPublishEntity example, PagingInfo pagingInfo) throws Exception {
        List<BizAgentApplicationPublishEntity> result = new ArrayList<BizAgentApplicationPublishEntity>();
        BizAgentApplicationPublishModel model = new BizAgentApplicationPublishModel();
        if (example != null) {
            model = BizAgentApplicationPublishConvert.entityToModel(example);
        }
        model.setIsDeleted("N");
        List<BizAgentApplicationPublishModel> models = this.repository.findByExample(model, pagingInfo);
        if (CollectionUtils.isNotEmpty(models)) {
            result = models.stream().map(BizAgentApplicationPublishConvert::modelToEntity).collect(Collectors.toList());
        }
        return result;
    }

    public BizAgentApplicationPublishEntity save(BizAgentApplicationPublishEntity entity) throws Exception {
        Assert.notNull(entity);
        entity.setId(null);
        entity.setIsDeleted("N");
        BizAgentApplicationPublishModel model = BizAgentApplicationPublishConvert.entityToModel(entity);
        BizAgentApplicationPublishModel saveModel = this.repository.save(model);
        return BizAgentApplicationPublishConvert.modelToEntity(saveModel);
    }

    public BizAgentApplicationPublishEntity update(BizAgentApplicationPublishEntity entity) throws Exception {
        Assert.notNull(entity);
        Assert.notNull(entity.getId(), "update pk can not be null");
        BizAgentApplicationPublishModel model = this.repository.get(entity.getId());
        if (model == null) {
            throw new I18nMessageException("exception/publication.failed");
        }
        BizAgentApplicationPublishModel updateModel = BizAgentApplicationPublishConvert.entityToModel(entity);
        updateModel.setIsDeleted(CommonConstant.IsDeleted.N);
        updateModel.setCreator(model.getCreator());
        updateModel.setCreatedTime(model.getCreatedTime());
        updateModel.setModifier(null);
        updateModel.setModifiedTime(null);
        updateModel.setSysVersion(model.getSysVersion());
        BizAgentApplicationPublishModel saveModel = this.repository.save(updateModel);
        return BizAgentApplicationPublishConvert.modelToEntity(saveModel);
    }

    public void deletedById(java.lang.Integer id) throws Exception {
        Assert.notNull(id);
        BizAgentApplicationPublishModel model = this.repository.get(id);
        if (model != null) {
            if ("N".equals(model.getIsDeleted())) {
                model.setIsDeleted("Y");
                this.repository.save(model);
            }
        }
        bizAgentApplicationMallService.deletedByAgentPublishId(id);
    }

    @Override
    public void deleteByAgentId(String agentId) throws Exception {
        Assert.notNull(agentId);
        BizAgentApplicationPublishModel model = new BizAgentApplicationPublishModel();
        model.setAgentId(agentId);
        model.setIsDeleted(CommonConstant.IsDeleted.N);
        List<BizAgentApplicationPublishModel> models = this.repository.findByExample(model);
        if (CollectionUtils.isNotEmpty(models)) {
            BizAgentApplicationPublishModel deleteModel = models.get(0);
            deleteModel.setIsDeleted(CommonConstant.IsDeleted.Y);
            this.repository.save(deleteModel);
        }
    }

    @Override
    public List<PublishAgentApplicationQueryItem> query(PublishAgentApplicationQueryCondition condition, PagingInfo pagingInfo) throws Exception {
        return this.sqlDao.query(condition, PublishAgentApplicationQueryItem.class, pagingInfo);
    }

    /**
     * 参数验证和转换 Entity To Model
     *
     * @param entity
     * @param model
     */
    private void paramVerificationAndConvert(BizAgentApplicationPublishEntity entity, BizAgentApplicationPublishModel model) {
        if (entity.getMemberId() != null) {
            model.setMemberId(entity.getMemberId());
        }
        if (StringUtils.isNotBlank(entity.getAgentAvatar())) {
            model.setAgentAvatar(entity.getAgentAvatar());
        }
        if (StringUtils.isNotBlank(entity.getAgentTitle())) {
            model.setAgentTitle(entity.getAgentTitle());
        }
        if (StringUtils.isNotBlank(entity.getAgentDesc())) {
            model.setAgentDesc(entity.getAgentDesc());
        }
        if (StringUtils.isNotBlank(entity.getAgentSystem())) {
            model.setAgentSystem(entity.getAgentSystem());
        }

        if (StringUtils.isNotBlank(entity.getPreamble())) {
            model.setPreamble(entity.getPreamble());
        }
        if (ArrayUtils.isNotEmpty(entity.getFeaturedQuestions())) {
            model.setFeaturedQuestions(JsonUtils.serialize(entity.getFeaturedQuestions()));
        }
        if (entity.getCommunicationTurn() != null) {
            Assert.isTrue(entity.getCommunicationTurn() >= 0 && entity.getCommunicationTurn() <= 100, "communication turn is error,must more than 0 and less than 100");
            model.setCommunicationTurn(entity.getCommunicationTurn());
        }
        if (StringUtils.isNotBlank(entity.getContinuousQuestionStatus())) {
            Assert.isTrue(AgentApplicationConstants.CONTINUOUS_QUESTION_STATUS.isQuestionStatus(entity.getContinuousQuestionStatus())
                    , "continuous question status is error , must in default , customizable and close.");
            model.setContinuousQuestionStatus(entity.getContinuousQuestionStatus());
            if (AgentApplicationConstants.CONTINUOUS_QUESTION_STATUS.CUSTOMIZABLE.equals(entity.getContinuousQuestionStatus()) && entity.getContinuousQuestionTurn() != null) {
                Assert.isTrue(entity.getContinuousQuestionTurn() >= 1 && entity.getContinuousQuestionTurn() <= 5, "continuous question turn is error,must more than 1 and less than 5");
                model.setContinuousQuestionTurn(entity.getContinuousQuestionTurn());
            }
        }
        if (StringUtils.isNotBlank(entity.getContinuousQuestionSystem())) {
            model.setContinuousQuestionSystem(entity.getContinuousQuestionSystem());
        }
        if (ArrayUtils.isNotEmpty(entity.getKnowledgeIds())) {
            model.setKnowledgeIds(JsonUtils.serialize(entity.getKnowledgeIds()));
        }
        if (StringUtils.isNotBlank(entity.getKnowledgeSearchType())) {
            model.setKnowledgeSearchType(entity.getKnowledgeSearchType());
        }
        if (entity.getKnowledgeSimilarity() != null) {
            model.setKnowledgeSimilarity(entity.getKnowledgeSimilarity());
        }
        if (entity.getKnowledgeNResult() != null) {
            model.setKnowledgeNResult(entity.getKnowledgeNResult());
        }
        model.setKnowledgeResponseType(entity.getKnowledgeResponseType());
        if (ArrayUtils.isNotEmpty(entity.getKnowledgeCustomResponse())) {
            model.setKnowledgeCustomResponse(ArrayUtils.isNotEmpty(entity.getKnowledgeCustomResponse()) ? JsonUtils.serialize(entity.getKnowledgeCustomResponse()) : null);
        }
        if (StringUtils.isNotBlank(entity.getLargeModel())) {
            model.setLargeModel(entity.getLargeModel());
        }
        if (ArrayUtils.isNotEmpty(entity.getUnitIds())) {
            model.setUnitIds(JsonUtils.serialize(entity.getUnitIds()));
        }
        model.setIsDocumentParsing(entity.getIsDocumentParsing());
    }
}