package com.yihu.wlyy.wechat.process;

import com.yihu.wlyy.util.SystemConf;
import com.yihu.wlyy.wechat.util.WeiXinMessageReplyUtils;
import com.yihu.wlyy.wechat.util.WeiXinMessageUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.util.*;

/**
 * 微信事件处理
 * <p>
 * Created by lyr on 2016/08/11.
 */
@Component
public class WeiXinEventProcess {

    /**
     * 微信推送事件处理
     *
     * @param message
     * @return
     */
    public static String eventProcess(Map<String, String> message) throws Exception {
        String result = "";
        String event = message.get("Event");

        switch (event) {
            case WeiXinMessageUtils.EVENT_TYPE_SCAN: // 扫描二维码事件
                result = scanEventProcess(message);
                break;
            case WeiXinMessageUtils.EVENT_TYPE_SUBSCRIBE: // 订阅事件
                if (message.containsKey("EventKey") && StringUtils.isNotEmpty(message.get("EventKey")) && message.containsKey("Ticket")
                        && StringUtils.isNotEmpty(message.get("Ticket"))) {
                    result = scanEventProcess(message);
                } else {
                    result = subscribeEventProcess(message);
                }
                break;
            case WeiXinMessageUtils.EVENT_TYPE_CLICK: //菜单点击
                result = WeiXinEventProcess.clickProcess(message);
            default:
                break;
        }

        return result;
    }

    /**
     * 微信菜单点击处理
     *
     * @param message
     * @return
     */
    public static String clickProcess(Map<String, String> message) throws Exception {
        String result = "";
        if (message.get("EventKey").equals("caozuoshuoming")) {

            String tempStr = clickEventProcess(message);
            /*int firsIndex = tempStr.indexOf("<item>");
            String result1 = tempStr.substring(0,firsIndex-1);
            int secondIndex = tempStr.indexOf("<item>",firsIndex+10);
            String result2 = tempStr.substring(secondIndex-1);*/
            result = tempStr.replace("<ArticleCount>5</ArticleCount>", "<ArticleCount>4</ArticleCount>");
        }
        if (message.get("EventKey").equals("jiankangdangan")) {
            result = clickEventProcessMenu(message);
        }
        return result;
    }

    /**
     * 菜单点击消息发送
     *
     * @param message
     * @return
     * @throws Exception
     */
    private static String clickEventProcess(Map<String, String> message) throws Exception {
        String result = "";
        // 配置信息
        Properties systemConf = SystemConf.getInstance().getSystemProperties();
        // 图文信息
        List<Map<String, String>> articles = new ArrayList<>();


        Map<String, String> articleConsult = new HashMap<>();
        // 图文URL
        String urlConsult = systemConf.getProperty("patient_consult_url");
        // 图文消息图片URL
        String picUrlConsult = systemConf.getProperty("patient_operatinginstrutions_pic_url");
        // URL设置服务器URL、AppId
        urlConsult = urlConsult.replace("{server}", systemConf.getProperty("wechat_base_url"))
                .replace("{appId}", systemConf.getProperty("appId"));
        //图片地址
        picUrlConsult = picUrlConsult.replace("{server}", systemConf.getProperty("server_url"));

        articleConsult.put("Url", urlConsult);
        articleConsult.put("Title", "医生咨询功能使用说明");
        articleConsult.put("Description", "功能使用说明");
        articleConsult.put("PicUrl", picUrlConsult);

        articles.add(articleConsult);

        Map<String, String> articleBooking = new HashMap<>();
        // 图文URL
        String urlBooking = systemConf.getProperty("patient_booking_url");
        // 图文消息图片URL
        String picUrlBooking = systemConf.getProperty("patient_booking_pic_url");
        // URL设置服务器URL、AppId
        urlBooking = urlBooking.replace("{server}", systemConf.getProperty("wechat_base_url"))
                .replace("{appId}", systemConf.getProperty("appId"));
        //图片地址
        picUrlBooking = picUrlBooking.replace("{server}", systemConf.getProperty("server_url"));

        articleBooking.put("Url", urlBooking);
        articleBooking.put("Title", "预约挂号功能使用说明");
        articleBooking.put("Description", "功能使用说明");
        articleBooking.put("PicUrl", picUrlBooking);

        articles.add(articleBooking);

        Map<String, String> articleDevice = new HashMap<>();
        // 图文URL
        String urlDevice = systemConf.getProperty("patient_device_url");
        // 图文消息图片URL
        String picUrlDevice = systemConf.getProperty("patient_device_pic_url");
        // URL设置服务器URL、AppId
        urlDevice = urlDevice.replace("{server}", systemConf.getProperty("wechat_base_url"))
                .replace("{appId}", systemConf.getProperty("appId"));
        //图片地址
        picUrlDevice = picUrlDevice.replace("{server}", systemConf.getProperty("server_url"));

        articleDevice.put("Url", urlDevice);
        articleDevice.put("Title", "体征设备管理功能使用说明");
        articleDevice.put("Description", "功能使用说明");
        articleDevice.put("PicUrl", picUrlDevice);

        articles.add(articleDevice);

        Map<String, String> articleFamily = new HashMap<>();
        // 图文URL
        String urlFamily = systemConf.getProperty("patient_family_url");
        // 图文消息图片URL
        String picUrlFamily = systemConf.getProperty("patient_family_pic_url");
        // URL设置服务器URL、AppId
        urlFamily = urlFamily.replace("{server}", systemConf.getProperty("wechat_base_url"))
                .replace("{appId}", systemConf.getProperty("appId"));
        //图片地址
        picUrlFamily = picUrlFamily.replace("{server}", systemConf.getProperty("server_url"));

        articleFamily.put("Url", urlFamily);
        articleFamily.put("Title", "我的家庭功能使用说明");
        articleFamily.put("Description", "功能使用说明");
        articleFamily.put("PicUrl", picUrlFamily);

        articles.add(articleFamily);

        // 构建回复消息XML
        result = WeiXinMessageReplyUtils.replyNewsMessage(message.get("FromUserName"), message.get("ToUserName"), articles);

        return result;
    }


