package com.liquidnet.service.goblin.service.impl;

import com.liquidnet.commons.lang.util.CollectionUtil;
import com.liquidnet.commons.lang.util.CurrentUtil;
import com.liquidnet.commons.lang.util.IDGenerator;
import com.liquidnet.service.adam.dto.vo.AdamUserInfoVo;
import com.liquidnet.service.base.ResponseDto;
import com.liquidnet.service.base.SqlMapping;
import com.liquidnet.service.base.constant.MQConst;
import com.liquidnet.service.goblin.dto.manage.vo.GoblinGoodsAnticipateValueVo;
import com.liquidnet.service.goblin.dto.vo.GoblinGoodAnticipateUserVo;
import com.liquidnet.service.goblin.dto.vo.GoblinGoodsAnticipateHelpVo;
import com.liquidnet.service.goblin.dto.vo.GoblinGoodsAnticipateShareVo;
import com.liquidnet.service.goblin.dto.vo.GoblinGoodsAnticipateVo;
import com.liquidnet.service.goblin.service.IGoblinGoodsAnticipateService;
import com.liquidnet.service.goblin.util.GoblinAnticipateUtils;
import com.liquidnet.service.goblin.util.GoblinMongoUtils;
import com.liquidnet.service.goblin.util.GoblinRedisUtils;
import com.liquidnet.service.goblin.util.QueueUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigInteger;
import java.time.LocalDateTime;
import java.util.LinkedList;
import java.util.List;

/**
 * <p>
 * 预约表 服务实现类
 * </p>
 *
 * @author liquidnet
 * @since 2022-04-07
 */
@Service
@Slf4j
public class GoblinGoodsAnticipateServiceImpl implements IGoblinGoodsAnticipateService {


    @Autowired
    GoblinRedisUtils goblinRedisUtils;

    @Autowired
    QueueUtils queueUtils;

    @Autowired
    GoblinAnticipateUtils goblinAnticipateUtils;

    @Autowired
    GoblinMongoUtils goblinMongoUtils;

    @Override
    public ResponseDto<Object> userAbout(String skuId) {
        //查询该skuId是否能被预约
        GoblinGoodsAnticipateValueVo anticipateValueVo = goblinRedisUtils.getValueBySkuId(skuId);
        if (anticipateValueVo != null) {
            anticipateValueVo.setState(GoblinAnticipateUtils.setState(anticipateValueVo.getAboutStartDate(), anticipateValueVo.getAboutEndDate()));
            if (!anticipateValueVo.getState().equals(1)) {
                return ResponseDto.failure("该商品预约尚未开始或已经结束，不可预约！");
            }
            //查询该用户是否预
            String uid = CurrentUtil.getCurrentUid();
            GoblinGoodAnticipateUserVo userVo = goblinRedisUtils.getUserAboutAut(skuId, uid);
            LinkedList<Object[]> sqlValue = CollectionUtil.linkedListObjectArr();
            if (userVo == null) {
                GoblinGoodAnticipateUserVo user = new GoblinGoodAnticipateUserVo();
                user.setUid(uid);
                user.setSkuId(skuId);
                String mobile = StringUtils.defaultString(((String) CurrentUtil.getTokenClaims().get(CurrentUtil.TOKEN_MOBILE)), "");
                user.setPhone(mobile);
                user.setState(0);
                user.setCreatedDate(LocalDateTime.now());
                //mongodb记录
                goblinRedisUtils.setUserAboutSku(user);
                //用户没有预约过
                //发送redis消息修改mysql记录用户预约
                sqlValue.add(new Object[]{
                        user.getUid(),
                        skuId,
                        user.getPhone(),
                        0,
                        user.getCreatedDate()
                });
                sendRedis("goblin_goods_anticipate_user", sqlValue);
                goblinRedisUtils.setSkuIdPeople(skuId);
                //获取用户头像个数小于等于2则保存用户头像
                List<String> userAvatar = goblinRedisUtils.getUserAvatar(skuId);
                if (userAvatar != null && userAvatar.size() <= 2) {
                    //查询用户信息获取用户头像并保存
                    AdamUserInfoVo userInfo = goblinAnticipateUtils.getUserInfo();
                    goblinRedisUtils.setUserAvatar(skuId, userInfo.getAvatar());
                }
            }
            return ResponseDto.success();
        }
        return ResponseDto.failure("该预约不存在！");
    }

