package thyyxxk.webserver.service.examinations;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.Nullable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import thyyxxk.webserver.config.exception.ExceptionEnum;
import thyyxxk.webserver.constants.Capacity;
import thyyxxk.webserver.dao.his.examinations.InspectionsDao;
import thyyxxk.webserver.entity.ResultVo;
import thyyxxk.webserver.entity.examinations.inspections.consts.PatientNumType;
import thyyxxk.webserver.entity.examinations.inspections.request.ReportIndexInquiry;
import thyyxxk.webserver.entity.examinations.lisdock.CustomerInfo;
import thyyxxk.webserver.entity.examinations.lisdock.HealthCardResult;
import thyyxxk.webserver.entity.examinations.lisdock.ItemResult;
import thyyxxk.webserver.entity.examinations.lisdock.PushResultParam;
import thyyxxk.webserver.entity.examinations.inspections.response.JyDetailItem;
import thyyxxk.webserver.entity.examinations.inspections.response.JyDetailOrder;
import thyyxxk.webserver.entity.examinations.inspections.response.JyDetailResponse;
import thyyxxk.webserver.entity.examinations.inspections.response.JyIndexResponse;
import thyyxxk.webserver.service.TokenService;
import thyyxxk.webserver.service.externalhttp.Html2ImgSrvc;
import thyyxxk.webserver.utils.Md5Util;
import thyyxxk.webserver.utils.ResultVoUtil;

import java.util.*;

/**
 * @author dj
 */
@Slf4j
@Service
public class LisDockService {
    private final static String APP_ID = "jkzd5e26bf01c5a0d79";
    private final static String IMG_URL_PREFIX = "https://staticweb.hnthyy.cn/inspections/";
    private static final String GET_CUSTOMER_INFO = "https://api.hnocc.com/commonInterface/selectUserInfo"; // 线上
    private static final String PUSH_RESULT = "https://api.hnocc.com/commonInterface/pushResult"; // 线上
    private final static String STOOL_CULTURE = "JK01";
    private final static String BLOOD_CHECK = "JK02";
    private final static String COVID_EXAM = "JK03";
    private final InspectionsDao dao;
    private final InspectionsService service;
    private final Html2ImgSrvc html2ImgSrvc;
    private final TokenService tokenService;
    private final RestTemplate template;

    @Autowired
    public LisDockService(InspectionsDao dao, InspectionsService service,
                          Html2ImgSrvc html2ImgSrvc, TokenService tokenService, RestTemplate template) {
        this.dao = dao;
        this.service = service;
        this.html2ImgSrvc = html2ImgSrvc;
        this.tokenService = tokenService;
        this.template = template;
    }

    public ResultVo<Map<String, Object>> scanBarCode(ReportIndexInquiry inquiry) {
        JSONObject customerInfo = getCustomerInfo(inquiry.getContent());
        if (null == customerInfo) {
            return ResultVoUtil.fail(ExceptionEnum.NULL_POINTER, "未查询到此条码对应的身份信息。");
        }
        Map<String, Object> map = new HashMap<>(Capacity.TWO);
        map.put("customerInfo", customerInfo);
        String tjNo = dao.selectTjNo(customerInfo.getString("idCard"));
        map.put("tjNo", tjNo);
        inquiry.setPatType(PatientNumType.Pis);
        inquiry.setPatNo(tjNo);
        map.put("inspectionsIndex", getFilteredList(inquiry));
        return ResultVoUtil.success(map);
    }

    public ResultVo<List<JyIndexResponse>> getIndexByTjNo(ReportIndexInquiry inquiry) {
        inquiry.setPatType(PatientNumType.Pis);
        inquiry.setPatNo(inquiry.getContent());
        return ResultVoUtil.success(getFilteredList(inquiry));
    }

    private List<JyIndexResponse> getFilteredList(ReportIndexInquiry inquiry) {
        List<JyIndexResponse> list = service.queryJyIndex(inquiry);
        list.removeIf(item ->
                !item.getExamPurpose().contains("大便培养") && !item.getExamPurpose().contains("大便体检") &&
                        !item.getExamPurpose().contains("甲肝抗体") && !item.getExamPurpose().contains("戊肝抗体") &&
                        !item.getExamPurpose().contains("核酸检测"));
        return list;
    }

