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

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

import com.testor.biz.rule.service.SysRuleService;
import com.testor.common.constant.DefaultRule;
import com.testor.module.train.database.model.domain.TTrainDatabase;
import com.testor.module.train.exam.model.domain.TTrainQuestionBank;
import com.tongtech.tfw.backend.common.context.ContextUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.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.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.testor.module.train.course.model.domain.TTrainCourse;
import com.testor.module.train.course.model.dto.TTrainCourseParam;
import com.testor.module.train.course.model.dto.TTrainCourseDelParam;
import com.testor.module.train.course.service.TTrainCourseService;

/**
 * 课程管理——安全培训教育Controller
 *
 * @author testor-framework
 * @date 2022-07-25 18:06:04
 */
@RestController
@RequestMapping("/course")
@Api(value = "TTrainCourse", tags = "安全培训教育——课程管理")
@Slf4j
public class TTrainCourseController extends SuperController {
    @Autowired
    private TTrainCourseService tTrainCourseService;
    @Autowired
    private SysRuleService sysRuleService;

    /* Generated Method*/
    @ApiOperation(value = "新增或修改 课程管理——安全培训教育", notes = "Add TTrainCourse")
    @PostMapping(value = "/add")
    public BaseResponse<TTrainCourse> addEntity(@RequestBody TTrainCourseParam addRequest) throws Exception {
        return tTrainCourseService.addEntity(addRequest);
    }

    @ApiOperation(value = "加入学习", notes = "传入课程id")
    @PostMapping(value = "/joinLearn")
    public BaseResponse<TTrainCourse> joinLearn(@RequestBody TTrainCourse addRequest) throws Exception {
        BaseResponse<TTrainCourse> response = new BaseResponse<>();
        tTrainCourseService.joinLearn(addRequest);
        return response;
    }

    @ApiOperation(value = "获取 课程管理——安全培训教育 ", notes = "Get TTrainCourse By Id")
    @GetMapping(value = "/get")
    public BaseResponse<TTrainCourseParam> getById(String id) {
        return tTrainCourseService.getByIds(id);
    }

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

    @ApiOperation(value = "选择资料", notes = "根据字典值获取资料")
    @GetMapping(value = "/selectData")
    public BaseResponse<List<TTrainDatabase>> selectData(String dictKey) throws Exception {
        return tTrainCourseService.selectData(dictKey);
    }

    @ApiOperation(value = "模糊搜索资料", notes = "根据资料名称模糊搜索资料进行添加")
    @GetMapping(value = "/fuzzySearch")
    public BaseResponse<List<TTrainDatabase>> fuzzySearch(String dataName) throws Exception {
        return tTrainCourseService.fuzzySearch(dataName);
    }

    @ApiOperation(value = "删除 课程管理——安全培训教育 ", notes = "delete TTrainCourse By Id")
    @PutMapping(value = "/delete")
    public BaseResponse<BizGeneralResponse> deleteEntity(@RequestBody TTrainCourseDelParam deleteRequest) {
        return tTrainCourseService.deleteEntity(deleteRequest);
    }

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

    @ApiOperation(value = "获取 课程管理——安全培训教育 分页列表", notes = "List TTrainCourse with page")
    @GetMapping(value = "/list")
    public BaseResponse<BaseResponseList<TTrainCourse>> listEntity(TTrainCourseParam param) {
        BaseResponse<BaseResponseList<TTrainCourse>> 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<TTrainCourse> resultPage = new Page<>(page, limit);
        QueryWrapper<TTrainCourse> queryWrapper = this.createQuery(param);
        Page<TTrainCourse> resultList = tTrainCourseService.page(resultPage, queryWrapper);
        BaseResponseList<TTrainCourse> baseResponseList = new BaseResponseList<>();
        baseResponseList.setData(resultList.getRecords());
        baseResponseList.setTotal(resultList.getTotal());
        baseResponse.setData(baseResponseList);
        return baseResponse;
    }

    //    @ApiOperation(value = "获取 课程管理——安全培训教育 列表", notes = "List TTrainCourse all")
//    @GetMapping(value = "/datas")
    public BaseResponse<BaseResponseList<TTrainCourse>> listAllEntity(TTrainCourseParam param) {
        BaseResponse<BaseResponseList<TTrainCourse>> baseResponse = new BaseResponse<>();
        // TODO 根据需求修改查询条件及查询参数
        QueryWrapper<TTrainCourse> queryWrapper = this.createQuery(param);
        List<TTrainCourse> resultList = tTrainCourseService.list(queryWrapper);
        BaseResponseList<TTrainCourse> baseResponseList = new BaseResponseList<>();
        baseResponseList.setData(resultList);
        baseResponseList.setTotal(resultList.size());
        baseResponse.setData(baseResponseList);
        return baseResponse;
    }

    /* Private Methods */

    /**
     * 列表查询条件及查询参数
     */
    private QueryWrapper<TTrainCourse> createQuery(TTrainCourseParam queryParam) {
        QueryWrapper<TTrainCourse> queryWrapper = new QueryWrapper<>();
        String rule = sysRuleService.dataRuleScope(DefaultRule.DEPT_ALL.name());
        if (StringUtils.isNotEmpty(rule)) {
            queryWrapper.apply(rule);
        }
        String orgId = ContextUtils.getLoginUser().getOrgId();
        queryWrapper.and(new Consumer<QueryWrapper<TTrainCourse>>() {
            @Override
            public void accept(QueryWrapper<TTrainCourse> tTrainQuestionBankQueryWrapper) {
                tTrainQuestionBankQueryWrapper.eq(TTrainCourse.COURSE_STATUS, "1").or().eq(TTrainQuestionBank.ORG_ID, orgId);
            }
        });
        if (StringHelper.isNotEmpty(queryParam.getOrgLevel())) {
            if (!"0".equals(queryParam.getOrgLevel())) {
                queryWrapper.eq(TTrainCourse.ORG_LEVEL, queryParam.getOrgLevel());
            }
        }
        if (StringHelper.isNotEmpty(queryParam.getCourseName())) {
            queryWrapper.like(TTrainCourse.COURSE_NAME, queryParam.getCourseName());
        }
        if (StringHelper.isNotEmpty(queryParam.getCourseStatus())) {
            queryWrapper.eq(TTrainCourse.COURSE_STATUS, queryParam.getCourseStatus());
        }
        if (StringHelper.isNotEmpty(queryParam.getStatus())) {
            queryWrapper.eq(TTrainCourse.STATUS, queryParam.getStatus());
        } else {
            queryWrapper.ne(TTrainCourse.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(TTrainCourse.CREATE_DATE);
        }
        return queryWrapper;
    }
}
