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

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

import com.testor.biz.sys.dict.data.controller.SysDictDataController;
import com.testor.biz.sys.org.model.domain.SysOrg;
import com.testor.biz.sys.org.service.SysOrgService;
import com.testor.module.train.exam.model.domain.TTrainQuestionBank;
import com.testor.module.train.exam.model.domain.TTrainTestQuestions;
import com.testor.module.train.exam.model.dto.TTrainTestQuestionsParam;
import com.testor.module.train.exam.service.TTrainTestQuestionsService;
import com.testor.module.train.paper.model.dto.ReturnTrainPaper;
import com.tongtech.tfw.backend.common.context.ContextUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import lombok.extern.slf4j.Slf4j;
import com.tongtech.tfw.backend.core.helper.StringHelper;
import com.tongtech.tfw.backend.core.helper.ObjectHelper;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RestController;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
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.models.supers.SuperController;
import com.tongtech.tfw.backend.core.helper.TypeHelper;
import com.tongtech.tfw.backend.core.helper.bean.BeanHelper;

import com.testor.module.train.paper.model.domain.TTrainPaper;
import com.testor.module.train.paper.model.dto.TTrainPaperParam;
import com.testor.module.train.paper.model.dto.TTrainPaperDelParam;
import com.testor.module.train.paper.service.TTrainPaperService;

/**
 * 试卷管理——安全教育培训Controller
 *
 * @author testor-framework
 * @date 2022-07-13 15:25:11
 */
@RestController
@RequestMapping("/paper")
@Api(value = "TTrainPaper", tags = "安全培训教育——试卷管理")
@Slf4j
public class TTrainPaperController extends SuperController {
    @Autowired
    private TTrainPaperService tTrainPaperService;
    @Autowired
    private TTrainTestQuestionsService tTrainTestQuestionsService;

    @Autowired
    private SysOrgService orgService;

    @ApiOperation(value = "所选题库 用于下拉框展示 试卷管理——安全教育培训", notes = "添加试卷时所选题库下拉框")
    @GetMapping(value = "/getQuestionBank")
    public BaseResponse<List<TTrainQuestionBank>> getQuestionBank() throws Exception {
        return tTrainPaperService.getQuestionBank();
    }

    @ApiOperation(value = "添加试题-随机组卷 试卷管理——安全教育培训", notes = "默认情况下题的数量传0")
    @PostMapping(value = "/autoAddTestQuestions")
    public BaseResponse<List<TTrainTestQuestionsParam>> autoAddTestQuestions(@RequestBody TTrainTestQuestionsParam tTrainTestQuestionsParam) throws Exception {
        return tTrainTestQuestionsService.autoAddTestQuestions(tTrainTestQuestionsParam);
    }

    @ApiOperation(value = "添加试题-手动组卷 试卷管理——安全教育培训", notes = "")
    @PostMapping(value = "/handAddTestQuestions")
    public BaseResponse<List<TTrainTestQuestions>> handAddTestQuestions(@RequestBody TTrainTestQuestionsParam tTrainTestQuestionsParam) throws Exception {
        return tTrainTestQuestionsService.handAddTestQuestions(tTrainTestQuestionsParam);
    }

    /* Generated Method*/
    @ApiOperation(value = "保存试卷-修改试卷 试卷管理——安全教育培训", notes = "多个试题id (testQuestionsId) 用逗号隔开")
    @PostMapping(value = "/add")
    public BaseResponse<TTrainPaper> addEntity(@RequestBody TTrainPaper addRequest) throws Exception {
        return tTrainPaperService.addEntity(addRequest);
    }

    @ApiOperation(value = "试卷详情 试卷管理——安全教育培训 ", notes = "Get TTrainPaper By Id")
    @GetMapping(value = "/detail")
    public BaseResponse<ReturnTrainPaper> detail(String id) throws Exception {
        return tTrainPaperService.detail(id);
    }

    @ApiOperation(value = "点击编辑获取试卷基本信息详情 试卷管理——安全教育培训 ", notes = "Get TTrainPaper By Id")
    @GetMapping(value = "/get")
    public BaseResponse<TTrainPaperParam> getById(String id) throws Exception {
        return tTrainPaperService.getByIds(id);
    }

    @ApiOperation(value = "修改试卷状态 试卷管理——安全教育培训 ", notes = "Update TTrainPaper By Id")
    @PutMapping(value = "/update")
    public BaseResponse<BizGeneralResponse> updateEntity(@RequestBody TTrainPaper updateRequest) throws Exception {
        return tTrainPaperService.updateEntity(updateRequest);
    }

    @ApiOperation(value = "删除 试卷管理——安全教育培训 ", notes = "delete TTrainPaper By Id")
    @PutMapping(value = "/delete")
    public BaseResponse<BizGeneralResponse> deleteEntity(@RequestBody TTrainPaperDelParam deleteRequest) throws Exception {
        return tTrainPaperService.deleteEntity(deleteRequest);
    }

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

