package com.testor.module.train.exam.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.testor.biz.rule.service.SysRuleService;
import com.testor.common.constant.DefaultRule;
import com.testor.module.train.exam.model.domain.TTrainQuestionBank;
import com.testor.module.train.exam.model.dto.TTrainQuestionBankDelParam;
import com.testor.module.train.exam.model.dto.TTrainQuestionBankParam;
import com.testor.module.train.exam.service.TTrainQuestionBankService;
import com.testor.module.train.paper.model.dto.TestQuestionsContent;
import com.testor.module.train.project.model.dto.Exercise;
import com.tongtech.tfw.backend.common.biz.constants.BizConstants;
import com.tongtech.tfw.backend.common.biz.models.BaseResponse;
import com.tongtech.tfw.backend.common.biz.models.BaseResponseList;
import com.tongtech.tfw.backend.common.biz.models.BizGeneralResponse;
import com.tongtech.tfw.backend.common.context.ContextUtils;
import com.tongtech.tfw.backend.common.models.supers.SuperController;
import com.tongtech.tfw.backend.core.helper.ObjectHelper;
import com.tongtech.tfw.backend.core.helper.StringHelper;
import com.tongtech.tfw.backend.core.helper.TypeHelper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;

/**
 * 题库——安全培训教育Controller
 *
 * @author testor-framework
 * @date 2022-07-13 15:19:22
 */
@RestController
@RequestMapping("/bank")
@Api(value = "TTrainQuestionBank", tags = "安全培训教育——题库")
@Slf4j
public class TTrainQuestionBankController extends SuperController {
    @Autowired
    private TTrainQuestionBankService tTrainQuestionBankService;
    @Autowired
    private SysRuleService sysRuleService;

    /* Generated Method*/
    @ApiOperation(value = "新增 题库——安全培训教育", notes = "Add TTrainQuestionBank")
    @PostMapping(value = "/add")
    public BaseResponse<TTrainQuestionBank> addEntity(@RequestBody TTrainQuestionBank addRequest) throws Exception {
        return tTrainQuestionBankService.addEntity(addRequest);
    }

    @ApiOperation(value = "获取 题库——安全培训教育 ", notes = "Get TTrainQuestionBank By Id")
    @GetMapping(value = "/get")
    public BaseResponse<TTrainQuestionBank> getById(String id) throws Exception {
        return tTrainQuestionBankService.getByIds(id);
    }

    @ApiOperation(value = "根据题库id获取所有试题详情 ", notes = "Get TTrainQuestionBank By Id")
    @GetMapping(value = "/getTestQuestions")
    public BaseResponse<BaseResponseList<TestQuestionsContent>> getTestQuestions(Exercise exercise) throws Exception {
        return tTrainQuestionBankService.getTestQuestions(exercise);
    }

    @ApiOperation(value = "加入学习- 题库", notes = "传入题库id")
    @PostMapping(value = "/joinLearnBank")
    public BaseResponse<TTrainQuestionBank> joinLearnBank(@RequestBody TTrainQuestionBank addRequest) throws Exception {
        BaseResponse<TTrainQuestionBank> response = new BaseResponse<>();
        tTrainQuestionBankService.joinLearnBank(addRequest);
        return response;
    }



    @ApiOperation(value = "修改 题库——安全培训教育 ", notes = "Update TTrainQuestionBank By Id")
    @PutMapping(value = "/update")
    public BaseResponse<BizGeneralResponse> updateEntity(@RequestBody TTrainQuestionBank updateRequest) throws Exception {
        return tTrainQuestionBankService.updateEntity(updateRequest);
    }

    @ApiOperation(value = "删除 题库——安全培训教育 ", notes = "delete TTrainQuestionBank By Id")
    @PutMapping(value = "/delete")
    public BaseResponse<BizGeneralResponse> deleteEntity(@RequestBody TTrainQuestionBankDelParam deleteRequest) throws Exception {
        return tTrainQuestionBankService.deleteEntity(deleteRequest);
    }

    //	@ApiOperation(value = "批量删除题库——安全培训教育", notes = "delete TTrainQuestionBank by batch Id")
//	@PutMapping(value = "/batch_delete")
    public BaseResponse<BizGeneralResponse> deleteEntityBatch(
            @RequestBody TTrainQuestionBankDelParam deleteRequest) {
        BaseResponse<BizGeneralResponse> baseResponse = new BaseResponse<>();
        if (ObjectHelper.isNotEmpty(deleteRequest) && (!deleteRequest.getIds().isEmpty())) {
            /* 批量删除 */
            List<TTrainQuestionBank> tTrainQuestionBankList = new ArrayList<>();
            for (String id : deleteRequest.getIds()) {
                TTrainQuestionBank data = new TTrainQuestionBank();
                data.setId(id);
                data.setStatus(BizConstants.STATUS_DELETE);
                tTrainQuestionBankList.add(data);
            }
            boolean result = tTrainQuestionBankService.updateBatchById(tTrainQuestionBankList);
            baseResponse.setData(
                    BizGeneralResponse.builder().result(TypeHelper.castToString(result)).build());
        }
        return baseResponse;
    }