    @Override
    public ResponseDto<Boolean> selectAnticipate(String skuId) {
        String uid = CurrentUtil.getCurrentUid();
        return ResponseDto.success(goblinRedisUtils.getUserAboutAut(skuId, uid) != null);
    }

    @Override
    public ResponseDto<Object> share(String skuId, String url) {
        //获取用户uid
        String uid = CurrentUtil.getCurrentUid();
        //获取redis关联记录
        Integer share = goblinRedisUtils.getShare(skuId, uid);
        if (share != null) {
            return ResponseDto.failure("已开启助力");
        } else {
            //查询sku需要助力人数
//            Integer skuIdPeople = goblinRedisUtils.getSharePeopleBySkuId(skuId);

            //redis缓存
            goblinRedisUtils.setShare(skuId, uid, 0);

            String sId = IDGenerator.nextTimeId2();
            GoblinGoodsAnticipateShareVo goblinGoodsAnticipateShareVo = GoblinGoodsAnticipateShareVo.getNew();
            goblinGoodsAnticipateShareVo.setSid(sId);
            goblinGoodsAnticipateShareVo.setUid(uid);
            goblinGoodsAnticipateShareVo.setSkuId(skuId);
            goblinGoodsAnticipateShareVo.setUrl(url);
            goblinGoodsAnticipateShareVo.setCreatedDate(LocalDateTime.now());
            //开启助力
            //mongodb缓存
            goblinMongoUtils.setGoblinGoodsAnticipateShareVo(goblinGoodsAnticipateShareVo);

            //redis消息  MySQL
            LinkedList<Object[]> sqlValue = CollectionUtil.linkedListObjectArr();
            sqlValue.add(new Object[]{
                    goblinGoodsAnticipateShareVo.getSid(),
                    goblinGoodsAnticipateShareVo.getUid(),
                    goblinGoodsAnticipateShareVo.getSkuId(),
                    goblinGoodsAnticipateShareVo.getUrl(),
                    goblinGoodsAnticipateShareVo.getCreatedDate()
            });
            sendRedis("goblin_goods_anticipate_user", sqlValue);
        }
        return ResponseDto.success();
    }

    @Override
    public ResponseDto<Object> help(String sid) {
        //获取uid
        String uid = CurrentUtil.getCurrentUid();

        //查询mongodb 是否助力过该分享
        GoblinGoodsAnticipateHelpVo goodsAnticipateHelpVo = goblinMongoUtils.getHelpVo(sid, uid);

        if (goodsAnticipateHelpVo == null) {
            GoblinGoodsAnticipateHelpVo helpVo = GoblinGoodsAnticipateHelpVo.getNew();
            helpVo.setHelpUid(uid);
            helpVo.setSid(sid);
            helpVo.setCreateDate(LocalDateTime.now());
            //mongodb缓存
            goblinMongoUtils.setHelpVo(helpVo);

            //redis消息   MySQL插入
            LinkedList<Object[]> sqlValue = CollectionUtil.linkedListObjectArr();
            sqlValue.add(new Object[]{
                    helpVo.getSid(),
                    helpVo.getHelpUid(),
                    helpVo.getCreateDate()
            });
            sendRedis("goblin_goods_anticipate_help",sqlValue);

            //记录助力人数头像（前六个）
            List<String> helpUserAvatar = goblinRedisUtils.getHelpUserAvatar(sid);
            if (helpUserAvatar.size() <= 6) {
                //获取用户头像保存
                AdamUserInfoVo userInfo = goblinAnticipateUtils.getUserInfo();
                //新增助力头像
                goblinRedisUtils.setHelpUserAvatar(sid, userInfo.getAvatar());
            }
            return ResponseDto.success();
        }
        return ResponseDto.failure("已助力该分享");
    }

    @Override
    public ResponseDto<Object> getHelpAvatar(String sid) {
        return ResponseDto.success(goblinRedisUtils.getHelpUserAvatar(sid));
    }

    public void sendRedis(String sqlKey, LinkedList<Object[]> sqlData) {
        LinkedList<String> sql = CollectionUtil.linkedListString();
        sql.add(SqlMapping.get(sqlKey));
        String sqlStr = SqlMapping.gets(sql, sqlData);
        queueUtils.sendMsgByRedis(
                MQConst.GoblinQueue.GOBLIN_STORE_MARKET.getKey(),
                sqlStr);
    }

}