    @ApiOperation(value = "获取 试卷管理——安全教育培训 分页列表", notes = "List TTrainPaper with page")
    @GetMapping(value = "/list")
    public BaseResponse<BaseResponseList<TTrainPaperParam>> listEntity(TTrainPaperParam param) throws Exception {
        BaseResponse<BaseResponseList<TTrainPaperParam>> 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<TTrainPaper> resultPage = new Page<>(page, limit);
        QueryWrapper<TTrainPaper> queryWrapper = this.createQuery(param);
        String orgId = ContextUtils.getLoginUser().getOrgId();

        List<SysOrg> list = orgService.list(new QueryWrapper<SysOrg>().select("org_id")
                .eq("parent_id", orgId).like("parent_ids", orgId).eq("status", "0").eq("is_dept", "0"));
        List<String> collect = list.stream().map(SysOrg::getOrgId).collect(Collectors.toList());
        collect.add(orgId);
        collect.add("32cdbb3a278944f1a83ca40dbcc93c0a");
        queryWrapper.in(collect.size()>0,"org_id",collect);
        Page<TTrainPaper> resultList = tTrainPaperService.page(resultPage, queryWrapper);
        BaseResponseList<TTrainPaperParam> baseResponseList = new BaseResponseList<>();
        List<TTrainPaper> records = resultList.getRecords();
        //todo 参数校验
        if (CollectionUtils.isEmpty(records)) {
            List<TTrainPaperParam> paperParams=new ArrayList<>();
            baseResponseList.setData(paperParams);
            baseResponseList.setTotal(0);
            baseResponse.setData(baseResponseList);
            return baseResponse;
        }
        List<TTrainPaperParam> tTrainPaperParams = converDict(records);
        baseResponseList.setData(tTrainPaperParams);
        baseResponseList.setTotal(resultList.getTotal());
        baseResponse.setData(baseResponseList);
        return baseResponse;
    }

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


    /**
     * 转字典值
     *
     * @param baseResponseList
     * @return
     */
    @Autowired
    private SysDictDataController sysDictDataController;

    private List<TTrainPaperParam> converDict(List<TTrainPaper> baseResponseList) {
        List<TTrainPaperParam> data1 = new ArrayList<>();
        for (TTrainPaper datum : baseResponseList) {
            TTrainPaperParam tTrainDatabase = BeanHelper.beanToBean(datum, TTrainPaperParam.class);
            String secondSubject = tTrainDatabase.getGroupPaperWay();
            if (StringUtils.isBlank(secondSubject)) {
                tTrainDatabase.setDictValue("");
                data1.add(tTrainDatabase);
                continue;
            }
            String subject_level = sysDictDataController.getDictTypeDetail("", "GROUP_PAPER_WAY", secondSubject).getData().getDictValue();
            tTrainDatabase.setDictValue(subject_level);
            data1.add(tTrainDatabase);
        }
        return data1;
    }

    /* Private Methods */

    /**
     * 列表查询条件及查询参数
     */
    private QueryWrapper<TTrainPaper> createQuery(TTrainPaperParam queryParam) {
        QueryWrapper<TTrainPaper> queryWrapper = new QueryWrapper<>();
        String orgId = ContextUtils.getLoginUser().getOrgId();
//        queryWrapper.eq(TTrainPaper.TEST_PAPER_STATUS, "1").or();
//        queryWrapper.eq(TTrainPaper.ORG_ID, orgId);
        queryWrapper.and(new Consumer<QueryWrapper<TTrainPaper>>() {
            @Override
            public void accept(QueryWrapper<TTrainPaper> tTrainPaperQueryWrapper) {
                tTrainPaperQueryWrapper.eq(TTrainPaper.TEST_PAPER_STATUS, "1").or().eq(TTrainPaper.ORG_ID, orgId);
            }
        });
        if (StringHelper.isNotEmpty(queryParam.getTestPaperStatus())) {
            queryWrapper.eq(TTrainPaper.TEST_PAPER_STATUS, queryParam.getTestPaperStatus());
        }
        if (StringHelper.isNotEmpty(queryParam.getTestPaperName())) {
            queryWrapper.like(TTrainPaper.TEST_PAPER_NAME, queryParam.getTestPaperName());
        }
        if (StringHelper.isNotEmpty(queryParam.getGroupPaperWay())) {
            queryWrapper.like(TTrainPaper.GROUP_PAPER_WAY, queryParam.getGroupPaperWay());
        }
        if (StringHelper.isNotEmpty(queryParam.getStatus())) {
            queryWrapper.eq(TTrainPaper.STATUS, queryParam.getStatus());
        } else {
            queryWrapper.ne(TTrainPaper.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(TTrainPaper.UPDATE_DATE);
        }
        return queryWrapper;
    }
}
