package com.ytpm.service.qnmjz.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.IdUtil;
import com.github.pagehelper.PageInfo;
import com.ytpm.agent.enums.UserStatusEnum;
import com.ytpm.app.model.YtDyzAnswerRecord;
import com.ytpm.app.model.YtDyzPowerRecord;
import com.ytpm.app.model.YtDyzUser;
import com.ytpm.app.param.AnswerRecordParam;
import com.ytpm.app.view.QuestionListView;
import com.ytpm.dao.qnjz.QNQuestionMapper;
import com.ytpm.dao.qnjz.QNUserMapper;
import com.ytpm.dao.qnmjz.QnmQuestionMapper;
import com.ytpm.dao.qnmjz.QnmUserMapper;
import com.ytpm.general.RepMessage;
import com.ytpm.general.Result;
import com.ytpm.general.ResultTable;
import com.ytpm.general.StatusCode;
import com.ytpm.service.qnjz.QnQuestionService;
import com.ytpm.service.qnmjz.QnmQuestionService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.Objects;

@Service
public class QnmQuestionServiceImpl implements QnmQuestionService {


    @Resource
    private QnmQuestionMapper qnmquestionMapper;
    @Resource
    private QnmUserMapper qnmUserMapper;

    /**
     * 获取题库
     */
    @Override
    public ResultTable<QuestionListView> questionList() {
        return ResultTable.resultTableOk(new PageInfo<QuestionListView>(qnmquestionMapper.questionList("AP_202505210009")));
    }
    /**
     * 回答问题
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<String> answerQuestion(AnswerRecordParam param) {
        YtDyzUser user = qnmUserMapper.selectPrimaryKey(param.getUserId());
        if(Objects.isNull(user)){
            return Result.resultOk(RepMessage.TOKEN_EXPIRE);
        }
        if(!UserStatusEnum.NORMAL.getCode().equals(user.getUserStatus())){
            return new Result<>(StatusCode.ACCESS_ERR,"当前用户处于风控中");
        }
        YtDyzAnswerRecord record = new YtDyzAnswerRecord();
        BeanUtil.copyProperties(param,record);
        record.setRecordId(IdUtil.fastSimpleUUID());
        record.setAnswerTime(new Date());
        qnmquestionMapper.saveAnswerRecord(record);
        qnmUserMapper.subOnePower(param.getUserId());
        YtDyzPowerRecord powerRecord = new YtDyzPowerRecord();
        powerRecord.setUserId(param.getUserId());
        powerRecord.setRecordId(IdUtil.fastSimpleUUID());
        powerRecord.setAddTime(new Date());
        powerRecord.setType(1);
        powerRecord.setRemark("减少体力");
        qnmUserMapper.addPowerRecord(powerRecord);
        return Result.resultOk(RepMessage.SAVE_SUCCESS);
    }
}
