package com.qxgmat.controller.admin;

import com.nuliji.tools.*;
import com.qxgmat.data.dao.entity.PreviewPaper;
import com.qxgmat.data.dao.entity.User;
import com.qxgmat.data.relation.entity.UserPreviewPaperRelation;
import com.qxgmat.dto.admin.response.UserPreviewListDto;
import com.qxgmat.service.UsersService;
import com.qxgmat.service.PreviewService;
import com.qxgmat.service.inline.ManagerLogService;
import com.qxgmat.service.UserPaperService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Collection;
import java.util.List;

@RestController("AdminUserPreviewController")
@RequestMapping("/admin/user/preview")
@Api(tags = "用户预习作业接口", description = "用户预习作业", produces = MediaType.APPLICATION_JSON_VALUE)
public class UserPreviewController {
    @Autowired
    private ManagerLogService managerLogService;

    @Autowired
    private UserPaperService userPaperService;

    @Autowired
    private UsersService usersService;

    @Autowired
    private PreviewService previewService;

    @RequestMapping(value = "/list", method = RequestMethod.GET)
    @ApiOperation(value = "预习作业列表", httpMethod = "GET")
    public Response<PageMessage<UserPreviewListDto>> list(
            @RequestParam(required = false, defaultValue = "1") int page,
            @RequestParam(required = false, defaultValue = "100") int size,
            @RequestParam(required = false, defaultValue = "0") int category,
            @RequestParam(required = false) Integer userId,
            @RequestParam(required = false) Integer previewId,
            @RequestParam(required = false) String startTime,
            @RequestParam(required = false) String endTime,
            HttpSession session) {
        PageResult<UserPreviewPaperRelation> p = previewService.listAdmin(page, size, category, userId, previewId, startTime, endTime);

        // 绑定用户
        Collection userIds = Transform.getIds(p, UserPreviewPaperRelation.class, "userId");
        List<User> userList = usersService.select(userIds);
        Transform.combine(p, userList, UserPreviewPaperRelation.class, "userId", "user", User.class, "id");

        // 绑定预习作业
        Collection previewIds = Transform.getIds(p, UserPreviewPaperRelation.class, "moduleId");
        List<PreviewPaper> previewPaperList = previewService.select(previewIds);
        Transform.combine(p, previewPaperList, UserPreviewPaperRelation.class, "moduleId", "preview", PreviewPaper.class, "id");

        List<UserPreviewListDto> pr = Transform.convert(p, UserPreviewListDto.class);

        return ResponseHelp.success(pr, page, size, p.getTotal());
    }
}
