package org.dromara.zhishu.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.dromara.zhishu.domain.TShopMessageSubscribe;
import org.dromara.zhishu.domain.vo.MessageSubscribeVo;
import org.dromara.zhishu.mapper.TShopMessageSubscribeMapper;
import org.dromara.zhishu.service.TShopMessageSubscribeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Slf4j
@Service
public class TShopMessageSubscribeServiceImpl implements TShopMessageSubscribeService {

    @Autowired
    private TShopMessageSubscribeMapper tShopMessageSubscribeMapper;

    @Override
    public void insertOrUpdate(List<MessageSubscribeVo> messageSubscribeVo, Long id) {
        // 查询库中是否存在该店铺的消息订阅记录
        List<TShopMessageSubscribe> tShopMessageSubscribeList = new LambdaQueryChainWrapper<>(tShopMessageSubscribeMapper)
                .eq(TShopMessageSubscribe::getDelFlag, "0")
                .eq(TShopMessageSubscribe::getShopId, id)
                .list();
        ObjectMapper mapper = new ObjectMapper();
        try {
            if (ObjectUtil.isEmpty(tShopMessageSubscribeList)) {
                // 没有则插入
                TShopMessageSubscribe tShopMessageSubscribe = new TShopMessageSubscribe();
                tShopMessageSubscribe.setShopId(id);

                // tShopMessageSubscribe.setSubscribeDetail(JSONObject.toJSONString(messageSubscribeVo));
                tShopMessageSubscribe.setSubscribeDetail(mapper.writeValueAsString(messageSubscribeVo));
                tShopMessageSubscribeMapper.insert(tShopMessageSubscribe);
            } else {
                // 有则更新
                new LambdaUpdateChainWrapper<>(tShopMessageSubscribeMapper)
                        .eq(TShopMessageSubscribe::getDelFlag, "0")
                        .eq(TShopMessageSubscribe::getShopId, id)
                        // .set(TShopMessageSubscribe::getSubscribeDetail, JSONObject.toJSONString(messageSubscribeVo))
                        .set(TShopMessageSubscribe::getSubscribeDetail, mapper.writeValueAsString(messageSubscribeVo))
                        .update();
            }
        } catch (JsonProcessingException e) {
            log.info("json转换异常");
            throw new RuntimeException(e);
        }
    }
}
