package com.cirle.scientific.questionnaire.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.cirle.scientific.questionnaire.dto.SubmitAnswerDTO;
import com.cirle.scientific.questionnaire.entity.QuestionnaireEntity;
import com.cirle.scientific.questionnaire.exception.AnswerSubmitException;
import com.cirle.scientific.questionnaire.exception.QuestionnaireNotFoundException;
import com.cirle.scientific.questionnaire.service.AnswerService;
import com.cirle.scientific.questionnaire.service.QuestionnaireService;
import com.cirle.scientific.questionnaire.valueobject.GetQuestionnaireVO;
import com.cirle.scientific.questionnaire.valueobject.GetQuestionnairesVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;

import java.net.URI;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

@Api(tags = "问卷APIs")
@SuppressWarnings("unused")
@RestController
public class QuestionnaireController {

    @Autowired
    private QuestionnaireService questionnaireService;

    @Autowired
    private AnswerService answerService;

    @ApiOperation("获取问卷集合")
    @GetMapping("/questionnaires")
    public GetQuestionnairesVO queryQuestionnaires() {
        // 构建结果对象
        GetQuestionnairesVO getQuestionnairesVO = new GetQuestionnairesVO();
        // 查询所有问卷列表
        List<QuestionnaireEntity> questionnaireEntities = questionnaireService.queryQuestionnaires();
        // 封装值对象
        getQuestionnairesVO.parseAll(questionnaireEntities);
        // 返回结果对象
        return getQuestionnairesVO;
    }

    @ApiOperation("获取问卷")
    @GetMapping("/questionnaires/{id}")
    public GetQuestionnaireVO queryQuestionnaire(@ApiParam(name = "id", value = "问卷ID") @PathVariable String id) throws QuestionnaireNotFoundException {
        // 获取问卷
        QuestionnaireEntity questionnaireEntity = questionnaireService.getQuestionnaire(id);
        // 构建结果对象
        GetQuestionnaireVO getQuestionnaireVO = new GetQuestionnaireVO();
        // 封装值对象
        getQuestionnaireVO.parse(questionnaireEntity);
        // 返回结果对象
        return getQuestionnaireVO;
    }

    @ApiOperation("获取66种常见病问卷")
    @GetMapping("/questionnaires/66-common-disease/optimization")
    public Map<String, Object> queryQuestionnaire() throws QuestionnaireNotFoundException {
        // 定义66种常见病问卷ID
        final String _66CommonDiseaseQuestionnaireId = "af449c5b-0965-43bd-852c-a2434892122b";
        // 定义节点名
        final String nodeName = "questionGroups";
        // 获取66种常见病问卷
        GetQuestionnaireVO getQuestionnaireVO = queryQuestionnaire(_66CommonDiseaseQuestionnaireId);
        // 将问卷信息转换为Map动态数据类型：序列化为JSON字符串再反序列化为Map
        String json = JSON.toJSONString(getQuestionnaireVO);
        Map<String, Object> questionnaireData = JSON.parseObject(json, new TypeReference<Map<String, Object>>() {
        });
        // 移除并获取questionGroups节点
        List<Object> questionGroups = new ArrayList<>((List<?>) questionnaireData.remove(nodeName));
        // 封装一级子节点
        List<Map<String, Object>> dynamicNode = new ArrayList<>();
        Map<String, Object> temp1 = new LinkedHashMap<>();
        temp1.put("name", "一、内科（26种）");
        temp1.put(nodeName, questionGroups.subList(0, 26));
        Map<String, Object> temp2 = new LinkedHashMap<>();
        temp2.put("name", "二、外科（17种）");
        temp2.put(nodeName, questionGroups.subList(26, 43));
        Map<String, Object> temp3 = new LinkedHashMap<>();
        temp3.put("name", "三、妇产科（7种）");
        temp3.put(nodeName, questionGroups.subList(43, 50));
        Map<String, Object> temp4 = new LinkedHashMap<>();
        temp4.put("name", "四、眼、耳鼻咽喉科（10种）");
        temp4.put(nodeName, questionGroups.subList(50, 60));
        Map<String, Object> temp5 = new LinkedHashMap<>();
        temp5.put("name", "五、口腔科（6种）");
        temp5.put(nodeName, questionGroups.subList(60, questionGroups.size()));
        dynamicNode.add(temp1);
        dynamicNode.add(temp2);
        dynamicNode.add(temp3);
        dynamicNode.add(temp4);
        dynamicNode.add(temp5);
        // 将子节点添加到问卷数据中
        questionnaireData.put("dynamicNode", dynamicNode);
        // 返回结果
        return questionnaireData;
    }

    @ApiOperation("提交问卷答案")
    @PostMapping("/questionnaires/{id}/answers")
    public ResponseEntity<Void> submitAnswer(@ApiParam(name = "id", value = "问卷ID") @PathVariable String id, @RequestBody SubmitAnswerDTO submitAnswerDTO) throws AnswerSubmitException {
        // 异步处理标识
        boolean async = !Boolean.FALSE.equals(submitAnswerDTO.getAsync());
        // 提交答案
        answerService.submitAnswer(id, submitAnswerDTO, async);
        // 异步返回202
        if (async) {
            return ResponseEntity.accepted().build();
        }
        // 构建新添资源URI地址（和当前请求地址一致）
        URI resourceUri = ServletUriComponentsBuilder.fromCurrentRequest().buildAndExpand().toUri();
        // 同步返回201
        return ResponseEntity.created(resourceUri).build();
    }

}