    /**
     * 菜单点击消息发送
     *
     * @param message
     * @return
     * @throws Exception
     */
    private static String clickEventProcessMenu(Map<String, String> message) throws Exception {
        String result = "";
        // 配置信息
        Properties systemConf = SystemConf.getInstance().getSystemProperties();
        // 图文信息
        List<Map<String, String>> articles = new ArrayList<>();
        //就诊记录
        Map<String, String> articleVisit = new HashMap<>();
        String visit = systemConf.getProperty("patient_visit_url");
        // 图文消息图片URL
        String visit_pic = systemConf.getProperty("patient_visit_pic");
        // URL设置服务器URL、AppId
        visit = visit.replace("{server}", systemConf.getProperty("wechat_base_url"))
                .replace("{appId}", systemConf.getProperty("appId"));
        //图片地址
        visit_pic = visit_pic.replace("{server}", systemConf.getProperty("server_url"));

        articleVisit.put("Url", visit);
        articleVisit.put("Title", "就诊记录");
        articleVisit.put("Description", "就诊记录");
        articleVisit.put("PicUrl", visit_pic);
        articles.add(articleVisit);

        //#检查检验
        Map<String, String> articleInspect = new HashMap<>();
        // 图文URL
        String inspect = systemConf.getProperty("patient_inspect_url");
        // 图文消息图片URL
        String inspect_pic = systemConf.getProperty("patient_inspect_pic");
        // URL设置服务器URL、AppId
        inspect = inspect.replace("{server}", systemConf.getProperty("wechat_base_url"))
                .replace("{appId}", systemConf.getProperty("appId"));
        //图片地址
        inspect_pic = inspect_pic.replace("{server}", systemConf.getProperty("server_url"));

        articleInspect.put("Url", inspect);
        articleInspect.put("Title", "检查检验");
        articleInspect.put("Description", "检查检验");
        articleInspect.put("PicUrl", inspect_pic);
        articles.add(articleInspect);

        Map<String, String> articleExamination = new HashMap<>();
        // 图文URL
        String examination = systemConf.getProperty("patient_examination_url");
        // 图文消息图片URL
        String examination_pic = systemConf.getProperty("patient_examination_pic");
        // URL设置服务器URL、AppId
        examination = examination.replace("{server}", systemConf.getProperty("wechat_base_url"))
                .replace("{appId}", systemConf.getProperty("appId"));
        //图片地址
        examination_pic = examination_pic.replace("{server}", systemConf.getProperty("server_url"));

        articleExamination.put("Url", examination);
        articleExamination.put("Title", "社区体检");
        articleExamination.put("Description", "社区体检");
        articleExamination.put("PicUrl", examination_pic);
        articles.add(articleExamination);
        // 构建回复消息XML
        result = WeiXinMessageReplyUtils.replyNewsMessage(message.get("FromUserName"), message.get("ToUserName"), articles);

        return result;
    }


