package com.ruoyi.applet.contoller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.applet.pojo.dto.AppletAnswerSubmitBo;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.JsonUtils;
import com.ruoyi.model.domain.*;
import com.ruoyi.model.mapper.AppletAnswerBaseMapper;
import com.ruoyi.model.mapper.AppletAnswerTrainMapper;
import com.ruoyi.model.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Api(description = "伴宠师-伴宠师考核")
@RestController
@RequestMapping("/applet/examination")
public class ApiAppletExaminationController {

    //题目信息
    @Autowired
    private IAppletQuestionService appletQuestionService;

    //题目答案信息
    @Autowired
    private IAppletAnswerService appletAnswerService;

    //宠物类型
    @Autowired
    private IAppletPetTypeService appletPetTypeService;

    //专业执照
    @Autowired
    private IAppletLicenseService appletLicenseService;

    //用户基本考核答案
    @Autowired
    private IAppletAnswerBaseService appletAnswerBaseService;

    //用户基本考核答案
    @Autowired
    private AppletAnswerBaseMapper appletAnswerBaseMapper;

    //用户培训考核答案
    @Autowired
    private IAppletAnswerTrainService appletAnswerTrainService;

    //用户培训考核答案
    @Autowired
    private AppletAnswerTrainMapper appletAnswerTrainMapper;

    @Autowired
    private IAppUsersService appUsersService;

    @Autowired
    private IAppletUsersTeacherService appletUsersTeacherService;

    @ApiOperation("伴宠师工作台-题目列表数据查询")
    @GetMapping("/questionList")
    public AjaxResult questionList(AppletQuestion question){
        List<AppletQuestion> questionList = appletQuestionService.selectAppletQuestionList(question);
        for (AppletQuestion appletQuestion:questionList){
            AppletAnswer appletAnswer = new AppletAnswer();
            appletAnswer.setQuestionId(appletQuestion.getId());
            List<AppletAnswer> answerList = appletAnswerService.selectAppletAnswerList(appletAnswer);
            appletQuestion.setAnswerList(answerList);
        }
        return AjaxResult.success("题目列表数据",questionList);
    }

//    @ApiOperation("伴宠师工作台-根据题目id查询题目答案")
//    @GetMapping("/insertUser")
//    public AjaxResult answerListByQuestionId(long questionId){
//        AppletAnswer appletAnswer = new AppletAnswer();
//        appletAnswer.setQuestionId(questionId);
//        List<AppletAnswer> answerList = appletAnswerService.selectAppletAnswerList(appletAnswer);
//        return AjaxResult.success("答案列表数据",answerList);
//    }

    @ApiOperation("伴宠师工作台-查询宠物类型列表")
    @GetMapping("/petTypeList")
    public AjaxResult petTypeList(AppletPetType appletPetType){
        List<AppletPetType> petTypeList = appletPetTypeService.selectAppletPetTypeList(appletPetType);
        return AjaxResult.success("宠物类型列表数据",petTypeList);
    }

    @ApiOperation("伴宠师工作台-查询专业执照列表")
    @GetMapping("/licenseList")
    public AjaxResult licenseList(AppletLicense appletLicense){
        List<AppletLicense> licenseList = appletLicenseService.selectAppletLicenseList(appletLicense);
        return AjaxResult.success("专业执照列表数据",licenseList);
    }

//    @ApiOperation("伴宠师工作台-查询用户基本考核答案列表")
//    @PostMapping("/answerBaseList")
//    public AjaxResult answerBaseList(@RequestBody AppletAnswerBase answerBase){
//        List<AppletAnswerBase> answerBaseList = appletAnswerBaseService.selectAppletAnswerBaseList(answerBase);
//        return AjaxResult.success("用户基本考核答案列表数据",answerBaseList);
//    }



    //查询用户考核状态
//    @ApiOperation("伴宠师工作台-查询用户考核状态")
//    @GetMapping("/answerStatus")
//    public AjaxResult answerStatus(Long userId){
//        /**
//         * 返回值 0 进入伴宠师资料页面，补充资料
//         * 返回值 1 进入基本考核
//         * 返回值 2 进入培训考核
//         * 返回值 3 进入审核中页面
//         * 返回值 4 进入审核失败页面
//         * 返回值 5 进入审核成功页面
//         */
//
//        AppletAnswerBase answerBase = new AppletAnswerBase();
//        answerBase.setUserId(userId);
//        List<AppletAnswerBase> answerBaseList = appletAnswerBaseService.selectAppletAnswerBaseList(answerBase);
//        if(answerBaseList.size() > 0){
//            return AjaxResult.success(1);//进入伴宠师资料页面，补充资料
//        }
//
//        return AjaxResult.error("用户基本考核未完成");
//    }

