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

import com.google.gson.JsonObject;
import com.ywt.outpatient.taihe.rpc.core.utils.Checker;
import com.ywt.outpatient.taihe.rpc.core.utils.StringHelper;
import com.ywt.outpatient.taihe.rpc.domain.entity.center.MedicalCard;
import com.ywt.outpatient.taihe.rpc.domain.entity.center.MedicalCardRepository;
import com.ywt.outpatient.taihe.rpc.domain.entity.center.RegisteredOrder;
import com.ywt.outpatient.taihe.rpc.service.Constants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * 《南方医务通》微信公众号模板消息、客服消息逻辑类
 *
 * @author johnson lin
 * @date 2019/6/27 3:57 PM
 */
@Service
public class NfYwtWeChatMsgService {
    private static final Logger logger = LoggerFactory.getLogger(NfYwtWeChatMsgService.class);

    /**
     * 《南方医务通》公众号 -> 门诊记录 URL
     */
    private static final String ORDER_CENTER_URL = "https://m.ywtinfo.com/nfywtwe/orderCenter";

    @Autowired
    private WeChatMsgProvider weChatMsgProvider;

    @Autowired
    private MedicalCardRepository medicalCardRepository;

    /**
     * 发送挂号成功模板消息
     * <p>
     * 模板（TPL_1015）：
     * "{{first.DATA}}
     * 就诊人：{{keyword1.DATA}}
     * 就诊卡号：{{keyword2.DATA}}
     * 挂号科室：{{keyword3.DATA}}
     * 看诊医生：{{keyword4.DATA}}
     * 就诊时间：{{keyword5.DATA}}
     * {{remark.DATA}}"
     *
     * @param registeredOrder {@link RegisteredOrder}
     */
    public void sendMsgForRegister(RegisteredOrder registeredOrder) {
        String first = "您好，您已预约成功！";
        String hisAdmitAddr = Checker.getStringValue(registeredOrder.getHisAdmitAddress());
        String remark =
                String.format("挂号序号：%s\r\n温馨提示：", Checker.getStringValue(registeredOrder.getHisSeqCode())) +
                        "1、预约挂号成功后，首次就诊患者，就诊前需到门诊一楼大厅圆台前打印健康码。" +
                        "2、请持诊疗卡或健康码到对应诊区，自助机报到就诊，就诊先后以报到为准，过号请重新报到。" +
                        "3、当日挂号当日有效。";
        if (!StringHelper.isNullOrEmpty(hisAdmitAddr)) {
            remark = "就诊地点：\r\n" + hisAdmitAddr + "\r\n" + remark;
        }
        String[] keywords = new String[]{
                registeredOrder.getPatientName(),
                registeredOrder.getHospitalName(),
                registeredOrder.getDeptName(),
                registeredOrder.getDoctorName(),
                String.format("%s %s-%s"
                        , registeredOrder.getRegisteredDate().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"))
                        , registeredOrder.getStartTime()
                        , registeredOrder.getEndTime())
        };
        MessageModel model = new MessageModel()
                .setUserId(registeredOrder.getUserId())
                .setTplCode("TPL_1057")
                .setUrl(ORDER_CENTER_URL)
                .setMiniProgram("")
                .setFirst(first)
                .setRemark(remark)
                .setKeywords(keywords);
        weChatMsgProvider.sendTemplateMessage(model);
    }

    /**
     * 预约取消成功通知
     * <p>
     * 模板（TPL_1056）：
     * <p>
     * "{{first.DATA}}
     * 就诊医院：{{keyword1.DATA}}
     * 就诊科室：{{keyword2.DATA}}
     * 就诊医生：{{keyword3.DATA}}
     * 就诊人：{{keyword4.DATA}}
     * 取消时间：{{keyword5.DATA}}
     * {{remark.DATA}}"
     * <p>
     * "您好，您已成功取消预约！
     * 就诊医院：南方医科大学南方医院
     * 就诊科室：儿科
     * 就诊医生：张三
     * 就诊人：李四
     * 取消时间：2017年6月26日 15:30
     * "
     *
     * @param registeredOrder {@link RegisteredOrder}
     */
    public void sendMsgForCancel(RegisteredOrder registeredOrder) {
        String first = "您好，您已成功退号！";
        String[] keywords = new String[]{
                registeredOrder.getHospitalName(),
                registeredOrder.getDeptName(),
                registeredOrder.getDoctorName(),
                registeredOrder.getPatientName(),
                LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy年MM月dd日 HH:mm"))
        };
        MessageModel model = new MessageModel()
                .setUserId(registeredOrder.getUserId())
                .setTplCode("TPL_1056")
                .setUrl(ORDER_CENTER_URL)
                .setMiniProgram("")
                .setFirst(first)
                .setRemark("")
                .setKeywords(keywords);
        weChatMsgProvider.sendTemplateMessage(model);
    }


    /*
     * 扫码报道消息推送
     *
     *
     */
    public void sendMsgForCheckIn(String name, String queueNo, String deptName, String areaId, String cardNo,
                                  String doctorName, String regTime, String admBoroughDesc, int userId, int hospitalId) {
        String first = "您已报道成功，序列号为" + queueNo + "，请在候诊区等候，，叫号后请到" + admBoroughDesc + "就诊。门诊开诊时间：周一到周五8:00-12:00,13:00-16:00，周六周日：8:00-12:00。";
        String[] keywords = new String[]{
                name, cardNo, deptName, doctorName, regTime
        };
        String remark = "请点击进入详情页面！";
        String mpPath = String.format(Constants.BY_REG_CHECKIN_URL, areaId, cardNo);
        String miniProgram = "";
        if (hospitalId == 41) {
            // todo: 白云小程序，"就诊卡号"字段变成"患者ID"
            MedicalCard medicalCard = medicalCardRepository.getByUserIdAndCardNoAndHospitalId(userId, cardNo, hospitalId);
            if (!Checker.isNone(medicalCard)){
                keywords[1] = medicalCard.getHisPatientId();
            }
            miniProgram = getNfyybyfyMpParamString(mpPath);
        }
        MessageModel model = new MessageModel()
                .setUserId(userId)
                .setTplCode("TPL_2002")
                .setUrl("")
                .setMiniProgram(miniProgram)
                .setFirst(first)
                .setKeywords(keywords)
                .setRemark(remark);
        weChatMsgProvider.sendTemplateMessage(model);
    }


    private String getNfyybyfyMpParamString(String mpPath) {
        JsonObject object = new JsonObject();
        object.addProperty("appid", Constants.NFYYBYFY_WXMP_APP_ID);// 所需跳转到的小程序appid
        object.addProperty("pagepath", "pages/index/index?entry=" + getEncodedURI(mpPath));// 所需跳转到小程序的具体页面路径
        return object.toString();
    }

    private String getEncodedURI(String path) {
        try {
            return URLEncoder.encode(path, StandardCharsets.UTF_8.toString());
        } catch (UnsupportedEncodingException e) {
            logger.error("WxProvider#getEncodedURI(path={} ):\n {}", path, e.getMessage(), e);
            return path;
        }
    }
}