    /**
     * 关注事件消息发送
     *
     * @param message
     * @return
     * @throws Exception
     */
    private static String subscribeEventProcess(Map<String, String> message) throws Exception {
        String result = "";
        // 配置信息
        Properties systemConf = SystemConf.getInstance().getSystemProperties();
        // 图文信息
        List<Map<String, String>> articles = new ArrayList<>();

        Map<String, String> article = new HashMap<>();
        // 图文URL
        String url = systemConf.getProperty("doctor_subscribe_url");
        // 图文消息图片URL
        String picUrl = systemConf.getProperty("doctor_qrcode_pic_url");
        // URL设置服务器URL、AppId
        url = url.replace("{server}", systemConf.getProperty("wechat_base_url"))
                .replace("{appId}", systemConf.getProperty("appId"));
        //图片地址
        picUrl = picUrl.replace("{server}", systemConf.getProperty("server_url"));

        article.put("Url", url);
        article.put("Title", "欢迎关注厦门i健康，快来签约家庭医生吧~");
        article.put("Description", "请点击查看家庭签约");
        article.put("PicUrl", picUrl);

        articles.add(article);

        //设置共有的图文消息
        setUrlItems(articles, systemConf);

        // 构建回复消息XML
        result = WeiXinMessageReplyUtils.replyNewsMessage(message.get("FromUserName"), message.get("ToUserName"), articles);

        return result;
    }

    /**
     * 设置微信公共的图文消息
     *
     * @param articles
     */
    public static void setUrlItems(List<Map<String, String>> articles, Properties systemConf) {
        Map<String, String> articleConsult = new HashMap<>();
        // 图文URL
        String urlConsult = systemConf.getProperty("patient_consult_url");
        // 图文消息图片URL
        String picUrlConsult = systemConf.getProperty("patient_operatinginstrutions_pic_url");
        // URL设置服务器URL、AppId
        urlConsult = urlConsult.replace("{server}", systemConf.getProperty("wechat_base_url"))
                .replace("{appId}", systemConf.getProperty("appId"));
        //图片地址
        picUrlConsult = picUrlConsult.replace("{server}", systemConf.getProperty("server_url"));

        articleConsult.put("Url", urlConsult);
        articleConsult.put("Title", "医生咨询功能使用说明");
        articleConsult.put("Description", "功能使用说明");
        articleConsult.put("PicUrl", picUrlConsult);

        articles.add(articleConsult);

        Map<String, String> articleBooking = new HashMap<>();
        // 图文URL
        String urlBooking = systemConf.getProperty("patient_booking_url");
        // 图文消息图片URL
        String picUrlBooking = systemConf.getProperty("patient_booking_pic_url");
        // URL设置服务器URL、AppId
        urlBooking = urlBooking.replace("{server}", systemConf.getProperty("wechat_base_url"))
                .replace("{appId}", systemConf.getProperty("appId"));
        //图片地址
        picUrlBooking = picUrlBooking.replace("{server}", systemConf.getProperty("server_url"));

        articleBooking.put("Url", urlBooking);
        articleBooking.put("Title", "预约挂号功能使用说明");
        articleBooking.put("Description", "功能使用说明");
        articleBooking.put("PicUrl", picUrlBooking);

        articles.add(articleBooking);

        Map<String, String> articleDevice = new HashMap<>();
        // 图文URL
        String urlDevice = systemConf.getProperty("patient_device_url");
        // 图文消息图片URL
        String picUrlDevice = systemConf.getProperty("patient_device_pic_url");
        // URL设置服务器URL、AppId
        urlDevice = urlDevice.replace("{server}", systemConf.getProperty("wechat_base_url"))
                .replace("{appId}", systemConf.getProperty("appId"));
        //图片地址
        picUrlDevice = picUrlDevice.replace("{server}", systemConf.getProperty("server_url"));

        articleDevice.put("Url", urlDevice);
        articleDevice.put("Title", "体征设备管理功能使用说明");
        articleDevice.put("Description", "功能使用说明");
        articleDevice.put("PicUrl", picUrlDevice);

        articles.add(articleDevice);

        Map<String, String> articleFamily = new HashMap<>();
        // 图文URL
        String urlFamily = systemConf.getProperty("patient_family_url");
        // 图文消息图片URL
        String picUrlFamily = systemConf.getProperty("patient_family_pic_url");
        // URL设置服务器URL、AppId
        urlFamily = urlFamily.replace("{server}", systemConf.getProperty("wechat_base_url"))
                .replace("{appId}", systemConf.getProperty("appId"));
        //图片地址
        picUrlFamily = picUrlFamily.replace("{server}", systemConf.getProperty("server_url"));

        articleFamily.put("Url", urlFamily);
        articleFamily.put("Title", "我的家庭功能使用说明");
        articleFamily.put("Description", "功能使用说明");
        articleFamily.put("PicUrl", picUrlFamily);

        articles.add(articleFamily);
    }