    //查询基本考核是否完成
//    @ApiOperation("伴宠师工作台-查询用户基本考核是否完成【废弃】")
//    @GetMapping("/answeBaseIsFinish")
//    public AjaxResult answeBaseIsFinish(Long userId){
//        AppletAnswerBase answerBase = new AppletAnswerBase();
//        answerBase.setUserId(userId);
//        List<AppletAnswerBase> answerBaseList = appletAnswerBaseService.selectAppletAnswerBaseList(answerBase);
//        if(answerBaseList.size() > 0){
//            return AjaxResult.success("用户基本考核已完成");
//        }
//        return AjaxResult.error("用户基本考核未完成");
//    }

    //查询基本考核是否完成
    @ApiOperation("伴宠师工作台-查询用户基本考核是否完成")
    @GetMapping("/answeBaseIsFinishV2")
    public AjaxResult answeBaseIsFinishV2(Long userId){

        List<Long> ids = appletQuestionService.lambdaQuery()
                .eq(AppletQuestion::getType, "基本")
                .select(AppletQuestion::getId)
                .list()
                .stream().map(n -> n.getId())
                .collect(Collectors.toList());

        Integer count = appletAnswerBaseService.lambdaQuery()
                .in(AppletAnswerBase::getQuestionId, ids)
                .eq(AppletAnswerBase::getUserId, userId)
                .count();

        Integer count1 = appletAnswerTrainService.lambdaQuery()
                .in(AppletAnswerTrain::getQuestionId, ids)
                .eq(AppletAnswerTrain::getUserId, userId)
                .count();

        if((count1 + count) > 0){
            return AjaxResult.success(1);
        }
        return AjaxResult.success(0);
    }


    //查询培训考核是否完成
//    @ApiOperation("伴宠师工作台-查询用户培训考核是否完成【废弃】")
//    @GetMapping("/answeTrainIsFinish")
//    public AjaxResult answeTrainIsFinish(Long userId){
//        AppletAnswerTrain answerTrain = new AppletAnswerTrain();
//        answerTrain.setUserId(userId);
//        List<AppletAnswerTrain> answerTrainList = appletAnswerTrainService.selectAppletAnswerTrainList(answerTrain);
//        if(answerTrainList.size() > 0){
//            return AjaxResult.success("用户培训考核已完成");
//        }
//        return AjaxResult.error("用户培训考核未完成");
//    }
    //查询培训考核是否完成
    @ApiOperation("伴宠师工作台-查询用户培训考核是否完成")
    @GetMapping("/answeTrainIsFinishV2")
    public AjaxResult answeTrainIsFinishV2(Long userId){


        List<Long> ids = appletQuestionService.lambdaQuery()
                .eq(AppletQuestion::getType, "培训")
                .select(AppletQuestion::getId)
                .list()
                .stream().map(n -> n.getId())
                .collect(Collectors.toList());

        Integer count = appletAnswerBaseService.lambdaQuery()
                .in(AppletAnswerBase::getQuestionId, ids)
                .eq(AppletAnswerBase::getUserId, userId)
                .count();

        Integer count1 = appletAnswerTrainService.lambdaQuery()
                .in(AppletAnswerTrain::getQuestionId, ids)
                .eq(AppletAnswerTrain::getUserId, userId)
                .count();

        if((count1 + count) > 0){
            return AjaxResult.success(1);
        }
        return AjaxResult.success(0);
    }




//    @ApiOperation("伴宠师工作台-根据题目id查询基本考核答案")
//    @GetMapping("/answeBaseByQuestionId")
//    public AjaxResult answeBaseByQuestionId(Long questionId, Long userId){
//        AppletAnswerBase answerBase = new AppletAnswerBase();
//        answerBase.setQuestionId(questionId);
//        answerBase.setUserId(userId);
//        List<AppletAnswerBase> answerBaseList = appletAnswerBaseService.selectAppletAnswerBaseList(answerBase);
//
//        for (AppletAnswerBase appletAnswerBase : answerBaseList) {
//            AppletAnswer answer = appletAnswerService.selectAppletAnswerById(appletAnswerBase.getAnswerId());
//            appletAnswerBase.setAnswer(answer);
//        }
//
//        return AjaxResult.success("用户基本考核答案列表数据",answerBaseList);
//    }

//    @ApiOperation("伴宠师工作台-添加用户基本考核答案")
//    @PostMapping("/addBaseAnswer")
//    public AjaxResult addBaseAnswer(@RequestBody AppletAnswerBase answerBase){
//
//        if(answerBase.getUserId() == null){
//            return AjaxResult.error("userId用户信息标识不能为空");
//        }
//        if(answerBase.getQuestionId() == null){
//            return AjaxResult.error("questionId标识不能为空");
//        }
////        //选删除之前的答案，再去添加新的
//        LambdaQueryWrapper<AppletAnswerBase> qw = Wrappers.<AppletAnswerBase>lambdaQuery()
//                .eq(AppletAnswerBase::getUserId, answerBase.getUserId())
//                .eq(AppletAnswerBase::getQuestionId, answerBase.getQuestionId());
//
//        appletAnswerBaseService.remove(qw);
//
//        return toAjax(appletAnswerBaseService.insertAppletAnswerBase(answerBase));
//    }


