package com.qxgmat.controller.admin;

import com.github.pagehelper.Page;
import com.nuliji.tools.PageMessage;
import com.nuliji.tools.Response;
import com.nuliji.tools.ResponseHelp;
import com.nuliji.tools.Transform;
import com.qxgmat.data.constants.enums.status.AskStatus;
import com.qxgmat.data.constants.enums.status.DirectionStatus;
import com.qxgmat.data.constants.enums.user.AskTarget;
import com.qxgmat.data.constants.enums.user.MoneyRange;
import com.qxgmat.data.dao.entity.*;
import com.qxgmat.dto.admin.extend.*;
import com.qxgmat.dto.admin.request.UserAskDto;
import com.qxgmat.dto.admin.response.UserAskDetailDto;
import com.qxgmat.dto.admin.response.UserAskListDto;
import com.qxgmat.help.ShiroHelp;
import com.qxgmat.service.ManagerService;
import com.qxgmat.service.UsersService;
import com.qxgmat.service.inline.ManagerLogService;
import com.qxgmat.service.inline.QuestionNoService;
import com.qxgmat.service.inline.QuestionService;
import com.qxgmat.service.inline.UserAskQuestionService;
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.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

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

@RestController("AdminUserAskController")
@RequestMapping("/admin/user/ask")
@Api(tags = "用户提问接口", description = "用户提问相关", produces = MediaType.APPLICATION_JSON_VALUE)
public class UserAskController {
    @Autowired
    private ManagerLogService managerLogService;
    @Autowired
    private ShiroHelp shiroHelp;

    @Autowired
    private UserAskQuestionService userAskQuestionService;

    @Autowired
    private QuestionService questionService;

    @Autowired
    private QuestionNoService questionNoService;

    @Autowired
    private UsersService usersService;

    @Autowired
    private ManagerService managerService;

    @RequestMapping(value = "/edit", method = RequestMethod.PUT)
    @ApiOperation(value = "修改提问信息", httpMethod = "PUT")
    public Response<Boolean> edit(@RequestBody @Validated UserAskDto dto, HttpServletRequest request) {
        UserAskQuestion entity = Transform.dtoToEntity(dto);
        UserAskQuestion in = userAskQuestionService.get(entity.getId());
        // 调整回答
        if(!entity.getAnswer().isEmpty() || !in.getAnswer().equals(entity.getAnswer())){
            entity.setAnswerTime(new Date());
            entity.setAnswerStatus(AskStatus.ANSWER.index);
            Manager manager = shiroHelp.getLoginManager();
            entity.setManagerId(manager.getId());
        }

        entity = userAskQuestionService.edit(entity);

        if (dto.getOther() !=null && dto.getOther().length > 0){
            // 更新回答排序
            userAskQuestionService.updateOrder(dto.getOther());
        }

        managerLogService.log(request);
        return ResponseHelp.success(true);
    }

    @RequestMapping(value = "/detail", method = RequestMethod.GET)
    @ApiOperation(value = "提问详情", httpMethod = "GET")
    public Response<UserAskDetailDto> detail(@RequestParam int id, HttpServletRequest request) {
        UserAskQuestion entity = userAskQuestionService.get(id);
        UserAskDetailDto dto = Transform.convert(entity, UserAskDetailDto.class);

        if (entity.getManagerId() != null && entity.getManagerId() > 0){
            Manager manager = managerService.get(entity.getManagerId());
            if (manager != null)
                dto.setManager(Transform.convert(manager, ManagerExtendDto.class));
        }

        User user = usersService.get(entity.getUserId());
        dto.setUser(Transform.convert(user, UserExtendDto.class));

        Question question = questionService.get(entity.getQuestionId());
        dto.setQuestion(Transform.convert(question, QuestionExtendDto.class));

        QuestionNo questionNo = questionNoService.get(entity.getQuestionNoId());
        dto.setQuestionNo(Transform.convert(questionNo, QuestionNoExtendDto.class));

        // 所有回答
        List<UserAskQuestion> userAskList = userAskQuestionService.listByQuestion(entity.getQuestionId(), true);
        dto.setOthers(Transform.convert(userAskList, UserAskExtendDto.class));
        return ResponseHelp.success(dto);
    }

    @RequestMapping(value = "/list", method = RequestMethod.GET)
    @ApiOperation(value = "提问列表", httpMethod = "GET")
    public Response<PageMessage<UserAskListDto>> list(
            @RequestParam(required = false, defaultValue = "1") int page,
            @RequestParam(required = false, defaultValue = "100") int size,
            @RequestParam(required = false) String type,
            @RequestParam(required = false) Integer category,
            @RequestParam(required = false) Number userId,
            @RequestParam(required = false) Number questionNoId,
            @RequestParam(required = false) String target,
            @RequestParam(required = false) Integer status,
            @RequestParam(required = false) Integer showStatus,
            @RequestParam(required = false) Integer moneyRang,
            @RequestParam(required = false, defaultValue = "id") String order,
            @RequestParam(required = false, defaultValue = "desc") String direction,
            HttpSession session) {
        Page<UserAskQuestion> p = userAskQuestionService.listWithUser(page, size, type, category, userId, questionNoId, AskTarget.ValueOf(target), AskStatus.ValueOf(status), showStatus, MoneyRange.ValueOf(moneyRang), order, DirectionStatus.ValueOf(direction));
        List<UserAskListDto> pr = Transform.convert(p, UserAskListDto.class);

        // 绑定题目
        Collection questionIds = Transform.getIds(p, UserAskQuestion.class, "questionId");
        List<Question> questionList = questionService.select(questionIds);
        Transform.combine(pr, questionList, UserAskListDto.class, "questionId", "question", Question.class, "id", QuestionExtendDto.class);

        // 绑定题目编号
        Collection questionNoIds = Transform.getIds(p, UserAskQuestion.class, "questionNoId");
        List<QuestionNo> questionNoList = questionNoService.select(questionNoIds);
        Transform.combine(pr, questionNoList, UserAskListDto.class, "questionNoId", "questionNo", QuestionNo.class, "id", QuestionNoExtendDto.class);

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

        // 绑定管理员
        Collection managerIds = Transform.getIds(p, UserAskQuestion.class, "managerId");
        List<Manager> managerList = managerService.select(managerIds);
        Transform.combine(pr, managerList, UserAskListDto.class, "managerId", "manager", Manager.class, "id", ManagerExtendDto.class);

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