package com.fs.aiTongueApi.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.fs.aiTongueApi.config.AiTongueConfig;
import com.fs.aiTongueApi.domain.AITongueResult;
import com.fs.aiTongueApi.domain.QueryAiTongue;
import com.fs.aiTongueApi.domain.QueryQuanXi;
import com.fs.aiTongueApi.domain.enums.TongueTypeEnums;
import com.fs.aiTongueApi.domain.inner.*;
import com.fs.aiTongueApi.service.AiTongueService;
import com.fs.common.utils.uuid.UUID;
import com.fs.his.domain.FsHealthTongue;
import com.fs.his.service.IFsHealthTongueService;
import lombok.extern.slf4j.Slf4j;
import org.apache.hc.core5.net.URIBuilder;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.InputStream;
import java.net.URI;
import java.net.URL;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Optional;

@Slf4j
@Service
public class AiTongueServiceImpl implements AiTongueService {

    @Autowired
    private IFsHealthTongueService tongueService;

    @Override
    public AITongueResult<TongueData> getHistoryTongue(QueryAiTongue queryAiTongue) {
        queryAiTongue.setAppkey(AiTongueConfig.appKey);
        String result = sendPost(AiTongueConfig.getFaceHistoryByIDUrl, queryAiTongue);
        System.out.println(result);
        AITongueResult<TongueData> aiTongueResult = JSON.parseObject(result, new TypeReference<AITongueResult<TongueData>>(){});
        return aiTongueResult;
    }

    @Override
    public AITongueResult<ConfidenceData> checkTongue(String url) {
        String s="";
        try {
            HttpClient httpClient = HttpClients.createDefault();
            HttpPost httpPost = new HttpPost(AiTongueConfig.checkTongue);
            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            URL urlItem = new URL(url);
            InputStream inputStream =urlItem.openStream();
            // 添加文件或表单参数
            builder.addBinaryBody("file", inputStream, ContentType.DEFAULT_BINARY, "图片.jpg");

            builder.addTextBody("appkey", AiTongueConfig.appKey);
            HttpEntity multipart = builder.build();
            httpPost.setEntity(multipart);
            // 执行请求
            HttpResponse response = httpClient.execute(httpPost);
            String responseBody = EntityUtils.toString(response.getEntity());
            System.out.println(responseBody);
            s=responseBody;
        } catch (Exception e) {
            e.printStackTrace();
        }

        AITongueResult<ConfidenceData> aiTongueResult = JSON.parseObject(s, new TypeReference<AITongueResult<ConfidenceData>>(){});
        return aiTongueResult;
    }

    @Override
    public AITongueResult<TongueData> quanXiTongue(QueryQuanXi queryQuanXi) {
        String s="";
        try {
            HttpClient httpClient = HttpClients.createDefault();
            HttpPost httpPost = new HttpPost(AiTongueConfig.quanxiUrl);
            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            URL urlItem = new URL(queryQuanXi.getFile());
            InputStream inputStream =urlItem.openStream();
            // 添加文件或表单参数
            builder.addBinaryBody("file", inputStream, ContentType.DEFAULT_BINARY, UUID.randomUUID().toString()+".jpg");

            builder.addTextBody("age", queryQuanXi.getAge(), ContentType.create("text/plain", Charset.forName("UTF-8")));
            builder.addTextBody("male", queryQuanXi.getMale(), ContentType.create("text/plain", Charset.forName("UTF-8")));
            builder.addTextBody("appkey", AiTongueConfig.appKey);
            if (queryQuanXi.getIsYuejin()!=null){
                builder.addTextBody("isYuejin", queryQuanXi.getIsYuejin(), ContentType.create("text/plain", Charset.forName("UTF-8")));
            }
            if (queryQuanXi.getName()!=null){
                builder.addTextBody("name", queryQuanXi.getName(), ContentType.create("text/plain", Charset.forName("UTF-8")));
            }
            if (queryQuanXi.getDesease()!=null){
                builder.addTextBody("desease", queryQuanXi.getDesease(), ContentType.create("text/plain", Charset.forName("UTF-8")));
            }

            HttpEntity multipart = builder.build();
            httpPost.setEntity(multipart);

            // 执行请求
            HttpResponse response = httpClient.execute(httpPost);
            String responseBody = EntityUtils.toString(response.getEntity());
            System.out.println(responseBody);
            s=responseBody;
        } catch (Exception e) {
            e.printStackTrace();
        }

        AITongueResult<TongueData> aiTongueResult = JSON.parseObject(s, new TypeReference<AITongueResult<TongueData>>(){});
        return aiTongueResult;
    }

