package cn.hnthyy.thmz.service.impl.thmz;

import cn.hnthyy.thmz.Utils.HttpUtil;
import cn.hnthyy.thmz.service.thmz.HaiCiAdapterService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Slf4j
@Service
public class HaiCiAdapterServiceTaiheImpl implements HaiCiAdapterService {

    @Value("${haiciServiceUrl}")
    private String haiciServiceUrl;
    //卡号变更通知开关
    @Value("${sendNoticeToHaiCi}")
    private boolean sendNoticeToHaiCi;

    private ExecutorService executor = Executors.newFixedThreadPool(5);

    /**
     * 更新病人卡号 消息通知
     *
     * @param oldCardNo 老卡号
     * @param cardNo    新卡号
     * @param timeStamp 变更时间
     */
    @Override
    public void cardChangeNotice(String oldCardNo, String cardNo, Date timeStamp) {
        if (!sendNoticeToHaiCi) {
            return;
        }
        executor.submit(() -> {
            try {
                String params = "{\"cardNo\":\"" + cardNo + "\",\"oldCardNo\":\"" + oldCardNo + "\",\"actionType\":\"1\"}";
                HttpUtil.httpPost(haiciServiceUrl + "/patientCards/changeCard", params, "application/json");
                log.info(params);
            } catch (Exception e) {
                e.printStackTrace();
            }
        });

    }

    @Override
    public void commonMessageNotice(String cardNo, String message, Date timeStamp) {
        executor.submit(() -> {
            try {
                String params = getCommonMessageJsonString(cardNo, message);
                HttpUtil.httpPost(haiciServiceUrl + "/wxApi/pushMessage", params, "application/json");
                log.info(params);
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }

    @Override
    public void rejectCallbackScheduleOfMedical(String reqNo) {
        executor.submit(() -> {
            try {
                HttpUtil.sendHttpGet(haiciServiceUrl+"/bookable/revokeBookPrescription?reqNo="+reqNo,"utf-8");
                log.info("回调丁捷微信服务，医技申请号【"+reqNo+"】");
            } catch (IOException e) {
                e.printStackTrace();
                log.info("回调丁捷微信服务失败，医技申请号【"+reqNo+"】");
            }
        });
    }


    /**
     * 生成向海鹚发送请求的参数 发送通用消息参数
     */
    private String getCommonMessageJsonString(String cardNo, String message) {
        return "{\"cardNo\":\"" + cardNo + "\",\"msgContext\":" + message + "}";
    }
}
