package com.fs.hisStore.service.impl;

import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fs.common.OrderUtils;
import com.fs.common.config.FSSysConfig;
import com.fs.common.core.domain.R;
import com.fs.common.exception.CustomException;
import com.fs.common.utils.DateUtils;
import com.fs.common.utils.HsCryptoUtil;
import com.fs.common.utils.StringUtils;
import com.fs.course.param.InquiryOrderHsLog;
import com.fs.course.vo.FsInquiryPatientInfoListUVO;
import com.fs.his.domain.FsPatient;
import com.fs.his.mapper.FsInquiryOrderMapper;
import com.fs.his.mapper.FsInquiryOrderReportMapper;
import com.fs.his.mapper.FsInquiryPatientInfoMapper;
import com.fs.his.mapper.FsPatientMapper;
import com.fs.hisStore.bean.Drug;
import com.fs.hisStore.bean.Prescribe;
import com.fs.hisStore.domain.*;
import com.fs.hisStore.param.FsPrescribeParam;
import com.fs.hisStore.param.FsPrescribeQueryParam;
import com.fs.hisStore.param.FsPrescribeVOParam;
import com.fs.hisStore.param.PrescribeParam;
import com.fs.hisStore.service.*;
import com.fs.hisStore.vo.FsPrescribeVO;
import org.apache.hc.client5.http.classic.methods.HttpPost;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.apache.hc.core5.http.io.entity.StringEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.fs.hisStore.mapper.FsPrescribeScrmMapper;

/**
 * 处方Service业务层处理
 *
 * @author fs
 * @date 2022-03-15
 */
@Service
public class FsPrescribeScrmServiceImpl implements IFsPrescribeScrmService
{
    @Autowired
    IPrescribeScrmService prescribeService;
    @Autowired
    FsPrescribeScrmMapper fsPrescribeMapper;
    @Autowired
    IFsStoreOrderScrmService orderService;
    @Autowired
    IFsPatientScrmService patientService;
    @Autowired
    IFsUserScrmService userService;
    @Autowired
    FSSysConfig fsSysConfig;
    @Autowired
    IFsStoreOrderItemScrmService orderItemService;
    @Autowired
    IFsStoreProductScrmService productService;
    @Autowired
    private FsInquiryPatientInfoMapper fsInquiryPatientInfoMapper;
    @Autowired
    private FsPatientMapper fsPatientMapper;
    @Autowired
    private FsInquiryOrderMapper inquiryOrderMapper;

    private final String appId = "TpmBATELpdeMbjtjdaVIGbznlJDRjLDw";
    private final String hsInquiryOrderPrescriptionUrl = "https://dev.om.yfttech.cn/open_platform/hospital/suppliers/v1/book_order/prescription";
    //应用秘钥
    private final String appSecret = "ExbfudweIeSCFLtp";
    // 三方平台RSA私钥（解密响应密钥用）
    private final String thirdPrivateKey = "LS0tLS1CRUdJTiBQUklWQVRFIEtFWS0tLS0tCk1JSUNkd0lCQURBTkJna3Foa2lHOXcwQkFRRUZBQVNDQW1Fd2dnSmRBZ0VBQW9HQkFMWmxsblI4SE5Qb0N2WFkKVFBCTmtLdFArejc0NVA4ZzlzZUVHVDZUbysxdmp4Sk9jc2VRNWpFNnR4Rm5IQlJsc3psam5sUHdYT25HYStFLwo3Q2phbElIZjdTZ2p0SzlKSCtpckd5eW1yaVN6cEYyMFpKT2wxQXhsams2UUVFdGRRS0VqYWI2NjFGVHN2clRDCjhaRzAzS05NOVVjM2F6SGY2bVRRUXJtRWp1WjlBZ01CQUFFQ2dZRUF0Zjc5dG5OVkRIaWYzeGthQkRsUkhpOHIKWW5WVmdlRHhmTGtwdTAvMEpPbkkxNXBoV3hJUkxwUUlzUnV5WUFQdVpsZ3BWbFlqVDd5R1RuYksvU1RGUW5YVwpGS05pUEtjQ1pXdXhBdkNhRFFCZ0ZHdXZpMjB6bjBBZ2hEU0tycEIrYU9NL1VGdjhFZWx0cE42WDA0Vis1RlY2CitwWGFsdkZjUlhUWEVHMXBTUUVDUVFEbnVFT2VmcUxKb1pDK3lwMlovMTFFRm0yaWxOL2VKOFBpdzRFUm5WdTkKRU5TWm9OdURIUjFSeVFlYWVzeXU3WlFadzV2d0VvZkFlL1MzV2ZhVlFBM0JBa0VBeVlKRVJEcmdLSHF3YzYyOQpkLys4RGNVOEtZei9hQ3ZqVm9kUGRmMVMwbXZpdUlUS2txYVZhdDFCTis2MjZMcFU2c1BsNVVHeWZ5aXlVc3FTCnpmSi92UUpBRDhGUGw2ODBrbEVSN21jSVlEZ2t0MFJ2SCtiUGNlTnlSakRVemNYTlB3V3Q3dVFwQ0xrcURTMkYKL3RMcXA5b3ZmN0QxSVZXaE5VMDRUbDhuak81V0FRSkJBS01wS0M5NjRJL0dMK09xbFJSNTdJSFY1dzNaemVCQwpVUlI2QVZ3UEh5V2tGM0xDaXVmTm5JUm4zR3YyalFIS0JnSUZWcnVYdzNqMHNkY1prVjdTY0owQ1FGVGJJTnRCCi9OcW5laWI3U3d4ZCt5NHZ4UkRHZVRxZUFjNXE5ZU5RNy8vbUFOWlZyUTZKSEJnZ1NjT3h6ZFhFZFZ5UTk5Z1AKYmQ3c2Z2Mlk2WGdhd3FFPQotLS0tLUVORCBQUklWQVRFIEtFWS0tLS0tCg";
    @Autowired
    private FsInquiryOrderReportMapper fsInquiryOrderReportMapper;
    /**
     * 向红杉发起问诊申请后返回的bookNo
     */
    public static final String CACHE_BOOK_NO_HS = "cache:hs:book:no:%d";
    @Qualifier("redisTemplate")


