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


import com.ywt.biz.common.util.Checker;
import com.ywt.biz.common.util.DateUtil;
import com.ywt.biz.common.util.StringHelper;
import com.ywt.gapi.user.GetSnsUserInfoRequest;
import com.ywt.gapi.user.GetSnsUserInfoResponse;
import com.ywt.gapi.user.UserService;
import com.ywt.outpatient.domain.entity.center.RegisterRecord;
import com.ywt.outpatient.domain.entity.center.RegisteredOrder;
import com.ywt.outpatient.service.rpc.Constants;
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.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;

/**
 * 太和微信公众号模板消息、客服消息逻辑类
 *
 * @author johnson lin
 * @date 2019/4/29 9:51 PM
 */
@Service
public class TaiheWeChatMsgService {
    private static Logger logger = LoggerFactory.getLogger(TaiheWeChatMsgService.class);

    @Autowired
    private WeChatMsgProvider weChatMsgProvider;

    @DubboReference
    private UserService userServiceBlockingStub;

    private static int OFFICAIL = 21;
    private static int MIN = 20;


    /**
     * 发送挂号成功模板消息
     * <p>
     * 模板（TPL_1006）：
     * "{{first.DATA}}
     * 就诊人：{{keyword1.DATA}}
     * 就诊卡号：{{keyword2.DATA}}
     * 挂号科室：{{keyword3.DATA}}
     * 看诊医生：{{keyword4.DATA}}
     * 就诊时间：{{keyword5.DATA}}
     * {{remark.DATA}}"
     *
     * @param registeredOrder {@link RegisteredOrder}
     */
    public void sendMsgForRegister(RegisteredOrder registeredOrder) {
        String hisAdmitAddr = Checker.getStringValue(registeredOrder.getHisAdmitAddress());
        String remark =
                String.format("挂号序号：%s\r\n温馨提示：", Checker.getStringValue(registeredOrder.getHisSeqCode())) +
                        "1、预约挂号成功后，首次就诊患者，就诊前需到门诊一楼大厅圆台前打印健康码。" +
                        "2、请持诊疗卡或健康码到对应诊区，自助机报到就诊，就诊先后以报到为准，过号请重新报到。" +
                        "3、当日挂号当日有效。";
        String remarkTaihe = remark;
        String timeStr = String.format("%s %s (%s-%s)", DateUtil.formatDate(registeredOrder.getRegisteredDate(), "yyyy-MM-dd"),
                Checker.getStringValue(registeredOrder.getHisAdmitRange()), registeredOrder.getStartTime(), registeredOrder.getEndTime());
        // 新增对白云医院的兼容
        if (registeredOrder.getHospitalId() == Constants.NFYYBYFY_HOSPITAL_ID) {
            remark = String.format("挂号序号：%s\r\n温馨提示：", Checker.getStringValue(registeredOrder.getHisSeqCode())) +
                    "1、请首次预约挂号的病人，就诊时先到门诊大厅挂号/收费⑤号窗进行身份确认后报到就诊" +
                    "2、就诊请先到分诊台报到，请按预约时段就诊报到，过号请重新报到" +
                    "3、就诊人员需携带身份证原件、佩戴口罩及出示健康码方可入院就诊" +
                    "4、就诊当日有效";
            // 白云显示具体时间段
            timeStr = String.format("%s %s-%s", DateUtil.formatDate(registeredOrder.getRegisteredDate(), "yyyy-MM-dd"),
                    Checker.getStringValue(registeredOrder.getStartTime()), Checker.getStringValue(registeredOrder.getEndTime()));
        }
        if (!StringHelper.isNullOrEmpty(hisAdmitAddr)) {
            remark = "就诊地点：" + hisAdmitAddr + "\r\n" + remark;
            remarkTaihe = "就诊地点：" + hisAdmitAddr + "\r\n" + remarkTaihe;
        }
        int hospitalId = Checker.getIntegerValue(registeredOrder.getHospitalId());
        String[] keywords =
                {
                        registeredOrder.getPatientName(),
                        registeredOrder.getMedicalCardNo(),
                        registeredOrder.getDeptName(),
                        registeredOrder.getDoctorName(),
                        timeStr
                };
        // todo: 白云小程序，"就诊卡号"字段变成"患者ID"
        if (hospitalId == Constants.NFYYBYFY_HOSPITAL_ID) {
            keywords[1] = registeredOrder.getHisPatientId();
        }
        String url = "";
        String miniProgram = "";
        if (hospitalId == Constants.TAIHE_HOSPITAL_ID) {
            // 太和跳往公众号
            url = Constants.GET_YWT_HTTPS_MSITE_DOMAIN + Constants.TH_REGISTER_INFO_ORDER_CENTER_URL;
        } else if (hospitalId == Constants.NFYYBYFY_HOSPITAL_ID) {
            // 白云跳往小程序
            String pagePath = Constants.BY_REGISTER_INFO_ORDER_CENTER_LIST;
            miniProgram = weChatMsgProvider.getMiniProgramParam(Constants.NFYYBYFY_WXMP_APP_ID, pagePath);
        }
        MessageModel model = new MessageModel()
                .setUserId(registeredOrder.getUserId())
                .setTplCode(getTplMsgCodeForRegister(hospitalId))
                .setUrl(url)
                .setMiniProgram(miniProgram)
                .setFirst("您好，您已预约成功！")
                .setRemark(remark)
                .setKeywords(keywords);
        weChatMsgProvider.sendTemplateMessage(model);
        // 白云小程序挂太和的号再发一条消息到白云公众号
        if (hospitalId == Constants.TAIHE_HOSPITAL_ID && Checker.getIntegerValue(registeredOrder.getSource()) == 20) {
            logger.info("TaiheWeChatMsgService#sendMsgForRegister(): 白云小程序挂太和的号再发一条消息到白云公众号");


                GetSnsUserInfoResponse response = userServiceBlockingStub.getSnsUserInfo(GetSnsUserInfoRequest.newBuilder()
                        .setUserId(registeredOrder.getUserId())
                        .setTerminal(OFFICAIL)
                        .build());
                String openId = "";
                String unionId = "";
                if (response.getCode() != 0 || (response.getCode() == 0 && Checker.isNone(response.getSnsUserInfo().getOpenId()))) {

                    String patientName = "";
                    String hisPatientId = "";
//                    MedicalCard card = medicalCardRepository.getById(request.getMedicalCardId());
//                    if(!Checker.isNone(card)){
//                        patientName = Checker.getStringValue(card.getPatientName());
//                        hisPatientId = Checker.getStringValue(card.getHisPatientId());
//                    }
                    String templateId = "oc7voZXzm5s4UYQp-6LKSPfAjUIV9RW-B8rmTDx1DUU";
                    String page = Constants.REGISTER_DETAIL;
                    Map<String, String> keywordMap = new HashMap();
                    keywordMap.put("thing22",  registeredOrder.getPatientName());
                    keywordMap.put("character_string11", registeredOrder.getMedicalCardNo());
                    keywordMap.put("thing5",    registeredOrder.getDeptName());
                    keywordMap.put("thing19",  registeredOrder.getDoctorName());
                    timeStr = String.format("%s %s-%s", DateUtil.formatDate(registeredOrder.getRegisteredDate(), "yyyyMMdd"),
                             registeredOrder.getStartTime(), registeredOrder.getEndTime());
                    keywordMap.put("thing16",  timeStr);
                    logger.info("sendMsgForRegister, timeSrt: {}, size: {}", timeStr, timeStr.length());
                    GetSnsUserInfoResponse snsResponse = userServiceBlockingStub.getSnsUserInfo(GetSnsUserInfoRequest.newBuilder()
                            .setUserId(registeredOrder.getUserId())
                            .setTerminal(MIN)
                            .build());
                    if (snsResponse.getCode() == 0 ) {
                        openId = snsResponse.getSnsUserInfo().getOpenId();
                        weChatMsgProvider.sendMPSubscribeMessage(MIN, openId, templateId, page, keywordMap);
                    }


                } else {
                    model.setTplCode(getTplMsgCodeForRegister(Constants.NFYYBYFY_HOSPITAL_ID));
                    model.setRemark(remarkTaihe);
                    weChatMsgProvider.sendTemplateMessage(model);
                }
        }
    }

