package com.uas.account.dao;

import com.uas.account.entity.UserQuestion;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * Created by wangmh on 2017/10/31.
 */
@Repository
public class UserQuestionDaoImpl extends BaseDao implements UserQuestionDao {

    @Override
    public List<UserQuestion> getEncryptedQuestion(Long userUU) {
        if (userUU == null) {
            return null;
        }
        List<UserQuestion> questions = jdbcTemplate.query("select id,userUU,question,answer,sort from ac$user$question where userUU=?",
                new BeanPropertyRowMapper<UserQuestion>(UserQuestion.class), userUU);
        return questions;
    }

    @Override
    public boolean checkEncryptedQuestion() {
        return false;
    }

    @Override
    public void save(List<UserQuestion> questions) {
        if (questions == null) {
            return;
        }
        for (UserQuestion question : questions) {
            int count = count("select id from ac$user$question where userUU=? and sort=?", question.getUserUU(), question.getSort());
            if (count == 0) {
                question.setId(generateId("ac$user$question_seq"));
                jdbcTemplate.update("insert into ac$user$question(id, useruu, question, answer, sort) values (?,?,?,?,?)",
                        question.getId(),question.getUserUU(),question.getQuestion(),question.getAnswer(),question.getSort());
            } else {
                jdbcTemplate.update("update ac$user$question set question=?,answer=?", question.getQuestion(), question.getAnswer());
            }
        }
    }

    @Override
    public void saveOne(UserQuestion question) {
        int count = count("select count(id) from ac$user$question where userUU=? and sort=?", question.getUserUU(), question.getSort());
        if (count == 0) {
            question.setId(generateId("ac$user$question_seq"));
            jdbcTemplate.update("insert into ac$user$question(id, useruu, question, answer, sort) values (?,?,?,?,?)",
                    question.getId(),question.getUserUU(),question.getQuestion(),question.getAnswer(),question.getSort());
        } else {
            jdbcTemplate.update("update ac$user$question set question=?,answer=? where useruu=? and sort=?",
                    question.getQuestion(), question.getAnswer(), question.getUserUU(), question.getSort());
        }
    }
}
