package cn.axzo.msg.center.message.service.impl;

import cn.axzo.msg.center.dal.MessageTemplateButtonV3Dao;
import cn.axzo.msg.center.dal.MessageTemplateGroupV3Dao;
import cn.axzo.msg.center.dal.MessageTemplateV3Dao;
import cn.axzo.msg.center.domain.entity.BaseEntityWithOperator;
import cn.axzo.msg.center.domain.entity.MessageTemplateButtonV3;
import cn.axzo.msg.center.domain.entity.MessageTemplateGroupV3;
import cn.axzo.msg.center.domain.entity.MessageTemplateV3;
import cn.axzo.msg.center.service.template.request.MessageTemplateSyncQueryRequest;
import cn.axzo.msg.center.service.template.request.MessageTemplateV3SyncRequest;
import cn.axzo.msg.center.service.template.request.MessageTemplateV3SyncResponse;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import lombok.RequiredArgsConstructor;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author yanglin
 */
@Service
@RequiredArgsConstructor
public class MessageTemplateV3SyncService {

    private final MessageTemplateV3Dao messageTemplateV3Dao;
    private final MessageTemplateGroupV3Dao messageTemplateGroupV3Dao;
    private final MessageTemplateButtonV3Dao messageTemplateButtonV3Dao;

    public MessageTemplateV3SyncResponse getSyncMessageTemplate(MessageTemplateSyncQueryRequest request) {
        MessageTemplateV3 template = findTemplate(request.getTemplateCode());
        if (template == null)
            return null;
        List<MessageTemplateGroupV3> groups = messageTemplateGroupV3Dao.lambdaQuery()
                .eq(MessageTemplateGroupV3::getTemplateCode, template.getCode())
                .list();
        List<MessageTemplateButtonV3> buttons = messageTemplateButtonV3Dao.lambdaQuery()
                .eq(MessageTemplateButtonV3::getTemplateCode, template.getCode())
                .list();

        template.getOrCreateRecordExt().setIsSyncedForTest(true);
        groups.forEach(group -> group.getOrCreateRecordExt().setIsSyncedForTest(true));
        buttons.forEach(button -> button.getOrCreateRecordExt().setIsSyncedForTest(true));

        MessageTemplateV3SyncResponse resp = new MessageTemplateV3SyncResponse();
        JSONObject respJson = new JSONObject();
        respJson.put("template", template);
        respJson.put("groups", groups);
        respJson.put("buttons", buttons);
        resp.setTemplate(respJson);
        return resp;
    }

    /**
     * @return error message
     */
    public String syncTemplate(MessageTemplateV3SyncRequest request) {
        MessageTemplateV3 template = request.getTemplate()
                .getObject("template", MessageTemplateV3.class);
        MessageTemplateV3 savedTemplate = findTemplate(template.getCode());
        if (savedTemplate != null) return "模板已存在";
        // @formatter:off
        List<MessageTemplateGroupV3> groups = request.getTemplate()
                .getObject("groups", new TypeReference<List<MessageTemplateGroupV3>>() {});
        List<MessageTemplateButtonV3> buttons = request.getTemplate()
                .getObject("buttons", new TypeReference<List<MessageTemplateButtonV3>>() {});
        // @formatter:on

        setBasicProps(template, request.getOperatorId(), request.getOperatorName());
        groups.forEach(group -> setBasicProps(group, request.getOperatorId(), request.getOperatorName()));
        buttons.forEach(button -> setBasicProps(button, request.getOperatorId(), request.getOperatorName()));

        messageTemplateV3Dao.save(template);
        if (CollectionUtils.isNotEmpty(groups))
            messageTemplateGroupV3Dao.saveBatch(groups);
        if (CollectionUtils.isNotEmpty(buttons))
            messageTemplateButtonV3Dao.saveBatch(buttons);

        return null;
    }

    private MessageTemplateV3 findTemplate(String templateCode) {
        return messageTemplateV3Dao.lambdaQuery()
                .eq(MessageTemplateV3::getCode, templateCode)
                .one();
    }

    private void setBasicProps(BaseEntityWithOperator<?> entity,
                               Long operatorId, String operatorName) {
        entity.setCreateAt(null);
        entity.setUpdateAt(null);
        entity.setCreatePersonId(operatorId);
        entity.setCreatePersonName(operatorName);
        entity.setUpdatePersonId(operatorId);
        entity.setUpdatePersonName(operatorName);
    }
}