    /**
     * 查询处方
     *
     * @param prescribeId 处方ID
     * @return 处方
     */
    @Override
    public FsPrescribeScrm selectFsPrescribeById(Long prescribeId)
    {
        return fsPrescribeMapper.selectFsPrescribeById(prescribeId);
    }

    /**
     * 查询处方列表
     *
     * @param fsPrescribe 处方
     * @return 处方
     */
    @Override
    public List<FsPrescribeScrm> selectFsPrescribeList(FsPrescribeScrm fsPrescribe)
    {
        return fsPrescribeMapper.selectFsPrescribeList(fsPrescribe);
    }

    /**
     * 新增处方
     *
     * @param fsPrescribe 处方
     * @return 结果
     */
    @Override
    public int insertFsPrescribe(FsPrescribeScrm fsPrescribe)
    {
        fsPrescribe.setCreateTime(DateUtils.getNowDate());
        return fsPrescribeMapper.insertFsPrescribe(fsPrescribe);
    }

    /**
     * 修改处方
     *
     * @param fsPrescribe 处方
     * @return 结果
     */
    @Override
    public int updateFsPrescribe(FsPrescribeScrm fsPrescribe)
    {
        return fsPrescribeMapper.updateFsPrescribe(fsPrescribe);
    }

    /**
     * 批量删除处方
     *
     * @param prescribeIds 需要删除的处方ID
     * @return 结果
     */
    @Override
    public int deleteFsPrescribeByIds(Long[] prescribeIds)
    {
        return fsPrescribeMapper.deleteFsPrescribeByIds(prescribeIds);
    }

    /**
     * 删除处方信息
     *
     * @param prescribeId 处方ID
     * @return 结果
     */
    @Override
    public int deleteFsPrescribeById(Long prescribeId)
    {
        return fsPrescribeMapper.deleteFsPrescribeById(prescribeId);
    }