    @ApiOperation("伴宠师工作台-添加用户基本考核答案V2")
    @PostMapping("/addBaseAnswerV2")
    @Transactional
    public AjaxResult addBaseAnswerV2(@RequestBody AppletAnswerSubmitBo answerSubmitBo){

        Long userId = null;

        if (answerSubmitBo.getAnswerBase() != null && answerSubmitBo.getAnswerBase().size() > 0){
            List<Long> ids = new ArrayList<>();
            for (AppletAnswerBase appletAnswerBase : answerSubmitBo.getAnswerBase()) {
                if(appletAnswerBase.getUserId() == null){
                    return AjaxResult.error("userId用户信息标识不能为空");
                }
                if(appletAnswerBase.getQuestionId() == null){
                    return AjaxResult.error("questionId标识不能为空");
                }
                ids.add(appletAnswerBase.getQuestionId());
                userId = appletAnswerBase.getUserId();
            }

            //选删除之前的答案，再去添加新的
            LambdaQueryWrapper<AppletAnswerBase> qw = Wrappers.<AppletAnswerBase>lambdaQuery()
                    .in(AppletAnswerBase::getQuestionId, ids)
                    .eq(AppletAnswerBase::getUserId, userId);
            appletAnswerBaseService.remove(qw);

            appletAnswerBaseService.saveBatch(answerSubmitBo.getAnswerBase());

        }
        if (answerSubmitBo.getAnswerTrains() != null && answerSubmitBo.getAnswerTrains().size() > 0) {
            List<Long> ids = new ArrayList<>();
            for (AppletAnswerTrain appletAnswerTrain : answerSubmitBo.getAnswerTrains()) {
                if (appletAnswerTrain.getUserId() == null) {
                    return AjaxResult.error("userId用户信息标识不能为空");
                }
                if (appletAnswerTrain.getQuestionId() == null) {
                    return AjaxResult.error("questionId标识不能为空");
                }
                ids.add(appletAnswerTrain.getQuestionId());
                userId = appletAnswerTrain.getUserId();
            }

            //选删除之前的答案，再去添加新的
            LambdaQueryWrapper<AppletAnswerTrain> qwt = Wrappers.<AppletAnswerTrain>lambdaQuery()
                    .eq(AppletAnswerTrain::getUserId, userId)
                    .in(AppletAnswerTrain::getQuestionId, ids);
            appletAnswerTrainMapper.delete(qwt);

            appletAnswerTrainService.saveBatch(answerSubmitBo.getAnswerTrains());

        }

        AppletUsersTeacher byId = appletUsersTeacherService.lambdaQuery()
                .eq(AppletUsersTeacher::getUserId, userId).one();

        //累计考试次数
        if (ObjectUtils.isNotEmpty(byId) && answerSubmitBo.getType() == 0){
            Integer examNumber = byId.getExamNumber() == null ? 0 : byId.getExamNumber();
            byId.setExamNumber(examNumber + 1);
            byId.setExamTime(LocalDateTime.now());
            appletUsersTeacherService.updateById(byId);
        }


        return toAjax(true);
    }

