package cn.com.ty.lift.ud.question.controller;

import cn.com.ty.lift.ud.chat.mapper.entity.LiftCaseEntity;
import cn.com.ty.lift.ud.chat.service.ILiftCaseService;
import cn.com.ty.lift.ud.common.BaseController;
import cn.com.ty.lift.ud.common.DelReq;
import cn.com.ty.lift.ud.common.NotExamineDto;
import cn.com.ty.lift.ud.question.controller.query.QuestionBankQuery;
import cn.com.ty.lift.ud.question.mapper.entity.GiveMoneyDto;
import cn.com.ty.lift.ud.question.mapper.entity.QuestionBankEntity;
import cn.com.ty.lift.ud.question.mapper.entity.QuestionCollectDto;
import cn.com.ty.lift.ud.question.service.IQuestionBankService;
import cn.com.ty.lift.ud.searchIndex.service.ISearchIndexService;
import cn.com.ty.lift.ud.userCollect.service.IUserCollectService;
import cn.com.xwy.boot.web.dto.RestResponse;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.IService;
import com.mysql.cj.util.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * 题库 API
 *
 * @author Xson
 * @date 2020-04-25
 */
@Api(tags = "题库 API- 小陶")
@RestController
@RequestMapping("/api/questionBanks")
public class QuestionBankController extends BaseController<QuestionBankEntity, QuestionBankQuery> {

    private final Logger log = LoggerFactory.getLogger(QuestionBankController.class);
    @Autowired
    private IQuestionBankService questionBankService;
    @Autowired
    private ISearchIndexService iSearchIndexService;
    @Autowired
    private IUserCollectService iUserCollectService;

    @Autowired
    private ILiftCaseService iLiftCaseService;

    @Override
    protected IService<QuestionBankEntity> getService() {
        return questionBankService;
    }

    @ApiOperation(value = "批量上架")
    @PostMapping("/useBath")
    public RestResponse useBath(@RequestBody DelReq ids) {
        return questionBankService.updateByIds(ids.getIds(), 1);
    }

    @ApiOperation(value = "批量下架")
    @PostMapping("/noUseBath")
    public RestResponse noUseBath(@RequestBody DelReq ids) {
        return questionBankService.updateByIds(ids.getIds(), 0);
    }

    @ApiOperation(value = "置顶")
    @PostMapping("/toUp/{id}")
    public RestResponse toUp(@PathVariable("id") Long id) {
        questionBankService.toUpOrDown(id,1);
        return RestResponse.success(null, "置顶成功");
    }

    @ApiOperation(value = "取消置顶")
    @PostMapping("/toDown/{id}")
    public RestResponse toDown(@PathVariable("id") Long id) {
        questionBankService.toUpOrDown(id,0);
        return RestResponse.success(null, "取消成功");
    }


    @ApiOperation(value = "审批 1:通过 2:驳回")
    @PostMapping("/examine")
    public RestResponse examine(@RequestBody NotExamineDto neDto ) {
        if(null == neDto.getId()){
            return RestResponse.fail("题目不能为空");
        }
        if(null == neDto.getExamineFlag()){
            return RestResponse.fail("审批类型不能为空");
        }
        return questionBankService.examineById(neDto);
    }

    /**
     * 重写条件查询的方法
     * @param request
     * @return
     */
    @ApiOperation(value = "列表分页查询")
    @PostMapping("/query-page")
    @Override
    public RestResponse getCondition(@RequestBody QuestionBankQuery request) {
        if(request.getPageNum() < 1){
            return RestResponse.fail("error", "当前页不能小于1");
        }
        if(StringUtils.isNullOrEmpty(request.getPlatform())  ){
            return RestResponse.fail("平台不能为空");
        }
        return questionBankService.selectByExample(request);
    }



    /**
     * 题库管理新增方法重写
     * @param qbEntity
     * @return
     */
    @ApiOperation(value = "新增")
    @PostMapping("/insert")
    @Override
    public RestResponse<QuestionBankEntity> create(@RequestBody QuestionBankEntity qbEntity) {

        if(null == qbEntity.getExpert()){
            return RestResponse.fail("专家不能为空");
        }
        if(null == qbEntity.getBrandId()){
            return RestResponse.fail("品牌ID不能为空");
        }
        if(null == qbEntity.getTitle()){
            return RestResponse.fail("标题不能为空");
        }
        //app端诊单ID 前端传，web端这个不存在，且专家默认为系统  userId = 1
        if(null == qbEntity.getLiftCaseId() && qbEntity.getExpert() != 1){
                return RestResponse.fail("诊单不能为空");
        }

        return questionBankService.modify(qbEntity);
    }


    @ApiOperation(value = "点赞-app")
    @PostMapping("/like/{userId}/{questionId}")
    public RestResponse like(@PathVariable("questionId") Long questionId,@PathVariable("userId") Long userId) {
        questionBankService.like(questionId,userId);
        return RestResponse.success(null, "点赞成功");
    }

    @ApiOperation(value = "取消点赞-app")
    @PostMapping("/noLike/{userId}/{questionId}")
    public RestResponse noLike(@PathVariable("questionId") Long questionId,@PathVariable("userId") Long userId) {
        questionBankService.noLike(questionId,userId);
        return RestResponse.success(null, "取消成功");
    }

