using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
using System.Timers;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Siger.Middlelayer.Common;
using Siger.Middlelayer.Log;

namespace Siger.ApiTPM.Utilities
{
    static class WeChatPushHelper
    {
        private static string APPID = "wx81faa5428f25deb3";

        private static string SECRET = "e7f24125ddcfe6cec9d674d29d3844a5";

        private static string wxtokenssf;

        private static int expiresIn;


        //{{first.DATA}}
        //处理时间：{{keyword1.DATA}}
        //处理结果：{{keyword2.DATA}}
        //{{remark.DATA}}
        //
        //您好，有新的消息通知。
        //处理时间：2019-01-02 11:08
        //处理结果：您的《物业报修申请》已经受理，维修人员将在您的预约时间段（2019-01-03 10:00——11:00）上门维修。
        //感谢您的使用。
        public static string temleteIdMdp = "mdpOK5hrFh_36XoSap06IAeDBsykrBhRo3bhV7T_Woo";

        //{{first.DATA}}
        //计划：{{keyword1.DATA}}
        //关联联系人：{{keyword2.DATA}}
        //计划时间：{{keyword3.DATA}}
        //{{remark.DATA}}
        //
        //您好，根据日历安排，您有以下计划
        //计划：每客笔记的第二笔款项到期，需要沟通回款事宜
        //关联联系人：Pony
        //计划时间：2015-09-09
        //请您及时处理！
        public static string temleteIdS11 = "S11lGmOqHcv3ogeT1L7AG5x_20q4WenIF7gH_AYppH4";


        //{{first.DATA}}
        //异常行为：{{keyword1.DATA}}
        //发生时间：{{keyword2.DATA}}
        //{{remark.DATA}}
        //
        //尊敬的用户，您在本店消费时存在如下违规异常行为
        //异常行为：在禁烟区吸烟
        //发生时间：2017-04-03 13
        //请及时终止违规行为，谢谢合作！
        public static string temleteIdYjf = "YjfMKxQalx8Xo0dSmqqyEVbByNmZQcPyb-XAuHiom6I";

        //{{first.DATA}}
        //设备位置：{{keyword1.DATA}}
        //异常说明：{{keyword2.DATA}}
        //报修时间：{{keyword3.DATA}}
        //{{remark.DATA}}
        //
        //注意，维修工单异常
        //设备位置： 加工四厂-DL 16线-OP30 粗车
        //异常说明：未按时接单
        //报修时间：2018-01-12 15:23
        //请协调资源处理 ~
        public static string temleteIdMls = "mls0Xe_xjvNuxGej7Whx2R0YG2oeJKZjd94-4DjQq2w";

        //{{first.DATA}}
        //工单号：{{keyword1.DATA}}
        //维修设备：{{keyword2.DATA}}
        //维修人：{{keyword3.DATA}}
        //完工时间：{{keyword4.DATA}}
        //{{remark.DATA}}
        //
        //工单已维修完成，请及时验收。
        //工单号：RO20180202170101
        //维修设备：打印机
        //维修人：User
        //完工时间：2018-02-02
        //来自CoolCare设备监测平台
        public static string temleteIdJuj = "JuJS3382VRHf_cS_DyeHs9OsQZqva5FrVNkTmS3R_-Q";

        //{{first.DATA}}
        //工单单号：{{keyword1.DATA}}
        //工单标题：{{keyword2.DATA}}
        //时间：{{keyword3.DATA}}
        //{{remark.DATA}}
        //
        //您的申请已经受理
        //工单单号：CB20170425001
        //工单标题：电脑硬盘坏死
        //时间：2017-04-25
        //您的申请我们已经收到，会尽快处理，请耐心等待！
        public static string temleteIdTbx = "tbxISjWSYVtjzmCwAIy3E4moUtXh3tze6xRbaWxLvLY";


        //{{first.DATA}}
        //工单单号：{{keyword1.DATA}}
        //工单内容：{{keyword2.DATA}}
        //提交时间：{{keyword3.DATA}}
        //{{remark.DATA}}
        //
        //您提交的诉求已经受理
        //工单单号：1234567890
        //工单内容：电脑卡顿。
        //提交时间：2018-12-18 21:39:40
        //您可以点击查看工单受理状态
        public static string temleteIdOiw = "oiWp1XKsqAbCLma-KvIhYfdFC1nk8MLNnfRcTS7yho0";