    @ApiOperation("伴宠师工作台-查询考试结果对象")
    @GetMapping("/getAnswerBuildData")
    public AjaxResult getAnswerBuildData(Long userId){
        AppletUsersTeacher teacher = appletUsersTeacherService.selectAppletUsersTeacherByUserId(userId);
        appletUsersTeacherService.buildData(teacher);
        return AjaxResult.success(teacher);
    }


//    @ApiOperation("伴宠师工作台-查询用户培训考核答案列表")
//    @PostMapping("/answeTrainList")
//    public AjaxResult answeTrainList(@RequestBody AppletAnswerTrain answerTrain){
//        List<AppletAnswerTrain> answerTrainList = appletAnswerTrainService.selectAppletAnswerTrainList(answerTrain);
//
//        for (AppletAnswerTrain appletAnswerTrain : answerTrainList) {
//            AppletQuestion question = appletQuestionService.selectAppletQuestionById(appletAnswerTrain.getQuestionId());
//            appletAnswerTrain.setQuestion(question);
//        }
//
//        return AjaxResult.success("用户培训考核答案列表数据",answerTrainList);
//    }







//    @ApiOperation("伴宠师工作台-根据题目id查询培训考核答案")
//    @GetMapping("/answeTrainByQuestionId")
//    public AjaxResult answeTrainByQuestionId(Long questionId, Long userId){
//        AppletAnswerTrain answerTrain = new AppletAnswerTrain();
//        answerTrain.setQuestionId(questionId);
//        answerTrain.setUserId(userId);
//        List<AppletAnswerTrain> answerTrainList = appletAnswerTrainService.selectAppletAnswerTrainList(answerTrain);
//
//        return AjaxResult.success("用户培训考核答案列表数据",answerTrainList);
//    }

//    @ApiOperation("伴宠师工作台-添加用户培训考核答案")
//    @PostMapping("/addTrainAnswer")
//    public AjaxResult addTrainAnswer(@RequestBody AppletAnswerTrain answerTrain){
//        if(answerTrain.getUserId() == null){
//            return AjaxResult.error("userId用户信息标识不能为空");
//        }
//        if(answerTrain.getQuestionId() == null){
//            return AjaxResult.error("questionId标识不能为空");
//        }
//
////        //选删除之前的答案，再去添加新的
//        LambdaQueryWrapper<AppletAnswerTrain> qw = Wrappers.<AppletAnswerTrain>lambdaQuery()
//                .eq(AppletAnswerTrain::getUserId, answerTrain.getUserId())
//                .eq(AppletAnswerTrain::getQuestionId, answerTrain.getQuestionId());
//
//        appletAnswerTrainMapper.delete(qw);
//
//        return toAjax(appletAnswerTrainService.insertAppletAnswerTrain(answerTrain));
//    }


    //查询培训考核是否完成
    @ApiOperation("伴宠师工作台-成为伴宠师")
    @GetMapping("/appletUsersTeacher")
    public AjaxResult appletUsersTeacher(Long userId){
        //审核通过，修改用户表
        AppUsers appUsers = appUsersService.selectAppUsersByUserId(userId);
        //用户不存在
        if(appUsers == null){
            return AjaxResult.error("用户不存在");
        }
        appUsers.setUserBcs(1);
        appUsers.setUserBcsRole(1);
        appUsersService.updateAppUsers(appUsers);
        return AjaxResult.success(0);
    }


    @ApiOperation("伴宠师工作台-重新考试")
    @GetMapping("/retakeExam")
    public AjaxResult retakeExam(Long userId, Integer type){

        List<Long> qid = appletQuestionService.lambdaQuery()
                .eq(AppletQuestion::getType, "培训")
                .select(AppletQuestion::getId)
                .list().stream().map(n -> n.getId())
                .collect(Collectors.toList());

        if (type == 0){//清除所有

            LambdaQueryWrapper<AppletAnswerBase> qw1 = Wrappers.<AppletAnswerBase>lambdaQuery()
                    .eq(AppletAnswerBase::getUserId, userId);

            appletAnswerBaseMapper.delete(qw1);

            LambdaQueryWrapper<AppletAnswerTrain> qw2 = Wrappers.<AppletAnswerTrain>lambdaQuery()
                    .eq(AppletAnswerTrain::getUserId, userId);

            appletAnswerTrainMapper.delete(qw2);

        }else if (qid.size() > 0){//清除培训

            LambdaQueryWrapper<AppletAnswerBase> qw1 = Wrappers.<AppletAnswerBase>lambdaQuery()
                    .in(AppletAnswerBase::getQuestionId, qid)
                    .eq(AppletAnswerBase::getUserId, userId);

            appletAnswerBaseMapper.delete(qw1);

            LambdaQueryWrapper<AppletAnswerTrain> qw2 = Wrappers.<AppletAnswerTrain>lambdaQuery()
                    .in(AppletAnswerTrain::getQuestionId, qid)
                    .eq(AppletAnswerTrain::getUserId, userId);

            appletAnswerTrainMapper.delete(qw2);
        }

        AppletUsersTeacher one = appletUsersTeacherService.lambdaQuery()
                .eq(AppletUsersTeacher::getUserId, userId)
                .one();
        if (ObjectUtils.isNotEmpty(one)){
            one.setStatus(0L);
            one.setReason("");
            appletUsersTeacherService.updateById(one);
        }

        return AjaxResult.success();
    }

    protected AjaxResult toAjax(int rows) {
        return rows > 0 ? AjaxResult.success() : AjaxResult.error();
    }
    protected AjaxResult toAjax(boolean b) {
        return b ? AjaxResult.success() : AjaxResult.error();
    }

}