    @ApiOperation(value = "收藏-app")
    @PostMapping("/collect/{userId}/{questionId}")
    public RestResponse collect(@PathVariable("questionId") Long questionId,@PathVariable("userId") Long userId) {
        questionBankService.collect(questionId,userId);
        return RestResponse.success(null, "收藏成功");
    }

    @ApiOperation(value = "取消收藏-app")
    @PostMapping("/noCollect/{userId}/{questionId}")
    public RestResponse noCollect(@PathVariable("questionId") Long questionId,@PathVariable("userId") Long userId) {
        questionBankService.noCollect(questionId,userId);
        return RestResponse.success(null, "取消成功");
    }

    @ApiOperation(value = "浏览-app")
    @PostMapping("/see/{userId}/{questionId}")
    public RestResponse see(@PathVariable("questionId") Long questionId,@PathVariable("userId") Long userId) {
        questionBankService.see(questionId,userId);
        return RestResponse.success(null, "浏览成功");
    }

    @ApiOperation(value = "打赏-app")
    @PostMapping("/giveMoney")
    public RestResponse giveMoney(@RequestBody GiveMoneyDto giveMoney) {

        questionBankService.giveMoney(giveMoney);
        return RestResponse.success(null, "打赏成功");
    }

    @GetMapping("/query/{id}")
    @ApiOperation(value = "根据id查详情")
    @Override
    public RestResponse get(@PathVariable("id") Long id) {
        QuestionBankEntity entity = questionBankService.selectById(id);
        if(entity != null){
            return RestResponse.success(entity, "查询成功");
        }else{
            return RestResponse.success(null, "暂无数据");
        }
    }

    @GetMapping("/query-app/{questionId}/{userId}")
    @ApiOperation(value = "查询题目详情  - app")
    public RestResponse getInfo(@PathVariable("questionId") Long questionId,@PathVariable("userId") Long userId) {
        QuestionBankEntity entity = questionBankService.selectInfo(questionId,userId);
        if(entity != null){
            return RestResponse.success(entity, "查询成功");
        }else{
            return RestResponse.success(null, "暂无数据");
        }
    }


    /**
     * 重写修改的方法
     * @param request
     * @return
     */
    @PutMapping("/update")
    @ApiOperation(value = "修改")
    @Override
    public RestResponse update(@RequestBody QuestionBankEntity request) {
        Long id = request.getId();
        QuestionBankEntity questionBankEntity = questionBankService.selectById(id);
        if(questionBankEntity.getExamineFlag() == 2){
            //驳回状态，修改的时候才会变成 待审核
            request.setExamineFlag(0);
        }
        boolean updateFlag = getService().updateById(request);
        QuestionBankEntity e = getService().getById(request.getId());
        if (updateFlag) {
            //修改成功，在全文索引表中插入数据，搜索的字段仅限于 title
//            if(null != request.getTitle() && null != request.getId()){
//                iSearchIndexService.updateSearchIndex(request.getTitle(),1,request.getId());
//            }
            return RestResponse.success(null, "修改成功");
        }else {
            return RestResponse.fail("修改失败");
        }
    }

    /**
     * 重写根据id删除的方法
     * @param req
     * @return
     */
    @DeleteMapping("/delete")
    @ApiOperation(value = "根据id删除")
    @Override
    public RestResponse delete(@RequestBody DelReq req) {
        boolean deleteFlag = getService().removeById(req.getId());
        if (deleteFlag) {
            //删除 user_collect 我的收藏的内容
            iUserCollectService.deleteByTypeAndDataId(req.getId(),1);
            //删除成功，在全文索引表中删除数据
            List<Long> ids = new ArrayList<>();
            ids.add(req.getId());
            iSearchIndexService.deleteSearchIndex(1,ids);
            return RestResponse.success(null, "删除成功");
        }else {
            return RestResponse.fail("删除失败");
        }
    }

    /**
     * 重写根据id批量删除的方法
     * @param req
     * @return
     */
    @DeleteMapping("/delete-batch")
    @ApiOperation(value = "批量删除")
    @Override
    public RestResponse deleteBath(@RequestBody DelReq req) {
        boolean deleteFlag = getService().removeByIds(req.getIds());
        if (deleteFlag) {
            for(Long id : req.getIds()){
                //删除 user_collect 我的收藏的内容
                iUserCollectService.deleteByTypeAndDataId(id,1);
            }
            //删除成功，在全文索引表中删除数据
            iSearchIndexService.deleteSearchIndex(1,req.getIds());
            return RestResponse.success(null, "删除成功");
        }else {
            return RestResponse.fail("删除失败");
        }
    }


    /**
     * 问题归档
     * @param qbEntity
     * @return
     */
    @ApiOperation(value = "问题归档")
    @PostMapping("/question-collect")
    public RestResponse questionCollect(@RequestBody QuestionCollectDto qbEntity) {
        if(null == qbEntity.getTitle()){
            return RestResponse.fail("标题不能为空");
        }
        if(null == qbEntity.getLiftCaseId()){
            return RestResponse.fail("诊单不能为空");
        }

        return questionBankService.questionCollect(qbEntity);
    }

}