        //{{first.DATA}}
        //工单编号：{{keyword1.DATA}}
        //工单标题：{{keyword2.DATA}}
        //工单状态：{{keyword3.DATA}}
        //工单处理人：{{keyword4.DATA}}
        //{{remark.DATA}}
        //
        //亲，您的工单有最新进展
        //工单编号：SD000223
        //工单标题：关于陈勇明(ym-chen6)[现场修复桌面软件]的服务请求申请
        //工单状态：已接单
        //工单处理人：冯工程师
        //我们将向您提供100分的服务，请继续等待。
        public static string temleteIdHdj = "Hdjldcro7HDHsIZaYaK733z05r-XvLXME46TmmvDoIM";


        //{{first.DATA}}
        //位置：{{keyword1.DATA}}
        //设备：{{keyword2.DATA}}
        //故障类型：{{keyword3.DATA}}
        //故障内容：{{keyword4.DATA}}
        //工单创建时间：{{keyword5.DATA}}
        //{{remark.DATA}}
        //
        //op30-半精车床出现故障，请前往处理
        //位置：加工四厂-D/C 16L
        //设备：op30-半精车
        //故障类型：机械故障
        //故障内容：自动门卡死
        //工单创建时间：2017-11-17 13:12:32
        //推荐解决方案：检查机械结构
        public static string temleteIdZkg = "ZKG3kFsncwcJyc3xeDz5qGpfCtH__D45nM7z0XDAhdc";

        static WeChatPushHelper()
        {
            try
            {
                string serviceAddress = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + APPID + "&secret=" + SECRET;
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(serviceAddress);
                request.Method = "GET";
                request.ContentType = "application/json;charset=UTF-8";
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                Stream myResponseStream = response.GetResponseStream();
                StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.UTF8);
                string retString = myStreamReader.ReadToEnd();
                myStreamReader.Close();
                myResponseStream.Close();
                //解析josn
                JObject jso = (JObject)JsonConvert.DeserializeObject(retString);
                wxtokenssf = jso["access_token"] != null ? jso["access_token"].ToString() : "";
                expiresIn = jso["expires_in"] != null ? int.Parse(jso["expires_in"].ToString()): 0;
                //Console.WriteLine("----------get wxtoken success-----------");
            }
            catch (Exception ex)
            {
                Logger.WriteLineError("----------get wxtoken failed:" + ex.Message + "-----------");
            }

            if(expiresIn > 0)
            {
                Timer timer = new Timer
                {
                    Enabled = true,
                    Interval = expiresIn * 1000 - 15 * 60 * 1000
                };
                // 提前15分钟刷新token
                //执行间隔时间,单位为毫秒; 这里实际间隔为10分钟  
                timer.Start();
                timer.Elapsed += new ElapsedEventHandler(getToken);
            }
        }