    public ResultVo<Map<String, String>> pushSelectedResult(PushResultParam param) {
        String itemCode;
        CustomerInfo customerInfo = param.getCustomerInfo();
        Map<String, String> map = new HashMap<>(Capacity.TWO);
        for (JyIndexResponse index : param.getInspectionsIndex()) {
            if (index.getExamPurpose().contains("大便培养") || index.getExamPurpose().contains("大便体检")) {
                customerInfo.setType("0");
                itemCode = STOOL_CULTURE;
            } else if (index.getExamPurpose().contains("核酸检测")) {
                customerInfo.setType("2");
                itemCode = COVID_EXAM;
            } else {
                customerInfo.setType("1");
                itemCode = BLOOD_CHECK;
            }
            HealthCardResult result = new HealthCardResult();
            result.setAppId(APP_ID);
            result.setCustomerInfo(customerInfo);
            JyDetailResponse detail = service.queryJyDetail(index.getReportId());
            JyDetailOrder header = detail.getOrder();
            List<ItemResult> itemResults = new ArrayList<>();
            ItemResult model = new ItemResult();
            model.setItemName("");
            model.setOpter(header.getTestUsrName());
            model.setAuditOpter(header.getAudtUsrName());
            model.setTestTime(header.getOrdrCreateDate().substring(0, 10));
            model.setAuditTime(header.getAudtTime().substring(0, 10));
            model.setResult("未见异常");
            model.setStatus("0");
            model.setReference("");
            model.setUnit("");
            model.setItemCode(itemCode);
            if (STOOL_CULTURE.equals(itemCode)) {
                for (JyDetailItem item : detail.getItems()) {
                    if (item.getItmName().contains("大便培养") || item.getItmName().contains("大便体检")) {
                        fillResultItem(itemResults, model, item);
                    } else if (item.getItmName().contains("阿米巴")){
                        ItemResult ambxlj = model.clone();
                        ambxlj.setItemName("阿米巴性痢疾");
                        if (!item.getItmStrValue().contains("未见")) {
                            ambxlj.setResult(item.getItmStrValue());
                            ambxlj.setStatus("1");
                        }
                        itemResults.add(ambxlj);
                    } else if (item.getItmName().contains("微生物培养")) {
                        fillResultItem(itemResults, model, item);
                        ItemResult ambxlj = model.clone();
                        ambxlj.setItemName("阿米巴性痢疾");
                        if (!item.getItmStrValue().contains("未检出")) {
                            ambxlj.setResult("检出");
                            ambxlj.setStatus("1");
                        }
                        itemResults.add(ambxlj);
                    }
                }
            } else {
                for (JyDetailItem item : detail.getItems()) {
                    ItemResult results = model.clone();
                    if (item.getItmName().contains("甲肝")) {
                        item.setItmName("甲型肝炎抗体IGM");
                    } else if (item.getItmName().contains("戊肝")) {
                        item.setItmName("戊型肝炎抗体IGM");
                    } else if (item.getItmName().contains("核酸") || item.getItmName().contains("新冠")
                            || item.getItmName().contains("新型冠状")) {
                        item.setItmName("新型冠状病毒感染性肺炎");
                    }
                    results.setItemName(item.getItmName());
                    results.setResult(item.getItmStrValue());
                    results.setStatus(item.getItmStrValue().contains("阴性") ? "0" : "1");
                    itemResults.add(results);
                }
            }
            result.setItemResults(itemResults);
            String reportUrl = html2image(result);
            if (null == reportUrl) {
                return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, "生成检验报告图片失败！");
            }
            result.getCustomerInfo().setReportUrl(reportUrl);
            result.setTimeStamp(tokenService.getLisDockSign()[0]);
            result.setSignature(tokenService.getLisDockSign()[1]);
            JSONObject pushRes = pushResult(result);
            map.put(itemCode, pushRes.getString("msg"));
        }
        return ResultVoUtil.success(map);
    }

    private void fillResultItem(List<ItemResult> itemResults, ItemResult model, JyDetailItem item) {
        ItemResult xjxlj = model.clone();
        xjxlj.setItemName("细菌性痢疾");
        if (!item.getItmStrValue().contains("未检出") && !item.getItmStrValue().contains("未见")) {
            xjxlj.setResult("检出");
            xjxlj.setStatus("1");
        }
        itemResults.add(xjxlj);
        ItemResult shhfsh = xjxlj.clone();
        shhfsh.setItemName("伤寒和副伤寒");
        itemResults.add(shhfsh);
        ItemResult hl = xjxlj.clone();
        hl.setItemName("霍乱");
        itemResults.add(hl);
    }

    private String html2image(HealthCardResult param) {
        Map<String, Object> res = html2ImgSrvc.execute(param);
        log.info("生成图片结果：{}", res);
        if (null == res || null == res.get("code")) {
            return null;
        }
        if ((int) res.get("code") != ExceptionEnum.SUCCESS.getCode()) {
            return res.get("message").toString();
        }
        return IMG_URL_PREFIX + res.get("path").toString();
    }

    public JSONObject pushResult(HealthCardResult param) {
        param.setTimeStamp(tokenService.getLisDockSign()[0]);
        param.setSignature(tokenService.getLisDockSign()[1]);
        JSONObject obj = JSONObject.parseObject(JSONObject.toJSONString(param));
        log.info("推送内容：{}", obj);
        String res = template.postForObject(PUSH_RESULT, obj, String.class);
        log.info("推送结果：{}", res);
        return JSONObject.parseObject(res);
    }

    private JSONObject getCustomerInfo(String barCode) {
        JSONObject param = new JSONObject();
        param.put("barCode", barCode);
        param.put("appId", APP_ID);
        param.put("timeStamp", tokenService.getLisDockSign()[0]);
        param.put("signature", tokenService.getLisDockSign()[1]);
        String res = template.postForObject(GET_CUSTOMER_INFO, param, String.class);
        JSONObject customerInfo = getCustomerInfoExecute(barCode, res);
        if (customerInfo != null) return customerInfo;
        String[] sign = new String[2];
        sign[0] = String.valueOf(System.currentTimeMillis());
        String ori = "jkzd5e26bf01c5a0d79" + sign[0] + "957a642f1dae09fd226a3517a465";
        sign[1] = Md5Util.encrypt(Md5Util.encrypt(ori));
        tokenService.setLisDockSign(sign);
        res = template.postForObject(GET_CUSTOMER_INFO, param, String.class);
        return getCustomerInfoExecute(barCode, res);
    }

    @Nullable
    private JSONObject getCustomerInfoExecute(String barCode, String res) {
        log.info("查询健康证【{}】个人信息：{}", barCode, res);
        JSONObject resObj = JSONObject.parseObject(res);
        if (resObj.getIntValue("code") == 0) {
            JSONObject data = resObj.getJSONObject("data");
            JSONObject customerInfo = new JSONObject();
            customerInfo.put("barCode", data.getString("barCode"));
            customerInfo.put("name", data.getString("name"));
            customerInfo.put("sex", data.getString("sex"));
            customerInfo.put("age", data.getString("age"));
            customerInfo.put("idCard", data.getString("idCard").toUpperCase());
            return customerInfo;
        }
        return null;
    }
}