    /**
     * 微信扫码事件处理
     *
     * @param message
     * @return
     * @throws Exception
     */
    private static String scanEventProcess(Map<String, String> message) throws Exception {
        String result = "";
        // 场景值
        String eventKey = message.get("EventKey");

        if (StringUtils.isNotEmpty(eventKey) && (eventKey.startsWith("qr_") ||
                eventKey.startsWith("qrscene_qr_"))) {
            // 配置
            Properties systemConf = SystemConf.getInstance().getSystemProperties();
            // 图文信息
            List<Map<String, String>> articles = new ArrayList<>();
            Map<String, String> article = new HashMap<>();
            // 医生二维码跳转URL
            String url = systemConf.getProperty("doctor_qrcode_url");
            // 图片URL
            String picUrl = systemConf.getProperty("doctor_qrcode_pic_url");
            // 二维码参数
            String[] keys = eventKey.replace("qrscene_qr_", "").replace("qr_", "").split("_");

            // 图文消息URL
            url = url.replace("{server}", systemConf.getProperty("wechat_base_url"))
                    .replace("{appId}", systemConf.getProperty("appId"))
                    .replace("{doctorCode}", keys[0]);
            //图片地址
            picUrl = picUrl.replace("{server}", systemConf.getProperty("server_url"));

            article.put("Url", url);
            article.put("Title", keys[1] + "医生签约");
            article.put("Description", "请点击查看医生详情并申请签约");
            article.put("PicUrl", picUrl);

            articles.add(article);

            //设置通用链接
            setUrlItems(articles, systemConf);
            //加入续签图文
            Map videoText = getNews("patient_sign_again_url", "patient_sign_again_pic_url", "家庭医生续签提醒", null);
            articles.add(videoText);
            // 消息XML
            result = WeiXinMessageReplyUtils.replyNewsMessage(message.get("FromUserName"), message.get("ToUserName"), articles);
        } else if (StringUtils.isNotEmpty(eventKey) && (eventKey.startsWith("hs_") ||
                eventKey.startsWith("qrscene_hs_"))) {
            // 配置信息
            Properties systemConf = SystemConf.getInstance().getSystemProperties();
            // 图文信息
            List<Map<String, String>> articles = new ArrayList<>();
            Map<String, String> article = new HashMap<>();
            // 社区二维码跳转URL
            String url = systemConf.getProperty("doctor_hos_qrcode_url");
            // 图片URL
            String picUrl = systemConf.getProperty("doctor_qrcode_pic_url");
            // 二维码参数
            String[] keys = eventKey.replace("qrscene_hs_", "").replace("hs_", "").split("_");

            // 图文消息URL
            url = url.replace("{server}", systemConf.getProperty("wechat_base_url"))
                    .replace("{appId}", systemConf.getProperty("appId"))
                    .replace("{hospital}", keys[0] + ":" + keys[1]);
            //图片地址
            picUrl = picUrl.replace("{server}", systemConf.getProperty("server_url"));

            article.put("Url", url);
            article.put("Title", keys[1]);
            article.put("Description", "请点击查看社区详情");
            article.put("PicUrl", picUrl);

            articles.add(article);
            //设置通用链接
            setUrlItems(articles, systemConf);
            //加入续签图文
            Map videoText = getNews("patient_sign_again_url", "patient_sign_again_pic_url", "家庭医生续签提醒", null);
            articles.add(videoText);
            // 消息XML
            result = WeiXinMessageReplyUtils.replyNewsMessage(message.get("FromUserName"), message.get("ToUserName"), articles);
        } else if (StringUtils.isNotEmpty(eventKey) && (eventKey.startsWith("tw_") ||
                eventKey.startsWith("qrscene_tw_"))) {
            // 配置信息
            Properties systemConf = SystemConf.getInstance().getSystemProperties();
            // 图文信息
            List<Map<String, String>> articles = new ArrayList<>();
            Map<String, String> article = new HashMap<>();
            // 区二维码跳转URL
            String url = systemConf.getProperty("doctor_town_qrcode_url");
            // 图片URL
            String picUrl = systemConf.getProperty("doctor_qrcode_pic_url");
            // 二维码参数
            String[] keys = eventKey.replace("qrscene_tw_", "").replace("tw_", "").split("_");

            // 图文消息URL
            url = url.replace("{server}", systemConf.getProperty("wechat_base_url"))
                    .replace("{appId}", systemConf.getProperty("appId"))
                    .replace("{town}", keys[0]);
            //图片地址
            picUrl = picUrl.replace("{server}", systemConf.getProperty("server_url"));

            article.put("Url", url);
            article.put("Title", keys[1]);
            article.put("Description", "请点击查看区详情");
            article.put("PicUrl", picUrl);

            articles.add(article);
            //设置通用链接
            setUrlItems(articles, systemConf);
            //加入续签图文
            Map videoText = getNews("patient_sign_again_url", "patient_sign_again_pic_url", "家庭医生续签提醒", null);
            articles.add(videoText);
            // 消息XML
            result = WeiXinMessageReplyUtils.replyNewsMessage(message.get("FromUserName"), message.get("ToUserName"), articles);
        }

        return result;
    }