    @ApiOperation(value = "获取 题库——安全培训教育 分页列表", notes = "List TTrainQuestionBank with page")
    @GetMapping(value = "/list")
    public BaseResponse<BaseResponseList<TTrainQuestionBank>> listEntity(TTrainQuestionBankParam param) throws Exception {
        BaseResponse<BaseResponseList<TTrainQuestionBank>> baseResponse = new BaseResponse<>();
        Long page =
                StringHelper.isEmpty(param.getPage()) ? BizConstants.PAGE : Long.valueOf(param.getPage());
        Long limit =
                StringHelper.isEmpty(param.getLimit()) ? BizConstants.LIMIT : Long.valueOf(param.getLimit());
        Page<TTrainQuestionBank> resultPage = new Page<>(page, limit);
        QueryWrapper<TTrainQuestionBank> queryWrapper = this.createQuery(param);
        Page<TTrainQuestionBank> resultList = tTrainQuestionBankService.page(resultPage, queryWrapper);
        BaseResponseList<TTrainQuestionBank> baseResponseList = new BaseResponseList<>();
        // 数据过滤
        String orgId = ContextUtils.getLoginUser().getOrgId();
        List<TTrainQuestionBank> records = resultList.getRecords();
        baseResponseList.setData(records);
        baseResponseList.setTotal(resultList.getTotal());
        baseResponse.setData(baseResponseList);
        return baseResponse;
    }

    //	@ApiOperation(value = "获取 题库——安全培训教育 列表", notes = "List TTrainQuestionBank all")
//	@GetMapping(value = "/datas")
    public BaseResponse<BaseResponseList<TTrainQuestionBank>> listAllEntity(TTrainQuestionBankParam param) {
        BaseResponse<BaseResponseList<TTrainQuestionBank>> baseResponse = new BaseResponse<>();
        QueryWrapper<TTrainQuestionBank> queryWrapper = this.createQuery(param);
        List<TTrainQuestionBank> resultList = tTrainQuestionBankService.list(queryWrapper);
        BaseResponseList<TTrainQuestionBank> baseResponseList = new BaseResponseList<>();
        baseResponseList.setData(resultList);
        baseResponseList.setTotal(resultList.size());
        baseResponse.setData(baseResponseList);
        return baseResponse;
    }

    /* Private Methods */

    /**
     * 列表查询条件及查询参数
     */
    private QueryWrapper<TTrainQuestionBank> createQuery(TTrainQuestionBankParam queryParam) {
        QueryWrapper<TTrainQuestionBank> queryWrapper = new QueryWrapper<>();
        String rule = sysRuleService.dataRuleScope(DefaultRule.DEPT_ALL.name());
        if (StringUtils.isNotEmpty(queryParam.getQuestionBankStatus())) {
            queryWrapper.eq(TTrainQuestionBank.QUESTION_BANK_STATUS, queryParam.getQuestionBankStatus());
        }
        String orgId = ContextUtils.getLoginUser().getOrgId();
//        queryWrapper.and(queryWrapper.eq(TTrainQuestionBank.QUESTION_BANK_STATUS, "1").or().eq(TTrainQuestionBank.ORG_ID, orgId));
        queryWrapper.and(new Consumer<QueryWrapper<TTrainQuestionBank>>() {
            @Override
            public void accept(QueryWrapper<TTrainQuestionBank> tTrainQuestionBankQueryWrapper) {
                tTrainQuestionBankQueryWrapper.eq(TTrainQuestionBank.QUESTION_BANK_STATUS, "1").or().eq(TTrainQuestionBank.ORG_ID, orgId);
            }
        });
        if (StringUtils.isNotEmpty(rule)) {
            queryWrapper.apply(rule);
        }
        if (StringHelper.isNotEmpty(queryParam.getQuestionBankName())) {
            queryWrapper.like(TTrainQuestionBank.QUESTION_BANK_NAME, queryParam.getQuestionBankName());
        }
        if (StringHelper.isNotEmpty(queryParam.getQuestionBankStatus())) {
            queryWrapper.eq(TTrainQuestionBank.QUESTION_BANK_STATUS, queryParam.getQuestionBankStatus());
        }
        if (StringHelper.isNotEmpty(queryParam.getQuestionBankSource())) {
            queryWrapper.eq(TTrainQuestionBank.QUESTION_BANK_SOURCE, queryParam.getQuestionBankSource());
        }
        if (StringHelper.isNotEmpty(queryParam.getStatus())) {
            queryWrapper.eq(TTrainQuestionBank.STATUS, queryParam.getStatus());
        } else {
            queryWrapper.ne(TTrainQuestionBank.STATUS, BizConstants.STATUS_DELETE);
        }
        if (StringHelper.isNotEmpty(queryParam.getOrderBy())) {
            if (StringHelper.isNotEmpty(queryParam.getOrderType())
                    && BizConstants.ASC.equals(queryParam.getOrderType())) {
                queryWrapper.orderByAsc(queryParam.getOrderBy());
            } else {
                queryWrapper.orderByDesc(queryParam.getOrderBy());
            }
        } else {
            queryWrapper.orderByDesc(TTrainQuestionBank.UPDATE_DATE);
        }
        return queryWrapper;
    }
}
