package com.ytpm.nofeeds.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.nofeeds.dao.AppUserMapper;
import com.ytpm.nofeeds.dao.QuestionMapper;
import com.ytpm.nofeeds.service.QuestionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.Objects;

@Service
public class QuestionServiceImpl implements QuestionService {

    @Autowired
    private QuestionMapper questionMapper;
    @Autowired
    private AppUserMapper appUserMapper;

    /**
     * 获取题库
     */
    @Override
    public ResultTable<QuestionListView> questionList() {
        return ResultTable.resultTableOk(new PageInfo<QuestionListView>(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,"当前用户处于风控中");
        }
        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);
    }
}
