package com.openhis.web.externalintegration.appservice.impl;

import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.core.common.core.domain.R;
import com.core.common.enums.TenantOptionDict;
import com.core.common.utils.StringUtils;
import com.core.web.util.TenantOptionUtil;
import com.openhis.common.enums.*;
import com.openhis.common.utils.CommonUtil;
import com.openhis.web.externalintegration.appservice.IFoodborneAcquisitionAppService;
import com.openhis.web.externalintegration.dto.FaSimplediseaseAddNopwParam;
import com.openhis.web.externalintegration.mapper.FoodborneAcquisitionAppMapper;

import lombok.extern.slf4j.Slf4j;

/**
 * 食源性疾病病例数据智能采集Service业务层处理
 *
 * @author Thanking
 * @date 2025-10-10
 */
@Slf4j
@Service
public class FoodborneAcquisitionAppServiceImpl implements IFoodborneAcquisitionAppService {
    @Autowired
    private FoodborneAcquisitionAppMapper foodborneAcquisitionAppMapper;

    /**
     * 是否是食源性诊断
     *
     * @param encounterId 就诊ID
     * @return 是否
     */
    @Override
    public R<?> isFoodDiseasesNew(Long encounterId) {
        // 判断食源性开关状态
        String foodborneSwitch = TenantOptionUtil.getOptionContent(TenantOptionDict.FOODBORNE_SWITCH);
        if (!Whether.YES.getCode().equals(foodborneSwitch)) {
            // 开关未开启时，返回空OK结果，跳过处理
            return R.ok();
        }
        // 判断食源性接口地址是否为空
        String foodborneApiUrl = TenantOptionUtil.getOptionContent(TenantOptionDict.FOODBORNE_API_URL);
        if (StringUtils.isEmpty(foodborneApiUrl)) {
            return R.fail("【食源性判断接口】租户配置项「食源性接口地址」未配置");
        }
        // 判断食源性医疗机构是否为空
        String foodborneHospital = TenantOptionUtil.getOptionContent(TenantOptionDict.FOODBORNE_HOSPITAL);
        if (StringUtils.isEmpty(foodborneHospital)) {
            return R.fail("【食源性判断接口】租户配置项「食源性医疗机构」未配置");
        }
        // 判断食源性登录账号是否为空
        String foodborneUserName = TenantOptionUtil.getOptionContent(TenantOptionDict.FOODBORNE_USER_NAME);
        if (StringUtils.isEmpty(foodborneUserName)) {
            return R.fail("【食源性判断接口】租户配置项「食源性登录账号」未配置");
        }
        // 定义诊断列表参数
        List<String> diagnosisNameList = new ArrayList<>();

        // TODO: 等待从doc_statistics表取主诉诊断

        // 查询就诊诊断内容列表
        List<String> encounterDiagnosisConditionNameList =
            foodborneAcquisitionAppMapper.selectEncounterDiagnosisConditionNameList(encounterId);
        diagnosisNameList.addAll(encounterDiagnosisConditionNameList);
        // 判断诊断是否为空
        if (diagnosisNameList.isEmpty()) {
            return R.fail("【食源性判断接口】未找到有效诊断");
        }
        // 设置超时时间
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(5000).setConnectionRequestTimeout(3000)
            .setSocketTimeout(30000).build();
        // 创建无视SSL验证的HttpClient
        CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(requestConfig)
            .setSSLSocketFactory(CommonUtil.createIgnoreSslSocketFactory()).build();
        CloseableHttpResponse response = null;
        // 发起HTTP请求
        try {
            // 对参数值进行URL编码
            String encodedDiagnosisName =
                URLEncoder.encode(String.join(",", diagnosisNameList), StandardCharsets.UTF_8.toString());
            // 拼接完整的请求URL
            String requestUrl = foodborneApiUrl + "/isFoodDiseasesNew?diagnosisName=" + encodedDiagnosisName;
            // 创建HttpGet对象并设置URL
            HttpGet httpGet = new HttpGet(requestUrl);
            // 执行请求
            response = httpClient.execute(httpGet);
            // 获取响应
            JSONObject object =
                JSON.parseObject(EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8.toString()));
            log.info("【食源性判断接口】入参encounterId：{}返回值：{}", encounterId, object.toString());
            // 判断返回的result字段
            String result = String.valueOf(object.getInnerMap().get("result"));
            if (!"true".equals(result)) {
                // 返回不是true时，返回空OK结果，跳过处理
                return R.ok();
            }
            // 查询食源性疾病病例数据智能采集上报跳转页面所需参数
            FaSimplediseaseAddNopwParam simplediseaseAddNopwParam = foodborneAcquisitionAppMapper
                .selectSimplediseaseAddNopwParam(encounterId, AdministrativeGender.MALE.getValue(),
                    AdministrativeGender.FEMALE.getValue(), EncounterType.FOLLOW_UP.getValue(),
                    EncounterClass.IMP.getValue(), ParticipantType.ADMITTER.getCode());
            if (simplediseaseAddNopwParam == null) {
                return R.fail("【食源性判断接口】跳转参数查询失败");
            }
            // 返回的标识字段 fillGuid
            String fillGuid = String.valueOf(object.getInnerMap().get("fillGuid"));
            // 拼装参数，作成跳转URL
            String jumpUrl = foodborneApiUrl + "/SimplediseaseAddNopw" + "?diseaseDate="
                + simplediseaseAddNopwParam.getDiseaseDate() + "&diseaseTreattime="
                + simplediseaseAddNopwParam.getDiseaseTreattime() + "&outPatientNumber="
                + URLEncoder.encode(simplediseaseAddNopwParam.getOutPatientNumber(), StandardCharsets.UTF_8.toString())
                + "&patientName="
                + URLEncoder.encode(simplediseaseAddNopwParam.getPatientName(), StandardCharsets.UTF_8.toString())
                + "&diseaseSex=" + simplediseaseAddNopwParam.getDiseaseSex() + "&guarderName="
                + URLEncoder.encode(simplediseaseAddNopwParam.getGuarderName(), StandardCharsets.UTF_8.toString())
                + "&diseaseIsreexam=" + simplediseaseAddNopwParam.getDiseaseIsreexam() + "&diseaseIspaint="
                + simplediseaseAddNopwParam.getDiseaseIspaint() + "&diseaseHospitalno="
                + simplediseaseAddNopwParam.getDiseaseHospitalno() + "&identityCard="
                + Optional.ofNullable(simplediseaseAddNopwParam.getIdentityCard()).orElse("") + "&diseaseBirthday="
                + Optional.ofNullable(simplediseaseAddNopwParam.getDiseaseBirthday()).orElse("") + "&phoneNumber="
                + Optional.ofNullable(simplediseaseAddNopwParam.getPhoneNumber()).orElse("") + "&workUnit="
                + URLEncoder.encode(Optional.ofNullable(simplediseaseAddNopwParam.getWorkUnit()).orElse(""),
                    StandardCharsets.UTF_8.toString())
                + "&deathDate=" + Optional.ofNullable(simplediseaseAddNopwParam.getDeathDate()).orElse("")
                + "&fillingDoctorName="
                + URLEncoder.encode(Optional.ofNullable(simplediseaseAddNopwParam.getFillingDoctorName()).orElse(""),
                    StandardCharsets.UTF_8.toString())
                + "&medicalInstiSeHospital=" + foodborneHospital + "&diseaseHometown=" + "&diseaseProvince="
                + URLEncoder.encode(Optional.ofNullable(simplediseaseAddNopwParam.getDiseaseProvince()).orElse(""),
                    StandardCharsets.UTF_8.toString())
                + "&diseaseCity="
                + URLEncoder.encode(Optional.ofNullable(simplediseaseAddNopwParam.getDiseaseCity()).orElse(""),
                    StandardCharsets.UTF_8.toString())
                + "&diseaseDistrict="
                + URLEncoder.encode(Optional.ofNullable(simplediseaseAddNopwParam.getDiseaseDistrict()).orElse(""),
                    StandardCharsets.UTF_8.toString())
                + "&diseaseAddress="
                + URLEncoder.encode(Optional.ofNullable(simplediseaseAddNopwParam.getDiseaseAddress()).orElse(""),
                    StandardCharsets.UTF_8.toString())
                + "&diseaseOccupation=23009012" + "&uName=" + foodborneUserName + "&fillGuid=" + fillGuid;
            // 返回非空OK结果，并携带跳转URL
            return R.ok(jumpUrl);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return R.fail("【食源性判断接口】发生异常：" + e.getMessage());
        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }

}