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

import com.liquidnet.commons.lang.util.CollectionUtil;
import com.liquidnet.service.base.SqlMapping;
import com.liquidnet.service.base.constant.MQConst;
import com.liquidnet.service.goblin.dto.GoblinUserSafeConfigDto;
import com.liquidnet.service.goblin.service.IGoblinUserSafeConfigService;
import com.liquidnet.service.goblin.util.GoblinRedisUtils;
import com.liquidnet.service.goblin.util.QueueUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.util.LinkedList;

@Service
public class GoblinUserSafeConfigServiceImpl implements IGoblinUserSafeConfigService {
    @Value("${liquidnet.secret.passwd-salt}")
    private String passwdSalt;
    @Autowired
    private QueueUtils queueUtils;
    @Autowired
    private GoblinRedisUtils goblinRedisUtils;

    @Override
    public boolean initSafePasswd(String passwd, String uid) {
        GoblinUserSafeConfigDto userSafeConfigDto = GoblinUserSafeConfigDto.getNew();
        userSafeConfigDto.setPasswd(DigestUtils.md5DigestAsHex(passwd.concat(passwdSalt).getBytes(StandardCharsets.UTF_8)));
        if (goblinRedisUtils.setUserSafeConfigDto(uid, userSafeConfigDto)) {
            LinkedList<String> toMqSqls = CollectionUtil.linkedListString();
            toMqSqls.add(SqlMapping.get("goblin_user_safe_config.set_passwd"));
            LinkedList<Object[]> initUserSafeConfigObjs = CollectionUtil.linkedListObjectArr();
            LocalDateTime nowDateTime = LocalDateTime.now();
            initUserSafeConfigObjs.add(new Object[]{uid, userSafeConfigDto.getPasswd(), nowDateTime, nowDateTime, uid, userSafeConfigDto.getPasswd(), nowDateTime});
            queueUtils.sendMsgByRedis(MQConst.GoblinQueue.SQL_GOODS.getKey(), SqlMapping.gets(toMqSqls, initUserSafeConfigObjs));
            return true;
        }
        return false;
    }
}
