package com.ywt.outpatient.service.rpc.common;

import com.ywt.biz.common.enums.TerminalEnum;
import com.ywt.biz.common.util.StringHelper;
import com.ywt.biz.common.util.serializers.JsonSerializer;
import com.ywt.gapi.base.wechat.WeChatService;
import com.ywt.gapi.message.SendTemplateMessageRequest;
import com.ywt.gapi.message.WeChatMessageService;
import com.ywt.outpatient.domain.entity.center.SnsUserInfo;
import com.ywt.outpatient.domain.entity.center.SnsUserInfoRepository;
import com.ywt.outpatient.domain.wechat.Keyword;
import org.apache.dubbo.config.annotation.DubboReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class WeChatProvider {
    private static Logger logger = LoggerFactory.getLogger(WeChatProvider.class);

    @DubboReference
    WeChatService weChatServiceBlockingStub;

    @Autowired
    private SnsUserInfoRepository snsUserInfoRepository;

    @DubboReference
    private WeChatMessageService weChatMessageServiceBlockingStub;

    public void notifyRegisteredTaihe() {

    }

    /**
     * 预约挂号成功通知
     * <p>
     * 详细内容：
     * {{first.DATA}}
     * 姓名：{{patientName.DATA}}
     * 性别：{{patientSex.DATA}}
     * 预约医院：{{hospitalName.DATA}}
     * 预约科室：{{department.DATA}}
     * 预约医生：{{doctor.DATA}}
     * 流水号：{{seq.DATA}}
     * {{remark.DATA}}
     *
     * @param userId
     * @param patientName
     * @param strSex
     * @param hospitalName
     * @param department
     * @param doctor
     * @param seq
     * @param status
     * @param amount
     * @param hisPatientId
     * @param registeredDate
     * @param doctorTitle
     */
    public void notifyRegistered(
            int userId, String patientName, String strSex, String hospitalName, String department,
            String doctor, String seq, int status, int amount, String hisPatientId,
            String registeredDate, String doctorTitle, String admitAddress) {
        String tplId = "TPL_1015";
        String first = "您好，您已预约挂号成功。";
        String remark = "";
        String userInfo = String.format("%s（ID号%s）您已成功预约%s号，",
                patientName, hisPatientId, registeredDate + department + doctor + doctorTitle);

        if (status != 1) {
            if (department.contains("惠侨")) {
                remark = userInfo + "请携带身份证和诊疗卡（复诊）提前半小时至惠侨楼二楼取号。" +
                        "如过时将作延迟就诊处理。如当次未就诊记爽约一次，爽约三次将对预约进行限制。" +
                        "如您无法就诊请提前一天取消预约。祝您身体健康！";
            } else {
                remark = userInfo + "请携带身份证和诊疗卡（复诊）提前半小时至门诊各挂号窗口或自助机取号。" +
                        "如过时将作延迟就诊处理。如当次未就诊记爽约一次，爽约三次将对预约进行限制。" +
                        "如您无法就诊请提前一天取消预约。祝您身体健康！";
            }
        } else {
            if (department.contains("惠侨")) {
                remark = String.format("%s本次挂号扣费 %.2f元,请携带就诊卡提前半小时到%s取号。" +
                        "如过时将作延迟就诊处理。如当次未就诊记爽约一次，爽约三次将对预约进行限制。" +
                        "如无法就诊请提前一天取消预约。祝您身体健康！", userInfo, amount / 100d, admitAddress);
            } else {
                remark = String.format("%s本次挂号扣费 %.2f元,请携带就诊卡提前半小时到%s报到。" +
                        "如过时将作延迟就诊处理。如当次未就诊记爽约一次，爽约三次将对预约进行限制。" +
                        "如无法就诊请提前一天取消预约。祝您身体健康！", userInfo, amount / 100d, admitAddress);
            }
        }

        Map<String, Object> map = new HashMap<>();
        map.put("first", new Keyword(first));
        map.put("patientName", new Keyword(patientName));
        map.put("patientSex", new Keyword(strSex));
        map.put("hospitalName", new Keyword(hospitalName));
        map.put("department", new Keyword(department));
        map.put("doctor", new Keyword(doctor));
        map.put("seq", new Keyword(seq));
        map.put("remark", new Keyword(remark));

        sendOfficialTplMsg(userId, TerminalEnum.PatientWxOfficial.getValue(), map, tplId, "", "");
    }

    /**
     * 通知患者，咨询订单接诊
     * <p>
     * 详细内容：
     * {{first.DATA}}
     * 咨询内容：{{keyword1.DATA}}
     * 回复内容：{{keyword2.DATA}}
     * 医生名：{{keyword3.DATA}}
     * {{remark.DATA}}
     *
     * @param userId
     * @param doctorName
     * @param content
     * @param url
     */
    public void notifyConsult(int userId, String doctorName, String content, String url) {
        String tplId = "TPL_1016";
        String first = String.format("您咨询的%s医生已接诊", doctorName);
        String remark = "";

        Map<String, Object> map = new HashMap<>();
        map.put("first", new Keyword(first));
        map.put("keyword1", new Keyword(content));
        map.put("keyword2", new Keyword("请点击查看！"));
        map.put("keyword3", new Keyword(doctorName));
        map.put("remark", new Keyword(remark));

        sendOfficialTplMsg(userId, TerminalEnum.PatientWxOfficial.getValue(), map, tplId, url, "");
    }

    /**
     * 加号通知
     * <p>
     * 详细内容
     * {{first.DATA}}
     * 医生：{{keyword1.DATA}}
     * 职称：{{keyword2.DATA}}
     * 医院：{{keyword3.DATA}}
     * {{remark.DATA}}
     *
     * @param userId
     * @param doctorName
     * @param title
     * @param hospitalName
     * @param remark
     */
    public void notifyAdditional(int userId, String doctorName, String title, String hospitalName, String remark) {
        String tplId = "TPL_1017";
        String first = "您好，加号预约成功。";
        Map<String, Object> map = new HashMap<>();
        map.put("first", new Keyword(first));
        map.put("keyword1", new Keyword(doctorName));
        map.put("keyword2", new Keyword(title));
        map.put("keyword3", new Keyword(hospitalName));
        map.put("remark", new Keyword(remark));

        sendOfficialTplMsg(userId, TerminalEnum.PatientWxOfficial.getValue(), map, tplId, "", "");
    }

    /**
     * 预约申请提醒
     * <p>
     * 详细内容：
     * {{first.DATA}}
     * 姓名：{{keyword1.DATA}}
     * 电话：{{keyword2.DATA}}
     * 期望日期：{{keyword3.DATA}}
     * {{remark.DATA}}
     *
     * @param userId
     * @param doctorName
     * @param patientName
     * @param mobile
     * @param url
     * @return
     * @deprecated Use {@link com.ywt.rpc.services.WeChatServiceProvider#sendOfficialTplMsgApplication(String, String, String, String, String, String, String)} instead
     */
    @Deprecated
    public void notifyRegistration(int userId, String doctorName, String patientName, String mobile, String url) {
        String tplId = "TPL_1018";
        String first = String.format("您申请的处方，%s医生已开出！", doctorName);
        String remark = "请点击查看并支付处方单！";
        Map<String, Object> map = new HashMap<>();
        map.put("first", new Keyword(first));
        map.put("keyword1", new Keyword(patientName));
        map.put("keyword2", new Keyword(mobile));
        map.put("keyword3", new Keyword("--"));
        map.put("remark", new Keyword(remark));

//            String url = String.format("https://dg.ywtinfo.com/gdywtwe/prescriptionOrder/%s?type=prescriptionOrder2", request.getBizNo());

        sendOfficialTplMsg(userId, TerminalEnum.PatientWxOfficial.getValue(), map, tplId, url, "");
    }

    /**
     * 诊后跟进提醒
     * {{first.DATA}}
     * 就诊医生：{{keyword1.DATA}}
     * 就诊医院：{{keyword2.DATA}}
     * 姓名：{{keyword3.DATA}}
     * {{remark.DATA}}
     *
     * @param userId
     * @param hospitalName
     * @param doctorName
     * @param patientName
     * @param url
     * @return
     */
    public void notifyFollowUpOrder(int userId, String hospitalName, String doctorName, String patientName, String url) {
        String tplId = "TPL_1019";
        String first = "您好，您的主诊医生诊后向您发起了诊后提醒";
        String remark = "提醒详情，点击查看！！";

        Map<String, Object> map = new HashMap<>();
        map.put("first", new Keyword(first));
        map.put("keyword1", new Keyword(doctorName));
        map.put("keyword2", new Keyword(hospitalName));
        map.put("keyword3", new Keyword(patientName));
        map.put("remark", new Keyword(remark));

        sendOfficialTplMsg(userId, TerminalEnum.PatientWxOfficial.getValue(), map, tplId, url, "");
    }

    /**
     * 通知医生，患者成功支付问诊订单
     * <p>
     * 详细内容：
     * {{first.DATA}}
     * 患者信息：{{keyword1.DATA}}
     * 病情主述：{{keyword2.DATA}}
     * {{remark.DATA}}
     *
     * @param userId
     * @param patientName
     * @param sex
     * @param age
     * @param description
     * @param url
     */
    public void notifyDoctorConsultPaid(int userId, String patientName, String sex, int age, String description,
                                        String url) {
        String tplId = "TPL_1020";
        int terminal = TerminalEnum.DoctorWxOfficial.getValue();
//        switch (TerminalEnum.valueOf(terminal)) {
//            case TAI_HE_INTERNET_HOSPITAL_DOCTOR_WX_OFFICIAL:
//                tplId = "TPL_1029";
//                break;
//            case DoctorWxOfficial:
//            default:
//                tplId = "TPL_1020";
//                break;
//        }
        String first = String.format("患者%s向您发起了在线问诊", patientName);
        String remark = "点击查看详情！";

        Map<String, Object> map = new HashMap<>();
        map.put("first", new Keyword(first));
        map.put("keyword1", new Keyword(String.format("%s %s %d岁", patientName, sex, age)));
        map.put("keyword2", new Keyword(description));
        map.put("remark", new Keyword(remark));
        logger.info("notifyDoctorConsultPaid: terminal {}, tplCode {}", terminal, tplId);
        sendOfficialTplMsg(userId, terminal, map, tplId, url, "");
    }

    private void sendOfficialTplMsg(int userId, int terminal, Map<String, Object> data, String tplCode, String url, String miniProgram) {
        SnsUserInfo snsUserInfo = snsUserInfoRepository.getSnsUserInfoByUserId(userId, terminal);

        if (snsUserInfo == null || snsUserInfo.getDeleted() || StringHelper.isNullOrWhiteSpace(snsUserInfo.getOpenId())) {
            logger.error("cannot find the user which id is" + userId);
            return;
        }

        sendOfficialTplMsg(snsUserInfo.getOpenId(), data, tplCode, url, miniProgram);
    }


    /**
     * 发送模板消息
     */
    private void sendOfficialTplMsg(String openId, Map<String, Object> data, String tplCode, String url, String miniProgram) {
        try {
            SendTemplateMessageRequest req = SendTemplateMessageRequest.newBuilder()
                    .setData(JsonSerializer.toJson(data))
                    .setTemplateCode(tplCode)
                    .setUrl(url)
                    .setMiniProgram(miniProgram)
                    .setToUser(openId)
                    .build();
            weChatMessageServiceBlockingStub.sendTemplateMessage(req);
        } catch (Exception e) {
            logger.error("sendOfficialTplMsg(): {}", e.getMessage(), e);
        }
    }
}