        private static void getToken(object source, ElapsedEventArgs e)
        {
            try
            {
                string serviceAddress = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + APPID + "&secret=" + SECRET;
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(serviceAddress);
                request.Method = "GET";
                request.ContentType = "application/json;charset=UTF-8";
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                Stream myResponseStream = response.GetResponseStream();
                StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.UTF8);
                string retString = myStreamReader.ReadToEnd();
                myStreamReader.Close();
                myResponseStream.Close();
                //解析josn
                JObject jso = (JObject)JsonConvert.DeserializeObject(retString);
                wxtokenssf = jso["access_token"] != null ? jso["access_token"].ToString() : "";
                expiresIn = jso["expires_in"] != null ? int.Parse(jso["expires_in"].ToString()) : 0;
                //Console.WriteLine("----------update wxtoken success-----------");
            }
            catch (Exception ex)
            {
                Logger.WriteLineError("----------update wxtoken failed: " + ex.Message + "-----------");
            }

        }

        public static void testttt()
        {
            Console.WriteLine("I am in testttt!");
        }

        public static void sendMsg(string openId, string templeteId, MessageBean msgPrm)
        {
            try
            {
                if (string.IsNullOrEmpty(wxtokenssf))
                {
                    string serviceTokenAddress = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + APPID + "&secret=" + SECRET;
                    HttpWebRequest tokenRequest = (HttpWebRequest)WebRequest.Create(serviceTokenAddress);
                    tokenRequest.Method = "GET";
                    tokenRequest.ContentType = "application/json;charset=UTF-8";
                    HttpWebResponse tokenResponse = (HttpWebResponse)tokenRequest.GetResponse();
                    Stream myTokenResponseStream = tokenResponse.GetResponseStream();
                    StreamReader myTokenStreamReader = new StreamReader(myTokenResponseStream, Encoding.UTF8);
                    string retString1 = myTokenStreamReader.ReadToEnd();
                    myTokenStreamReader.Close();
                    myTokenResponseStream.Close();
                    //解析josn
                    JObject jso1 = (JObject)JsonConvert.DeserializeObject(retString1);
                    wxtokenssf = jso1["access_token"] != null ? jso1["access_token"].ToString() : "";
                }
                string serviceAddress = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + wxtokenssf;
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(serviceAddress);
                request.Method = "POST";
                request.ContentType = "application/json";

                StringBuilder sb = new StringBuilder();
                sb.Append("{");
                sb.Append(@"""touser"":""");
                sb.Append(openId);
                sb.Append(@""",");
                sb.Append(@"""template_id"":""");
                sb.Append(templeteId);
                sb.Append(@""",");
                sb.Append(@"""data"":{");
                sb.Append(@"""first"":{");
                sb.Append(@"""value"":""");
                sb.Append(msgPrm.firstPrm.value);
                sb.Append(@"""");
                if (!string.IsNullOrEmpty(msgPrm.firstPrm.color))
                {
                    sb.Append(@",""color"":""");
                    sb.Append(msgPrm.firstPrm.color);
                    sb.Append(@"""");
                }
                sb.Append("},");

                List<ContBean> conts = msgPrm.keywordsPrm;

                if (null != conts && conts.Count > 0)
                {
                    for (int i = 0; i < conts.Count; i++)
                    {
                        sb.Append(@"""keyword");
                        sb.Append((i + 1).ToString());
                        sb.Append(@""":{");
                        sb.Append(@"""value"":""");
                        sb.Append(conts[i].value);
                        sb.Append(@"""");
                        if (!string.IsNullOrEmpty(conts[i].color))
                        {
                            sb.Append(@",""color"":""");
                            sb.Append(conts[i].color);
                            sb.Append(@"""");
                        }
                        sb.Append("},");
                    }
                }
                sb.Append(@"""remark"":{");
                sb.Append(@"""value"":""");
                sb.Append(msgPrm.remarkPrm.value);
                sb.Append(@"""");
                if (!string.IsNullOrEmpty(msgPrm.remarkPrm.color))
                {
                    sb.Append(@",""color"":""");
                    sb.Append(msgPrm.remarkPrm.color);
                    sb.Append(@"""");
                }
                sb.Append("}}}");

                using (StreamWriter dataStream = new StreamWriter(request.GetRequestStream()))
                {
                    dataStream.Write(sb.ToString());
                    dataStream.Close();
                }
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                Stream myResponseStream = response.GetResponseStream();
                StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.UTF8);
                string retString = myStreamReader.ReadToEnd();
                myStreamReader.Close();
                myResponseStream.Close();

                //解析josn
                //JObject jso = (JObject)JsonConvert.DeserializeObject(retString);
                //string rtnCode = jso["errcode"].ToString();
                //string rtnMsg = jso["errmsg"].ToString();
                //Logger.WriteLineInfo("------------send msg return code is:" + rtnCode + ", return msg is:" + rtnMsg +
                //                     ", json string is:" + sb.ToString());
            }
            catch (Exception ex)
            {
                Logger.WriteLineError("----------push wechat message failed:" + ex.Message + "-----------");
            }
        }
    }
}