    private String getTplMsgCodeForRegister(Integer hospitalId) {
        switch (Checker.getIntegerValue(hospitalId)) {
            case Constants.TAIHE_HOSPITAL_ID:
                return "TPL_1006";
            case Constants.NFYYBYFY_HOSPITAL_ID:
                return "TPL_2001";
            default:
                return "";
        }
    }

    /**
     * 无诊疗卡预约挂号成功模板消息
     * <p>
     * 模板（TPL_1006）：
     * "{{first.DATA}}
     * 就诊人：{{keyword1.DATA}}
     * 就诊卡号：{{keyword2.DATA}}
     * 挂号科室：{{keyword3.DATA}}
     * 看诊医生：{{keyword4.DATA}}
     * 就诊时间：{{keyword5.DATA}}
     * {{remark.DATA}}"
     *
     * @param record {@link RegisterRecord}
     */
    public void sendMsgForRegisterWithoutMedicalCard(RegisterRecord record) {
        String first = "您好，您已预约成功！（境外人士专用）";
        String remark = "温馨提醒：请就诊当天带上证件前往医院窗口进行取号，取号后直接前往门诊科室就诊。";
        String[] keywords =
                {
                        record.getPatientName(),
                        "境外人士",
                        record.getDeptName(),
                        record.getDoctorName(),
                        String.format("%s %s-%s"
                                , record.getRegisteredDate().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"))
                                , record.getStartTime()
                                , record.getEndTime())
                };
        MessageModel model = new MessageModel()
                .setUserId(record.getUserId())
                .setTplCode(getTplMsgCodeForRegister(record.getHospitalId()))
                .setUrl("")
                .setMiniProgram("")
                .setFirst(first)
                .setRemark(remark)
                .setKeywords(keywords);
        weChatMsgProvider.sendTemplateMessage(model);
    }

