package com.liquidnet.service.sweet.service.impl;

import com.liquidnet.commons.lang.util.CollectionUtil;
import com.liquidnet.commons.lang.util.DateUtil;
import com.liquidnet.commons.lang.util.IDGenerator;
import com.liquidnet.commons.lang.util.StringUtil;
import com.liquidnet.service.base.ResponseDto;
import com.liquidnet.service.base.SqlMapping;
import com.liquidnet.service.base.constant.MQConst;
import com.liquidnet.service.sweet.config.WechatMaConfigure;
import com.liquidnet.service.sweet.utils.QueueUtils;
import com.liquidnet.service.sweet.utils.WechatUsersRedisUtils;
import com.liquidnet.service.sweet.vo.SweetMaoDengVo;
import com.liquidnet.service.sweet.vo.SweetWechatUsersVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.LinkedList;

@Service
@Slf4j
public class SweetWechatMaoDengServiceImpl {

    @Autowired
    private WechatUsersRedisUtils redisUtils;
    @Autowired
    QueueUtils queueUtils;
    @Autowired
    WechatMaConfigure maConfigure;

    public ResponseDto addBuilderImg(String userId, String imgUrl) {
        LocalDateTime localDateTime = LocalDateTime.now(); //生成创建时间
        try {
            SweetWechatUsersVo wechatUsers = redisUtils.getSweetWechatUsersOfUnionId(userId, 2);
            if (null == wechatUsers) {
                return ResponseDto.failure("请求失败");
            }
            SweetMaoDengVo sweetMaoDeng = redisUtils.getSweetMaoDeng(wechatUsers.getOpenId());
            if (sweetMaoDeng != null) {
                sweetMaoDeng.setImgUrl(imgUrl);
            }
            String textMsg = sweetMaoDeng.getTextMsg();
            String picUrl = sweetMaoDeng.getPicUrl();
            sweetMaoDeng.setCreatedAt(localDateTime);
            redisUtils.setSweetMaoDeng(sweetMaoDeng);
            if (sweetMaoDeng.getMaoId() == null) {
                sweetMaoDeng.setMaoId("0");
            }
            if (StringUtil.isNotEmpty(textMsg) && StringUtil.isNotEmpty(picUrl)) {
                //redis队列入库
                LinkedList<String> sqls = CollectionUtil.linkedListString();
                LinkedList<Object[]> sqlsDataA = CollectionUtil.linkedListObjectArr();
                sqls.add(SqlMapping.get("sweet_wechat_maodeng.img.update"));
                sqlsDataA.add(new Object[]{imgUrl, wechatUsers.getOpenId(), sweetMaoDeng.getMaoId()});
                queueUtils.sendMsgByRedis(MQConst.SweetQueue.SWEET_WECHAT_MAODENG_TEXT_INSERT.getKey(), SqlMapping.gets(sqls, sqlsDataA));
                return ResponseDto.success("请求成功");
            }

            return ResponseDto.failure("请求失败");
        } catch (Exception e) {
            e.printStackTrace();
            log.error("[ERROR] = {}", e);
            return ResponseDto.failure("请求失败");
        }
    }
}