    @Override
    public AITongueResult<FsHealthTongue> newCheckTongue(String url) {
        String s="";
        try {
            HttpClient httpClient = HttpClients.createDefault();
            HttpPost httpPost = new HttpPost(AiTongueConfig.newCheckTongue);
            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            URL urlItem = new URL(url);
            InputStream inputStream =urlItem.openStream();
            // 添加文件或表单参数
            builder.addBinaryBody("file", inputStream, ContentType.DEFAULT_BINARY, "图片.jpg");

            HttpEntity multipart = builder.build();
            httpPost.setEntity(multipart);
            // 执行请求
            HttpResponse response = httpClient.execute(httpPost);
            String responseBody = EntityUtils.toString(response.getEntity());
            log.info(responseBody);
            s=responseBody;

            AITongueResult<List<List<ConfidenceDataNew>>> aiTongueResult = JSON.parseObject(s, new TypeReference<AITongueResult<List<List<ConfidenceDataNew>>>>(){});
            List<List<ConfidenceDataNew>> data = aiTongueResult.getData();
            FsHealthTongue healthTongue = new FsHealthTongue();
            if (data != null && !data.isEmpty()){
                String boTaiDesc =  "舌未见剥落提示脏腑气充足,胃阴正常,气阴平衡。";
                String chiHenDesc = "舌未见齿痕表示脾气正常。";
                String lieWenDesc = "舌未见裂纹表示脏腑津液正常。";
                String houDu;
                TongueInfo tongueInfo = new TongueInfo();
                for (int i = 0; i < 4; i++) {
                    List<ConfidenceDataNew> confidenceDataNews = data.get(i);
                    if (confidenceDataNews != null && !confidenceDataNews.isEmpty()){
                        Optional<ConfidenceDataNew> oldestPerson = confidenceDataNews.stream()
                                .max(Comparator.comparingDouble(p -> Double.parseDouble(p.getVal())));
                        ConfidenceDataNew confidenceDataNew = oldestPerson.get();

                        healthTongue.setTongueUrl(url);
                        if(i == 0){
                            switch (confidenceDataNew.getLabel()){
                                case "01":
                                    healthTongue.setShemianName("鲜红舌");
                                    break;
                                case "02":
                                    healthTongue.setShemianName("淡白舌");
                                    break;
                                case "03":
                                    healthTongue.setShemianName("淡红舌");
                                    break;
                                case "04":
                                    healthTongue.setShemianName("紫舌");
                                    break;
                            }
                            String sheZhi = TongueTypeEnums.fromCategoryAndCode("SheZhi", confidenceDataNew.getLabel());
                            healthTongue.setShemianDesc(sheZhi);
                            //设置舌质
                            tongueInfo.setShemianName(healthTongue.getShemianName());
                        }
                        if(i == 1){
                            switch (confidenceDataNew.getLabel()){
                                case "01":
                                    healthTongue.setTaiseName("黄苔");
                                    break;
                                case "02":
                                    healthTongue.setTaiseName("灰苔");
                                    break;
                                case "03":
                                    healthTongue.setTaiseName("白苔");
                                    break;
                            }
                            String taiSe = TongueTypeEnums.fromCategoryAndCode("TaiSe", confidenceDataNew.getLabel());
                            healthTongue.setTaiseDesc(taiSe);
                            //设置苔色
                            tongueInfo.setTaiseName(healthTongue.getTaiseName());
                        }
                        if(i == 2){
                            switch (confidenceDataNew.getLabel()){
                                case "01":
                                    healthTongue.setBotai(1L);
                                    String boTai = TongueTypeEnums.fromCategoryAndCode("Xing", "01");
                                    healthTongue.setBotaiDesc(boTai);
                                    //设置是否剥脱 0正常 1剥脱
                                    tongueInfo.setBotai(1);

                                    healthTongue.setChihen(0L);
                                    healthTongue.setChihenDesc(chiHenDesc);
                                    healthTongue.setLiewen(0);
                                    healthTongue.setLiewenDesc(lieWenDesc);
                                    break;
                                case "02":
                                    healthTongue.setBotai(0L);
                                    healthTongue.setBotaiDesc(boTaiDesc);
                                    //设置是否剥脱 0正常 1剥脱
                                    tongueInfo.setBotai(0);

                                    healthTongue.setChihen(1L);
                                    String chiHen = TongueTypeEnums.fromCategoryAndCode("Xing", "02");
                                    healthTongue.setChihenDesc(chiHen);
                                    healthTongue.setLiewen(0);
                                    healthTongue.setLiewenDesc(lieWenDesc);
                                    break;
                                case "03":
                                    healthTongue.setBotai(0L);
                                    healthTongue.setBotaiDesc(boTaiDesc);
                                    //设置是否剥脱 0正常 1剥脱
                                    tongueInfo.setBotai(0);

                                    healthTongue.setChihen(0L);
                                    healthTongue.setChihenDesc(chiHenDesc);
                                    healthTongue.setLiewen(1);
                                    String lieWen = TongueTypeEnums.fromCategoryAndCode("Xing", "03");
                                    healthTongue.setLiewenDesc(lieWen);
                                    break;
                            }
                        }
                        if(i == 3){
                            switch (confidenceDataNew.getLabel()){
                                case "01":
                                    //厚
                                    houDu = TongueTypeEnums.fromCategoryAndCode("HouDu", "01");
                                    break;
                                default:
                                    //薄
                                    houDu = TongueTypeEnums.fromCategoryAndCode("HouDu", "02");
                                    break;
                            }
                            //设置厚度
                            tongueInfo.setHoudu(houDu);
                        }

                    }else{
                        //形状相关的为空就将这几个值置为0(表示正常)
                        if(i == 2){
                            healthTongue.setBotai(0L);
                            healthTongue.setBotaiDesc(boTaiDesc);
                            //设置是否剥脱 0正常 1剥脱
                            tongueInfo.setBotai(0);

                            healthTongue.setChihen(0L);
                            healthTongue.setChihenDesc(chiHenDesc);
                            healthTongue.setLiewen(0);
                            healthTongue.setLiewenDesc(lieWenDesc);
                        }
                    }
                }

                TongueInfo fastTongueInfo = tongueService.selectFsTongueInfo(tongueInfo);
                if(fastTongueInfo != null && fastTongueInfo.getTypeName() != null){
                    healthTongue.setTypeName(fastTongueInfo.getTypeName());
                    healthTongue.setTypeJson(fastTongueInfo.getTypeJson());
                    return getAiTongueResult(healthTongue,"40001","ok");
                }
                return getAiTongueResult(healthTongue,"40003","未检测到舌头，请按照要求查询拍照检测");
            }
            return getAiTongueResult(healthTongue,"40003","未能从服务器获取结果，请稍后再试");
        } catch (Exception e) {
            return getAiTongueResult(null,"40003","请求频繁，请稍后再试");
        }
    }

    private static @NotNull AITongueResult<FsHealthTongue> getAiTongueResult(FsHealthTongue healthTongue, String code, String msg) {
        AITongueResult<FsHealthTongue> result = new AITongueResult<>();
        result.setData(healthTongue);
        result.setCode(code);
        meta meta = new meta();
        meta.setCode(code);
        meta.setMsg(msg);
        meta.setTimestamp(String.valueOf(new Date()));
        result.setMeta(meta);
        return result;
    }


    public  String sendPost(String url,Object param){
        HttpClient httpClient = HttpClients.createDefault();
        try {
            URIBuilder builder = new URIBuilder(url);
            URI uri = builder.build();
            HttpPost httpPost = new HttpPost(uri);
            httpPost.setHeader("Content-Type", "application/json"); // 设置Content-Type为"application/json"
            httpPost.setEntity(new StringEntity(JSON.toJSONString(param), StandardCharsets.UTF_8));
            HttpResponse response = httpClient.execute(httpPost);
            String reJson = EntityUtils.toString(response.getEntity());
            return reJson;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