    /**
     * 发送取消预约挂号模板消息
     * <p>
     * 模板（TPL_1002）：
     *
     * @param registeredOrder {@link RegisteredOrder}
     */
    public void sendMsgForCancel(RegisteredOrder registeredOrder) {
        String[] keywords =
                {
                        Constants.TAIHE_HOSPITAL_NAME,
                        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_1002")
                .setUrl("https://m.ywtinfo.com/nfthwe/orderCenter")
                .setMiniProgram("")
                .setFirst("您好，您已成功退号！")
                .setRemark("")
                .setKeywords(keywords);
        weChatMsgProvider.sendTemplateMessage(model);
    }

    public void notifyCancel4NFYYBYFY(int userId, String hospitalName, String patientName, String doctorName, String regDateStr) {
        final String tplCode = "TPL_2006";
        final String url = "";
        final String miniProgram = "";
        final String first = "您好，您预约的号源已经成功取消。取消号源信息如下：";
        final String remark = "";
        String[] keynotes = {
                patientName,
                regDateStr,
                doctorName,
                hospitalName
        };
        MessageModel model = new MessageModel()
                .setUserId(userId)
                .setTplCode(tplCode)
                .setUrl(url)
                .setMiniProgram(miniProgram)
                .setFirst(first)
                .setRemark(remark)
                .setKeynotes(keynotes);
        weChatMsgProvider.sendTemplateMessage(model);
    }

    /**
     * 取号成功通知
     *
     * <p>
     * 太和公众号优化需求V1.2.5修改（2019/4/22 18:24）：
     * 1、不显示当前排队人数
     * 2、通知改为不可跳转，final String url = String.format("https://m.ywtinfo.com/nfthwe/waitingTreatmentCount/%s", registrationId);
     * <p>
     * <p>
     * 模板（TPL_1005）：
     * {{first.DATA}}
     * 当前排号：{{keyword1.DATA}}
     * 取号时间：{{keyword2.DATA}}
     * {{remark.DATA}}
     * <p>
     * 您好，取号成功！
     * 当前排号：12
     * 取号时间：2014-10-30 18:40
     * "
     *
     * @param registeredOrder {@link RegisteredOrder}
     */
    public void sendMsgForTook(RegisteredOrder registeredOrder) {
        String[] keywords =
                {
                        "--",
                        LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"))
                };
        MessageModel model = new MessageModel()
                .setUserId(registeredOrder.getUserId())
                .setTplCode("TPL_1005")
                .setUrl("")
                .setMiniProgram("")
                .setFirst("您好，取号成功！")
                .setRemark("")
                .setKeywords(keywords);
        weChatMsgProvider.sendTemplateMessage(model);
    }

    public void sendMsgForMriBooking(int userId, String name, String mobile, String date) {
        String[] keywords = {
                name, mobile, date
        };
        String first = "您的预约已申请成功，预约信息为：";
        String remark = "请等待客服人员电话联系";
        MessageModel model = new MessageModel()
                .setUserId(userId)
                .setTplCode("TPL_8050")
                .setUrl("")
                .setMiniProgram("")
                .setFirst(first)
                .setRemark(remark)
                .setKeywords(keywords);
        weChatMsgProvider.sendTemplateMessage(model);
    }

    public void sendMsgForCreateMedicalCard(int userId, String cardNo, String name, String sexy, String age, int hospital) {
        String first = "";
        String remark = "";
        String[] keywords = {
                cardNo, name, sexy, age
        };
        String url = "";
        if (hospital == Constants.TAIHE_HOSPITAL_ID) {
            url = String.format(Constants.TH_MEDICALCARD_URL, 0, 0);
        }
        String tplCode = "TPL_012049";
        if (hospital == Constants.NFYYBYFY_HOSPITAL_ID) {
            tplCode = "TPL_021005";
        }
        String mpPath = String.format(Constants.BY_MEDICALCARD_URL, 0, 0);
        String miniProgram = (hospital == Constants.NFYYBYFY_HOSPITAL_ID) ? weChatMsgProvider.getNfyybyfyMpParamString(mpPath) : "";
        MessageModel model = new MessageModel()
                .setUserId(userId)
                .setTplCode(tplCode)
                .setUrl(url)
                .setMiniProgram(miniProgram)
                .setFirst(first)
                .setRemark(remark)
                .setKeywords(keywords);
        weChatMsgProvider.sendTemplateMessage(model);

    }
}
