package com.ywt.outpatient.controllers;

import com.ywt.biz.common.enums.SexEnum;
import com.ywt.biz.common.util.StringHelper;
import com.ywt.gapi.Result;
import com.ywt.gapi.ResultCode;
import com.ywt.gapi.nfyy.*;
import com.ywt.gapi.nfyy.Doctor;
import com.ywt.gapi.system.*;
import com.ywt.outpatient.core.BaseResponse;
import com.ywt.outpatient.core.Constant;
import org.apache.dubbo.config.annotation.DubboReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping({"/yiDa"})
public class YiDaController {
    private static Logger logger = LoggerFactory.getLogger(YiDaController.class);

    @DubboReference
    private YiDaService yiDaServiceBlockingStub;

    @DubboReference
    private SystemService systemServiceBlockingStub;

    @DubboReference
    private NfyyService nfyyServiceBlockingStub;

    @RequestMapping({"/recommeTaiheRegisterControllernd"})
    public @ResponseBody
    BaseResponse recommend(@RequestParam(name = "age") int age,
                           @RequestParam(name = "sex") int sex,
                           @RequestParam(name = "desc") String desc) {
        BaseResponse response = new BaseResponse();

        if (age < 1 || age > 130) {
            return response.failed(BaseResponse.PARAMETER_ERROR, "请输入正确的年龄");
        }

        if (sex != SexEnum.Male.getValue() && sex != SexEnum.Female.getValue()) {
            return response.failed(BaseResponse.PARAMETER_ERROR, "性别不能为空");
        }

        if (StringHelper.isNullOrWhiteSpace(desc)) {
            return response.failed(BaseResponse.PARAMETER_ERROR, "病情描述不能为空");
        }

        if (desc.length() > 100) {
            return response.failed(BaseResponse.PARAMETER_ERROR, "病情描述字数不能超过100");
        }

        try {
            InferenceRequest inferenceRequest = InferenceRequest.newBuilder()
                    .setAge(age)
                    .setSex(sex)
                    .setContent(desc)
                    .build();
            InferenceResponse inferenceResponse = yiDaServiceBlockingStub.inference(inferenceRequest);

            if (inferenceResponse.getCode() == ResultCode.SUCCEED_VALUE) {
                if (inferenceResponse.getDepartmentList() != null && inferenceResponse.getDepartmentList().size() > 0) {
                    YiDaDepartment department = inferenceResponse.getDepartmentList().get(0);

                    Map<String, Object> data = new HashMap<>();
                    data.put("deptCode", department.getId());
                    data.put("deptName", department.getName());

                    GetDeptByYiDaCodeRequest getDeptByYiDaCodeRequest = GetDeptByYiDaCodeRequest.newBuilder()
                            .setYiDaCode(department.getId())
                            .build();
                    GetDeptByYiDaCodeResponse getDeptByYiDaCodeResponse = systemServiceBlockingStub.getDeptByYiDaCode(getDeptByYiDaCodeRequest);
                    Result result = getDeptByYiDaCodeResponse.getResult();

                    if (result.getCode() == ResultCode.SUCCEED) {
                        Dept dept = getDeptByYiDaCodeResponse.getDept();

                        GetDoctorListRequest getDoctorListRequest = GetDoctorListRequest.newBuilder()
                                .setDepartmentCode(dept.getDeptCode())
                                .setDoctorName("")
                                .build();
                        GetDoctorListResponse getDoctorListResponse = nfyyServiceBlockingStub.getDoctorList(getDoctorListRequest);

                        if (getDoctorListResponse.getCode() == ResultCode.SUCCEED_VALUE &&
                                getDoctorListResponse.getDoctorGroupList() != null &&
                                getDoctorListResponse.getDoctorGroupList().size() > 0) {
                            DoctorGroup group = getDoctorListResponse.getDoctorGroupList().get(0);

                            int i = 0;
                            List<String> doctorCodes = new LinkedList<>();
                            List<Doctor> doctorList = new LinkedList<>();

                            for (Doctor doctor : group.getDoctorsList()) {
                                if (i > 1) {
                                    break;
                                }

                                doctorList.add(doctor);
                                doctorCodes.add(doctor.getDoctorCode());
                                i++;
                            }

                            GetYiDaDoctorCodeRequest getYiDaDoctorCodeRequest = GetYiDaDoctorCodeRequest.newBuilder()
                                    .addAllDoctorId(doctorCodes)
                                    .build();
                            GetYiDaDoctorCodeResponse getYiDaDoctorCodeResponse = systemServiceBlockingStub.getYiDaDoctorCode(getYiDaDoctorCodeRequest);

                            if (getYiDaDoctorCodeResponse.getResult().getCode() == ResultCode.SUCCEED) {
                                StatsDoctorRequest statsDoctorRequest = StatsDoctorRequest.newBuilder()
                                        .setDepartmentId(dept.getDeptCode())
                                        .setTopDiseaseCount(6)
                                        .setSize(2)
                                        .setStart(0)
                                        .addAllDoctorIds(getYiDaDoctorCodeResponse.getDoctorCodeList().stream().map(YiDaDoctorCode::getYiDaDoctorCode).collect(Collectors.toList()))
                                        .build();
                                StatsDoctorResponse statsDoctorResponse = yiDaServiceBlockingStub.statsDoctor(statsDoctorRequest);

                                if (statsDoctorResponse.getCode() == ResultCode.SUCCEED_VALUE && statsDoctorResponse.getItemList().size() > 0) {
                                    List<Map<String, Object>> lst = new LinkedList<>();
                                    for (YiDaDoctorStatsData yiDaDoctorStatsData : statsDoctorResponse.getItemList()) {
                                        Map<String, Object> map = new HashMap<>();
                                        map.put("doctorCode", yiDaDoctorStatsData.getDoctorId());
                                        map.put("totalTreat", yiDaDoctorStatsData.getTotalTreat());

//                                        Doctor doctor = doctorList.stream()
//                                                .filter(p -> p.getDoctorCode().equals(yiDaDoctorStatsData.getDoctorId()))
//                                                .limit(1L).collect(Collectors.toList()).get(0);
                                        Doctor doctor = doctorList.get(0);//测试

                                        map.put("doctorName", doctor.getDoctorName());
                                        map.put("avatar", doctor.getImageUrl());
                                        map.put("title", doctor.getDoctorTitle());
                                        map.put("hospital", "南方医科大学南方医院");
                                        map.put("specialty", doctor.getDoctorSpec());
                                        map.put("dept", department.getName());

                                        List<Map<String, Object>> diseaseList = new LinkedList<>();

                                        if (yiDaDoctorStatsData.getDiseaseList() != null) {
                                            for (YiDaDoctorStatsData.Disease disease : yiDaDoctorStatsData.getDiseaseList()) {
                                                Map<String, Object> hashMap = new HashMap<>();
                                                hashMap.put("id", disease.getId());
                                                hashMap.put("name", disease.getName());
                                                hashMap.put("treatCount", disease.getTreatCount());
                                                diseaseList.add(hashMap);
                                            }
                                        }

                                        map.put("diseaseList", diseaseList);

                                        lst.add(map);
                                    }

                                    data.put("doctorList", lst);
                                }
                            }
                        }
                    }

                    return response.succeed(data);
                }
            }

            return response.failed(BaseResponse.APP_ERROR, "数据暂时无法处理数据，请稍后重试");
        } catch (Exception e) {
            logger.error("recommend():{}", e.getMessage(), e);
            return response.failed(BaseResponse.APP_EXCEPTION, Constant.ERROR_PROMPT);
        }
    }


}