    @Override
    public R doPrescribe(long userId, FsPrescribeParam param) {
        FsStoreOrderScrm order=orderService.selectFsStoreOrderById(param.getOrderId());
        if(order==null){
            throw  new CustomException("订单不存在");
        }
//      if(order.getStatus()!=1){
//           throw  new CustomException("未支付订单不能开处方");
//      }
        FsPrescribeScrm checkPrescribe=fsPrescribeMapper.selectFsPrescribeByOrderId(order.getId());
        if(checkPrescribe!=null){
            throw  new CustomException("已提交处方申请，正在开方...");
        }
        FsStoreOrderItemScrm orderItemMap=new FsStoreOrderItemScrm();
        orderItemMap.setOrderId(order.getId());
        orderItemMap.setIsPrescribe(1);
        List<FsStoreOrderItemScrm> items= orderItemService.selectFsStoreOrderItemList(orderItemMap);
        String rpId= OrderUtils.getOrderNo();
        FsPatientScrm patient=patientService.selectFsPatientById(param.getPatientId());
        FsUserScrm user=userService.selectFsUserById(userId);
        PrescribeParam prescribeParam=new PrescribeParam();
        List<Prescribe> data=new ArrayList<>();
        Prescribe prescribe=new Prescribe();
        prescribe.setRp_type("01");
        prescribe.setRp_id(rpId);
        prescribe.setPharmacy_code("00001");
        prescribe.setPharmacy_name("默认门店");
        prescribe.setPatient_name(patient.getPatientName());
        prescribe.setPatient_age(DateUtils.getAge(patient.getBirthday()));
        prescribe.setPatient_tel(user.getPhone());
        prescribe.setPatient_gender(patient.getGender().toString());
        prescribe.setIs_history_allergic(param.getIsAllergic()?"是":"否");
        prescribe.setLiver_unusual(param.getIsLiver()?"是":"否");
        prescribe.setRenal_unusual(param.getIsRenal()?"是":"否");
        prescribe.setLactation_flag(param.getIsLactation());
        prescribe.setChief_complaint(param.getChiefComplaint());
        prescribe.setNow_illness(param.getNowIllness());
        prescribe.setHistory_illness(param.getHistoryIllness());
        if(StringUtils.isNotEmpty(param.getRecordPic())){
            prescribe.setRecord_pic(param.getRecordPic().split(","));
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date now = new Date();
        prescribe.setRp_create_time(sdf.format(now));
        prescribe.setRp_url_type("png");
        prescribe.setLactation_flag("否");
        prescribe.setCallback_url(fsSysConfig.getCallbackUrl());
        data.add(prescribe);

        List<Drug> drug_list=new ArrayList<>();
        for(FsStoreOrderItemScrm item:items){
            FsStoreProductScrm product=productService.selectFsStoreProductById(item.getProductId());
            Drug drug=new Drug();
            drug.setDrug_common_name(product.getPrescribeName());
            drug.setDrug_specification(product.getPrescribeSpec());
            drug.setSale_amount(item.getNum().toString());
            drug.setSale_unit(product.getUnitName());
            drug.setApproval_number(product.getPrescribeCode());
            drug_list.add(drug);
            prescribe.setDrug_list(drug_list);
            prescribeParam.setData(data);
        }
        R response=prescribeService.doPrescribe(prescribeParam);
        if(response.get("code").equals(200)){
            FsPrescribeScrm fsPrescribe=new FsPrescribeScrm();
            fsPrescribe.setRpId(rpId);
            fsPrescribe.setUserId(userId);
            fsPrescribe.setPatientId(patient.getPatientId());
            fsPrescribe.setPharmacyCode("00001");
            fsPrescribe.setPharmacyName("默认门店");
            fsPrescribe.setStatus(0);
            fsPrescribe.setPrescribeType(1);
            fsPrescribe.setOrderId(order.getId());
            fsPrescribe.setCreateTime(new Date());
            fsPrescribe.setPatientGender(patient.getGender().toString());
            fsPrescribe.setPatientName(patient.getPatientName());
            fsPrescribe.setIsHistoryAllergic(param.getIsAllergic()?"是":"否");
            fsPrescribe.setLiverUnusual(param.getIsLiver()?"是":"否");
            fsPrescribe.setLactationFlag(param.getIsLactation());
            fsPrescribe.setRenalUnusual(param.getIsRenal()?"是":"否");
            fsPrescribe.setChiefComplaint(param.getChiefComplaint());
            fsPrescribe.setNowIllness(param.getNowIllness());
            fsPrescribe.setHistoryIllness(param.getHistoryIllness());
            fsPrescribe.setRecordPic(param.getRecordPic());
            fsPrescribe.setPatientAge(String.valueOf( DateUtils.getAge(patient.getBirthday())));
            fsPrescribeMapper.insertFsPrescribe(fsPrescribe);

            FsStoreOrderScrm orderMap=new FsStoreOrderScrm();
            orderMap.setId(order.getId());
            orderMap.setPrescribeId(fsPrescribe.getPrescribeId());
            orderService.updateFsStoreOrder(orderMap);
            return R.ok("操作成功").put("order",order);

        }
        else{
            return R.error(response.get("msg").toString());
        }
    }

    @Override
    public FsPrescribeScrm selectFsPrescribeByRpId(String rpId) {
        return fsPrescribeMapper.selectFsPrescribeByRpId(rpId);
    }

    @Override
    public List<FsPrescribeVO> selectFsPrescribeListQuery(FsPrescribeQueryParam param) {
        return fsPrescribeMapper.selectFsPrescribeListQuery(param);

    }

    @Override
    public List<FsPrescribeVO> selectFsPrescribeListVO(FsPrescribeVOParam fsPrescribe) {
        return fsPrescribeMapper.selectFsPrescribeListVO(fsPrescribe);
    }

    @Override
    public FsPrescribeScrm selectFsPrescribeByOrderId(Long id) {
        return fsPrescribeMapper.selectFsPrescribeByOrderId(id);
    }

    //从红杉获取处方
    @Override
    public R getPrescribeFromHs(String userId,String inquiryOrderId) throws JsonProcessingException {
        FsInquiryPatientInfoListUVO info = fsInquiryPatientInfoMapper.getInfo(Long.valueOf(inquiryOrderId));
        FsPatient fsPatient = fsPatientMapper.selectFsPatientByPatientId(info.getPatientId());
        InquiryOrderHsLog inquiryOrderHsLog = inquiryOrderMapper.selectHsLog(inquiryOrderId);

        String s = sendPostRequest(inquiryOrderHsLog.getBookNo());
        JsonNode jsonNode = new ObjectMapper().readTree(s);
        JsonNode data = jsonNode.get("data");
        if (data == null){
            throw new RuntimeException("未收到响应的结果");
        }
        Map<String, Object> decrypt = HsCryptoUtil.decrypt( data, appSecret, thirdPrivateKey);
        ObjectMapper objectMapper = new ObjectMapper();
        String jsonString = objectMapper.writeValueAsString(decrypt);
        HsPrescribScrm hsPrescribScrm = objectMapper.readValue(jsonString, HsPrescribScrm.class);
        //拼参数新建处方
        FsPrescribeParam prescribeParam=new FsPrescribeParam();
        prescribeParam
//                .setOrderId(Long.parseLong())//todo 逻辑更改弃用
                .setPrescribeType(1).setInquiryOrderId(Long.valueOf(inquiryOrderId))
                .setUserId(Long.parseLong(userId)).setPatientId(info.getPatientId())
                .setPrescribeCode(hsPrescribScrm.getPrescriptionInfo().getOrderNo())
                .setPatientDescs(hsPrescribScrm.getMedicalRecord().getRecount())
                .setPatientAge(String.valueOf(hsPrescribScrm.getMedicalRecord().getAge()))
                .setPatientName(hsPrescribScrm.getMedicalRecord().getRealName())
                .setWeight(String.valueOf(fsPatient.getWeight()))
                .setIsAllergic(hsPrescribScrm.getMedicalRecord().getAllergyhistory()!=null)
//                .setIsHistoryAllergic(hsPrescribScrm.getMedicalRecord().getAllergyhistory()==null?"是":"否")
                .setHistoryAllergic(hsPrescribScrm.getMedicalRecord().getAllergyhistory())
                .setIsLiver(true).setIsRenal(true)
//                .setLiverUnusual("是").setRenalUnusual("是")
                .setIsLactation("否")//无法准确提取红杉响应的情况
                .setPatientTel(fsPatient.getMobile()).setPatientGender(String.valueOf(hsPrescribScrm.getMedicalRecord().getSex()))
                .setDiagnose(hsPrescribScrm.getMedicalRecord().getDiagnose().toString())
                .setDoctorName(hsPrescribScrm.getPrescriptionInfo().getBillingDoctorName());
        doPrescribe(Long.parseLong(userId),prescribeParam);

        //todo 未完成，售后，处方逻辑未清楚，需对接组长再细了解
        return null;
    }
    private String sendPostRequest(String request) {
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            // 构建URL
            String urlWithParams = hsInquiryOrderPrescriptionUrl;
            HttpPost httpPost = new HttpPost(urlWithParams);

            // 设置请求头
            httpPost.setHeader("appid", appId);
            httpPost.setHeader("Accept", "application/json");
            httpPost.setHeader("Content-Type", "application/json");
            httpPost.setHeader("User-Agent", "Mozilla/5.0");
            httpPost.setHeader("_method","GET");//按红杉要求，要传方法

            // 设置请求体
            String requestBody = request;
            StringEntity entity = new StringEntity(requestBody, StandardCharsets.UTF_8);
            httpPost.setEntity(entity);

            // 执行请求
            try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
                int statusCode = response.getCode();
                System.out.println("响应码: " + statusCode);
                String responseBody = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
                return responseBody;
            }

        } catch (Exception e) {
            e.printStackTrace();
            return "向红杉发起请求失败: " + e.getMessage();
        }
    }
}
