package com.ytpm.question.service.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.general.RepMessage;
import com.ytpm.general.Result;
import com.ytpm.general.ResultTable;
import com.ytpm.general.StatusCode;
import com.ytpm.question.dao.AppUserMapper;
import com.ytpm.question.dao.QuestionMapper;
import com.ytpm.question.service.QuestionService;
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 QuestionServiceImpl implements QuestionService {

    @Resource
    private QuestionMapper questionMapper;
    @Resource
    private AppUserMapper appUserMapper;

    /**
     * 获取题库
     */
    @Override
    public ResultTable<QuestionListView> questionList() {
        return ResultTable.resultTableOk(new PageInfo<>(questionMapper.questionList("AP_202505210009")));
    }

    /**
     * 回答问题
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<String> answerQuestion(AnswerRecordParam param) {
        YtDyzUser user = appUserMapper.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, "当前用户处于风控中");
        }
        if (user.getPower() == null || user.getPower() <= 0) {
            return new Result<>(StatusCode.ACCESS_ERR, "用户体力不足，无法答题");
        }
        YtDyzAnswerRecord record = new YtDyzAnswerRecord();
        BeanUtil.copyProperties(param, record);
        record.setRecordId(IdUtil.fastSimpleUUID());
        record.setAnswerTime(new Date());
        questionMapper.saveAnswerRecord(record);
        appUserMapper.subOnePower(param.getUserId());
        YtDyzPowerRecord powerRecord = new YtDyzPowerRecord();
        powerRecord.setUserId(param.getUserId());
        powerRecord.setRecordId(IdUtil.fastSimpleUUID());
        powerRecord.setAddTime(new Date());
        powerRecord.setType(1);
        powerRecord.setRemark("减少体力");
        appUserMapper.addPowerRecord(powerRecord);
        return Result.resultOk(RepMessage.SAVE_SUCCESS);
    }
}
