package com.fs.hospital580.service.impl;


import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONUtil;
import com.fs.hospital580.config.Hospital580Config;
import com.fs.hospital580.dto.*;
import com.fs.hospital580.entity.Hospital580ScrmEntity;
import com.fs.hospital580.service.Hospital580Service;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

@Service
@Slf4j
public class Hospital580ServiceImpl implements Hospital580Service {
    
    @Autowired
    private Hospital580Config hospital580Config;
    
    /**
     * 4.7 同步药品信息接口-580提供
     */
    private static final String MEDICINE_PATH = "/v1_0/ehospital/openapi/kz/medicine/sync";
    /**
     * 4.2新 新增问诊单接口-580提供
     */
    private static final String PREDEMAND_PATH = "/v1_0/ehospital/openapi/kz/web/predemand/initPreDemand";
    /**
     * 5、查询诊断
     */
    private static final String DISEASE_PATH = "/v2_0/ehospital/openapi/diagnosis/disease/query";

    private static final String TEXTRECORD_PATH = "/v1_0/ehospital/openapi/kz/textRecord/list";

    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public Result580 syncMedicine(MedicineDto dto) {
        dto.setCallbackUrl(hospital580Config.getCallbackUrl());
        return requestResult580(dto, MEDICINE_PATH);

    }


    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public Result580 initPreDemand(PreDemandDto dto) {
        dto.setStoreId(hospital580Config.getStoreId());
        return requestResult580(dto, PREDEMAND_PATH);
    }

    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public Result580 disease(DiseaseDto dto) {
        return requestResult580(dto, DISEASE_PATH);
    }

    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public Result580 textRecord(TextRecordDto dto) {
        return requestResult580(dto, TEXTRECORD_PATH);
    }

    private <T extends CommonDto> Result580 requestResult580(T t, String path) {
        t.initCommonDto(hospital580Config.getClientId(), hospital580Config.getSecretKey());
        String url = hospital580Config.getUrl() + path;
        String body = JSONUtil.toJsonStr(t);
        String result;
        Result580 result580;
        boolean requestStatus;
        try {
            log.info("请求580接口:{}", body);
            result = HttpRequest.post(url)
                    .body(body)//表单内容
                    .timeout(10000)//超时，毫秒
                    .execute().body();
            log.info("请求580接口返回:{}", result);
            result580 = JSONUtil.toBean(result, Result580.class);
            requestStatus = true;
        } catch (Exception e) {
            log.info("请求580接口异常:", e);
            result580 = new Result580(e.getMessage());
            requestStatus = false;
            result="";
        }
        /*
          保存调用记录
         */
        Hospital580ScrmEntity build = Hospital580ScrmEntity.builder()
                .request(url)
                .requestParm(body)
                .response(result)
                .requestStatus(requestStatus)
                .createTime(LocalDateTime.now())
                .build();
        build.insert();
        result580.setRequestId(build.getId());
        return result580;
    }

    /*public static void main(String[] args) {
        // 创建测试实例
        Hospital580ServiceImpl service = new Hospital580ServiceImpl();

        // 创建测试数据
        MedicineDto dto = new MedicineDto();
        //dto.setCallbackUrl("http://localhost:8080/callback");

        List<Medicine> medicineList = new ArrayList<>();

        // 添加测试药品数据
        Medicine medicine = new Medicine();
        medicine.setCategoryId(0); // 西药
        medicine.setCommonName("阿司匹林肠溶片");
        medicine.setName("拜阿司匹灵");
        medicine.setDosage("片剂");
        medicine.setSpec("0.25g*12粒");
        medicine.setPackingSpec("30片/盒");
        medicine.setManufacturer("拜耳医药保健有限公司");
        medicine.setApprovalNumber("国药准字H10980126");
        medicine.setUnit("盒");
        medicine.setMedicineId("MED123456");
        medicine.setBarCode("6920228888888");
        medicine.setIsPrescription(0);
        medicine.setPrice(25.80);
        medicine.setStock(1000);
        medicine.setSpecialCommonName("");
        medicine.setSpecialSpec("");

        medicineList.add(medicine);


        dto.setMedicineList(medicineList);

        // 调用测试方法
        System.out.println("开始测试 medicine 接口...");
        dto.setSign(ObjectApiSignUtil.getSign(dto, SECRETKEY));
        System.out.println("签名：" + JSONUtil.toJsonStr(dto));
        service.medicine(dto);
        System.out.println("测试完成");
    }*/

}