    /**
     * 构建单个图文消息工具类
     *
     * @param url         跳转URL
     * @param picUrl      图片地址
     * @param title       图文标题
     * @param description 图文描述
     * @return
     */
    public static Map getNews(String url, String picUrl, String title, String description) {
        Properties systemConf = SystemConf.getInstance().getSystemProperties();
        Map<String, String> news = new HashMap<>();
        // 图文URL
        String targetUrl = systemConf.getProperty(url);
        // 图文消息图片URL
        String pictureUrl = systemConf.getProperty(picUrl);
        // URL设置服务器URL、AppId
        targetUrl = targetUrl.replace("{server}", systemConf.getProperty("wechat_base_url"))
                .replace("{appId}", systemConf.getProperty("appId"));
        //图片地址
        pictureUrl = pictureUrl.replace("{server}", systemConf.getProperty("server_url"));
        System.out.println("url ====> " + targetUrl);
        System.out.println("picurl ======> " + pictureUrl);
        news.put("Url", targetUrl);
        if (StringUtils.isNotEmpty(title)) {
            news.put("Title", title);
        }
        if (StringUtils.isNotEmpty(description)) {
            news.put("Description", description);
        }
        news.put("PicUrl", pictureUrl);
        return news;
    }

    /**
     * 居民微信回复关键字处理
     *
     * @param message
     * @return
     */
    public static String replyKeyword(Map<String, String> message) throws Exception {
        String result = "";
        String description = "您的家庭医生签约将于6月30日到期，为了能继续给您提供健康服务，诚邀您续签家庭医生。";
        String description1 = "为了能给您提供健康服务，诚邀您签签约家庭医生。";
        // 图文信息
        List<Map<String, String>> articles = new ArrayList<>();
        Map videoText = getNews("doctor_subscribe_url", "doctor_qrcode_pic_url", "欢迎关注厦门i健康，快来签约家庭医生吧~", null);
        Map videoText1 = getNews("patient_sign_again_url", "patient_sign_again_pic_url", "家庭医生续签提醒", null);
        articles.add(videoText);
        articles.add(videoText1);
        // 构建回复消息XML
        result = WeiXinMessageReplyUtils.replyNewsMessage(message.get("FromUserName"), message.get("ToUserName"), articles);
        return result;
    }

}
