package com.ytpm.service.xjlrl.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.xjlrl.XjlrlQuestionMapper;
import com.ytpm.dao.xjlrl.XjlrlUserMapper;
import com.ytpm.general.RepMessage;
import com.ytpm.general.Result;
import com.ytpm.general.ResultTable;
import com.ytpm.general.StatusCode;
import com.ytpm.service.xjlrl.XjlrlQuestionService;
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 XjlrlQuestionServiceImpl implements XjlrlQuestionService {


    @Resource
    private XjlrlQuestionMapper xjlquestionMapper;
    @Resource
    private XjlrlUserMapper xjlUserMapper;

    /**
     * 获取题库
     */
    @Override
    public ResultTable<QuestionListView> questionList() {
        return ResultTable.resultTableOk(new PageInfo<QuestionListView>(xjlquestionMapper.questionList("AP_202505210009")));
    }
    /**
     * 回答问题
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<String> answerQuestion(AnswerRecordParam param) {
        YtDyzUser user = xjlUserMapper.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());
        xjlquestionMapper.saveAnswerRecord(record);
        xjlUserMapper.subOnePower(param.getUserId());
        YtDyzPowerRecord powerRecord = new YtDyzPowerRecord();
        powerRecord.setUserId(param.getUserId());
        powerRecord.setRecordId(IdUtil.fastSimpleUUID());
        powerRecord.setAddTime(new Date());
        powerRecord.setType(1);
        powerRecord.setRemark("减少体力");
        xjlUserMapper.addPowerRecord(powerRecord);
        return Result.resultOk(RepMessage.SAVE_SUCCESS);
    }
}
