using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.IO;
using System.Text.RegularExpressions;

namespace QQRobotInterface
{
    public partial class _Default : System.Web.UI.Page
    {
        public static Queue que = Queue.Synchronized(new Queue());
        public static Hashtable hashFriends = Hashtable.Synchronized(new Hashtable());
        public static Hashtable hashWenda = Hashtable.Synchronized(new Hashtable());
        public static Hashtable hashHei = Hashtable.Synchronized(new Hashtable());

        public string qq = ConfigurationManager.AppSettings["qq"];
        protected void Page_Load(object sender, EventArgs e)
        {
            //检查授权
            if (!Request.UserHostAddress.Equals(ConfigurationManager.AppSettings["ip"]))
                return;

            if (Request.RequestType.Equals("post", StringComparison.InvariantCultureIgnoreCase))
            {
                string ExternalId = Request.Form["ExternalId"].Trim();
                string Sender = Request.Form["Sender"].Trim();
                string Message = Request.Form["Message"].Trim();

                if (hashHei.Contains(Sender))//黑名单
                {
                    return;
                }

                #region 频率管理，防止攻击
                int count = 0;
                if (Cache[Sender] != null)
                {
                    count = (int)Cache[Sender];
                    Cache.Remove(Sender);
                }
                count = count + 1;

                //计数
                if (count > 20)
                {
                    Cache.Add(Sender, count, null, DateTime.Now.AddMinutes(10), TimeSpan.Zero, System.Web.Caching.CacheItemPriority.High, null);
                    return;
                }
                else if (count > 15)
                {
                    Response.Write("您发送的速度太快了，还是休息一下吧。");
                    Cache.Add(Sender, count, null, DateTime.Now.AddMinutes(1), TimeSpan.Zero, System.Web.Caching.CacheItemPriority.High, null);
                    return;
                }
                else
                {
                    Cache.Add(Sender, count, null, DateTime.Now.AddMinutes(1), TimeSpan.Zero, System.Web.Caching.CacheItemPriority.High, null);
                }
                #endregion


                if (ExternalId == "0")
                {//qq消息

                    string result = ProcessContent(ExternalId, Sender, Message);

                    Response.Write("[font=宋体,9," + new Random().Next(0, 0xffffff).ToString() + "]" + result);
                    #region 监控to4111852
                    if (Sender != qq)
                        que.Enqueue(string.Format("0\n" + qq + "\n{0}对机器人说：{1}", Sender, Message));
                    #endregion
                }
                else if (ExternalId == "-1")
                {//加好友消息
                    Cache["receive"] = string.Format("收到加好友的请求：{0}的消息：{1}", Sender, Message);
                    que.Enqueue("0\n" + qq + "\n" + Sender + "加我为好友");
                    Response.Write(Message + " " + ChangeState());
                }
                else if (ExternalId == "-2")
                {//好友列表
                    StringReader reader = new StringReader(Message);
                    string line = reader.ReadLine();
                    while (line != null)
                    {
                        Match m = Regex.Match(line, @"^(\d+) (ONLINE|OFFLINE|AWAY|HIDDEN) (.*?)$", RegexOptions.Compiled | RegexOptions.IgnoreCase);
                        string qq = m.Groups[1].ToString();
                        string status = m.Groups[2].ToString();
                        string nick = m.Groups[3].ToString();
                        hashFriends[qq] = new string[] { nick, status };
                        line = reader.ReadLine();
                    }
                }
                else if (ExternalId == "-3")
                {//qq签名改变
                    if (Sender == "819512594")
                        return;
                    Cache["receive"] = string.Format("收到QQ：{0}的签名：{1}", Sender, Message);
                    Response.Write(string.Format("{0}，您的新签名很有意思：{1}", Sender, Message));
                }
                else if (ExternalId == "-4")
                {//好友状态改变
                    StringReader reader = new StringReader(Message);
                    string line = reader.ReadLine();
                    while (line != null)
                    {
                        Match m = Regex.Match(line, @"^(\d+) (ONLINE|OFFLINE|AWAY|HIDDEN) (.*?)$", RegexOptions.Compiled | RegexOptions.IgnoreCase);
                        string qq = m.Groups[1].ToString();
                        string status = m.Groups[2].ToString();
                        string nick = m.Groups[3].ToString();
                        hashFriends[qq] = new string[] { nick, status };
                        if (status.Equals("ONLINE", StringComparison.InvariantCultureIgnoreCase))
                            Response.Write(ChangeState());

                        line = reader.ReadLine();
                    }
                }
                else if (ExternalId == "-5")
                {
                    que.Enqueue("0\n" + qq + "\n机器人重启了！！！");
                }
                else if (ExternalId == "-6")
                {
                    que.Enqueue("0\n" + qq + "\n" + Sender + "抖动");
                    Response.Write("再抖就把你吃掉[face16.gif]\n\n增加表情、字体、字号、颜色、接收群图片，用主动触发发送消息机制代替轮询。");
                }
                else if (Regex.IsMatch(ExternalId, @"^\d+$", RegexOptions.Compiled))
                {//群消息处理
                    //que.Enqueue("0\n4111852\n" + ExternalId + "群消息：" + Message);

                    Cache["receive"] = string.Format("收到群：{0}的消息：{1}", ExternalId, Message);

                    string result = ProcessContent(ExternalId, Sender, Message);
                    Response.Write("[font=宋体,9," + new Random().Next(0, 0xffffff).ToString() + "]" + result);
                }
                else
                {
                    que.Enqueue("0\n" + qq + "\n收到QQ：" + Sender + "未知消息");
                    Response.Write("收到QQ：" + Sender + "未知消息");
                }

            }
            else
            {
                if (Request.QueryString["client"] == "msnrobot")
                {
                    //从MSN队列获取
                }
                else
                {
                    //从QQ队列获取
                    if (que.Count > 0)
                    {
                        Response.Write(que.Dequeue() as string);
                    }
                }
                //Response.Write("49076875\n0\n现在时间是：" + DateTime.Now.ToString());//主动给群49076875发送消息
                //Response.Write("0\n4111852\n现在时间是：" + DateTime.Now.ToString());//主动发送QQ消息给4111852
            }
        }

        private string ProcessContent(string ExternalId, string Sender, string Message)
        {
            #region 取消黑名单
            Match m = Regex.Match(Message, @"^白名单 (.*?)$", RegexOptions.Compiled | RegexOptions.IgnoreCase);
            if (m.Success && Sender == qq)
            {
                Cache.Remove(m.Groups[1].Value.Trim());
                hashHei.Remove(m.Groups[1].Value.Trim());
                return m.Groups[1].Value.Trim() + "被移除黑名单";
            }
            #endregion

            #region 黑名单管理
            m = Regex.Match(Message, @"^黑名单 (.*?)$", RegexOptions.Compiled | RegexOptions.IgnoreCase);
            if (m.Success && Sender == qq)
            {
                if (!hashHei.Contains(m.Groups[1].Value.Trim()))
                    hashHei.Add(m.Groups[1].Value.Trim(), string.Empty);
                return m.Groups[1].Value.Trim() + "被列入黑名单";
            }
            #endregion

            #region 发消息
            m = Regex.Match(Message, @"^to (\d+)(.*?)$", RegexOptions.Compiled | RegexOptions.IgnoreCase);
            if (m.Success && Sender == qq)
            {
                que.Enqueue(string.Format("0\n{0}\n{1}", m.Groups[1].Value.Trim(), m.Groups[2].Value.Trim()));
                return "发送成功";
            }
            m = Regex.Match(Message, @"^toq (\d+)(.*?)$", RegexOptions.Compiled | RegexOptions.IgnoreCase);
            if (m.Success && Sender == qq)
            {
                que.Enqueue(string.Format("{0}\n0\n{1}", m.Groups[1].Value.Trim(), m.Groups[2].Value.Trim()));
                return "发送成功";
            }
            #endregion

            #region 修改签名
            m = Regex.Match(Message, @"^签名 (.*?)$", RegexOptions.Compiled | RegexOptions.IgnoreCase);
            if (m.Success && Sender == qq)
            {
                que.Enqueue(string.Format("-4\n{0}", m.Groups[1].Value.Trim()));
                return "签名设置成功[face79.gif]";
            }
            #endregion

            #region 常用功能
            m = Regex.Match(Message, @"^ip (.*?)$", RegexOptions.Compiled | RegexOptions.IgnoreCase);
            if (m.Success)
            {
                return new cn.svnhost.web.WebService().GetIP(m.Groups[1].Value.Trim());
            }
            m = Regex.Match(Message, @"^id (.*?)$", RegexOptions.Compiled | RegexOptions.IgnoreCase);
            if (m.Success)
            {
                return new cn.svnhost.web.WebService().GetUserID(m.Groups[1].Value.Trim());
            }
            if (Message.Trim().Equals("today", StringComparison.InvariantCultureIgnoreCase))
            {
                return new cn.svnhost.web.WebService().History();
            }
            m = Regex.Match(Message, @"^m (.*?)$", RegexOptions.Compiled | RegexOptions.IgnoreCase);
            if (m.Success)
            {
                return new cn.svnhost.web.WebService().Mobile(m.Groups[1].Value.Trim());
            }
            m = Regex.Match(Message, @"^lt (.*?)$", RegexOptions.Compiled | RegexOptions.IgnoreCase);
            if (m.Success)
            {
                return string.Format("http://wpa.qq.com/msgrd?v=3&uin={0}&site=qq&menu=yes", m.Groups[1].Value.Trim());
            }
            m = Regex.Match(Message, @"^tq (.*?)$", RegexOptions.Compiled | RegexOptions.IgnoreCase);
            if (m.Success)
            {
                return new cn.svnhost.web.WebService().Weather(m.Groups[1].Value.Trim());
            }
            m = Regex.Match(Message, @"^((yb)|(qh)) (.*?)$", RegexOptions.Compiled | RegexOptions.IgnoreCase);
            if (m.Success)
            {
                return new cn.svnhost.web.WebService().Zicode(m.Groups[4].Value.Trim());
            }
            m = Regex.Match(Message, @"^alexa (.*?)$", RegexOptions.Compiled | RegexOptions.IgnoreCase);
            if (m.Success)
            {
                return new cn.svnhost.web.WebService().alexa(m.Groups[1].Value.Trim());
            }
            m = Regex.Match(Message, @"^baidu (.*?)$", RegexOptions.Compiled | RegexOptions.IgnoreCase);
            if (m.Success)
            {
                return new cn.svnhost.web.WebService().baidu(m.Groups[1].Value.Trim());
            }
            m = Regex.Match(Message, @"^pr (.*?)$", RegexOptions.Compiled | RegexOptions.IgnoreCase);
            if (m.Success)
            {
                return new cn.svnhost.web.WebService().pr(m.Groups[1].Value.Trim());
            }
            if (Message.Trim().Equals("joke", StringComparison.InvariantCultureIgnoreCase))
            {
                return new cn.svnhost.web.WebService().joke();
            }
            m = Regex.Match(Message, @"^wb (.*?)$", RegexOptions.Compiled | RegexOptions.IgnoreCase);
            if (m.Success)
            {
                return new cn.svnhost.web.WebService().wubi(m.Groups[1].Value.Trim());
            }
            m = Regex.Match(Message, @"^jt (.*?)$", RegexOptions.Compiled | RegexOptions.IgnoreCase);
            if (m.Success)
            {
                return new cn.svnhost.web.WebService().StrConvSimplified(m.Groups[1].Value.Trim());
            }
            m = Regex.Match(Message, @"^ft (.*?)$", RegexOptions.Compiled | RegexOptions.IgnoreCase);
            if (m.Success)
            {
                return new cn.svnhost.web.WebService().StrConvTraditional(m.Groups[1].Value.Trim());
            }
            m = Regex.Match(Message, @"^md5 (.*?)$", RegexOptions.Compiled | RegexOptions.IgnoreCase);
            if (m.Success)
            {
                return System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(m.Groups[1].Value.Trim(), "md5");
            }
            m = Regex.Match(Message, @"^((ems)|(aae)|(anjiekuaidi)|(anxindakuaixi)|(baifudongfang)|(biaojikuaidi)|(bht)|(cces)|(Coe)|(changyuwuliu)|(datianwuliu)|(debangwuliu)|(dpex)|(dhl)|(dsukuaidi)|(fedex)|(feikangda)|(fenghuangkuaidi)|(ganzhongnengda)|(guangdongyouzhengwuliu)|(huitongkuaidi)|(hengluwuliu)|(huaxialongwuliu)|(jiayiwuliu)|(jinguangsudikuaijian)|(jixianda)|(jiajiwuliu)|(jiayunmeiwuliu)|(kuaijiesudi)|(lianhaowuliu)|(longbanwuliu)|(minghangkuaidi)|(peisihuoyunkuaidi)|(quanchenkuaidi)|(quanjitong)|(quanritongkuaidi)|(quanyikuaidi)|(shenghuiwuliu)|(suer)|(shengfengwuliu)|(tiandihuayu)|(tiantian)|(tnt)|(ups)|(wanjiawuliu)|(wenjiesudi)|(wuyuansudi)|(wanxiangwuliu)|(xinbangwuliu)|(xinfengwuliu)|(xingchengjibian)|(xinhongyukuaidi)|(yafengsudi)|(yibangwuliu)|(youshuwuliu)|(yuanchengwuliu)|(yuantong)|(yuanweifeng)|(yuanzhijiecheng)|(yuefengwuliu)|(yunda)|(yuananda)|(Yuntongkuaidi)|(zhaijisong)|(zhongtiewuliu)|(zhongtong)|(zhongyouwuliu)) (.*?)$", RegexOptions.Compiled | RegexOptions.IgnoreCase);
            if (m.Success)
            {
                System.Net.WebClient client = new System.Net.WebClient();
                client.Encoding = System.Text.Encoding.UTF8;
                return client.DownloadString("http://api.kuaidi100.com/api?id=42b8d11f02faa24d&com=" + m.Groups[1].Value.Trim() + "&nu=" + m.Groups[m.Groups.Count - 1].Value.Trim() + "&show=3&muti=1&order=asc");
            }
            if (Message.Equals("kuaidi", StringComparison.InvariantCultureIgnoreCase))
                return @"使用方法，快递公司代码+空格+单号，例如：yuantong 1407157585
快递公司代码  公司名称
ems EMS
aae AAE全球专递
anjiekuaidi 安捷快递
anxindakuaixi 安信达快递
baifudongfang 百福东方
biaojikuaidi 彪记快递
bht BHT
cces 希伊艾斯快递
Coe 中国东方（COE）
changyuwuliu 长宇物流
datianwuliu 大田物流
debangwuliu 德邦物流
dpex DPEX
dhl DHL
dsukuaidi D速快递
fedex fedex
feikangda 飞康达物流
fenghuangkuaidi 凤凰快递
ganzhongnengda 港中能达物流
guangdongyouzhengwuliu 广东邮政物流
huitongkuaidi 汇通快运
hengluwuliu 恒路物流
huaxialongwuliu 华夏龙物流
jiayiwuliu 佳怡物流
jinguangsudikuaijian 京广速递
jixianda 急先达
jiajiwuliu 佳吉物流
jiayunmeiwuliu 加运美
kuaijiesudi 快捷速递
lianhaowuliu 联昊通物流
longbanwuliu 龙邦物流
minghangkuaidi 民航快递
peisihuoyunkuaidi 配思货运
quanchenkuaidi 全晨快递
quanjitong 全际通物流
quanritongkuaidi 全日通快递
quanyikuaidi 全一快递
shenghuiwuliu 盛辉物流
suer 速尔物流
shengfengwuliu 盛丰物流
tiandihuayu 天地华宇
tiantian 天天快递
tnt TNT
ups UPS
wanjiawuliu 万家物流
wenjiesudi 文捷航空速递
wuyuansudi 伍圆速递
wanxiangwuliu 万象物流
xinbangwuliu 新邦物流
xinfengwuliu 信丰物流
xingchengjibian 星晨急便
xinhongyukuaidi 鑫飞鸿物流快递
yafengsudi 亚风速递
yibangwuliu 一邦速递
youshuwuliu 优速物流
yuanchengwuliu 远成物流
yuantong 圆通速递
yuanweifeng 源伟丰快递
yuanzhijiecheng 元智捷诚快递
yuefengwuliu 越丰物流
yunda 韵达快运
yuananda 源安达
Yuntongkuaidi 运通快递
zhaijisong 宅急送
zhongtiewuliu 中铁快运
zhongtong 中通速递
zhongyouwuliu 中邮物流
";


            int a = Message.IndexOf("<Image FileName=\"", StringComparison.CurrentCultureIgnoreCase);
            if (a >= 0)
            {
                a = a + 17;
                int b = Message.IndexOf('"', a + 1);
                if (b > 0)
                {
                    return string.Format("发现图片：http://qun.qq.com/cgi/svr/chatimg/get?pic={0}&gid={2}&time={1}\n\n", Message.Substring(a, b - a), (int)(DateTime.Now - DateTime.Parse("1970-1-1")).TotalSeconds, ExternalId);
                }
            }

            if (Message.Trim().Equals("h", StringComparison.InvariantCultureIgnoreCase))
            {
                return @"
使用方法为命令+空格+参数，可用命令如下
help：查看小I帮助菜单，例如：help
kuaidi：查看快递帮助菜单，例如：kuaid
ip：查询IP地址或者域名所属地，例如：ip svnhost.cn
id：查询身份证号码，例如：id 220103198810101010
today：查询历史上的今天，例如：today
m：查询手机号码归属地，例如：m 15079690000
tq：查询天气预报，例如：tq 上海
joke：讲一个笑话，例如：joke
alexa：查询网站alexa排名，例如：alexa svnhost.cn
baidu：查询网站百度收录数，例如：baidu svnhost.cn
pr：查询网站 Google PR值，例如：pr svnhost.cn
wb：查询五笔字根，例如：wb 发
jt：转化成简体字，例如：jt 我想要轉化成簡體啊
ft：转化成繁体字，例如：ft 我想要转化成简体啊
lt：发起QQ聊天，例如：lt 4111852
md5：计算MD5值，例如：md5 admin
qh：区号，例如：qh 0571或者qh 上海
yb：邮编，例如：yb 0571或者yb 上海
";
            }
            #endregion

            string ret = Xiaoi.xiaoi.chatXiaoi(Message);
            if (!string.IsNullOrEmpty(ret))
                return ret.Replace("\\r", "\r");

            return "您的问题是在太高深了，我还没有学会。[face15.gif]\n您可以发送help来查看我会哪些内容。";
        }

        private string ChangeState()
        {
            string msg = "您好，现在的时间是：" + DateTime.Now.ToString() + "，\n";
            switch (DateTime.Now.Hour)
            {
                case 1:
                    msg += "一点多啦！别忘了休息哦！";
                    break;
                case 2:
                    msg += "你真是工作狂啊，该休息了，身体是革命的本钱！";
                    break;
                case 3:
                    msg += "午夜三点！你还不准备睡觉吗？";
                    break;
                case 4:
                    msg += "凌晨四点多了，一定要把您这种忘我的工作精神上报中央！";
                    break;
                case 5:
                    msg += "您是刚起床还是还没睡啊？";
                    break;
                case 6:
                    msg += "早上好！新一天又开始啦！有什么打算呢？";
                    break;
                case 7:
                    msg += "吃过早饭了吗？";
                    break;
                case 8:
                case 9:
                case 10:
                    msg += "早！又是忙碌的一天！";
                    break;
                case 11:
                    msg += "快中午啦，准备做饭了呀！";
                    break;
                case 12:
                    msg += "中午好！你吃饭了吗？";
                    break;
                case 13:
                case 14:
                    msg += "下午好，准备准备要上班了！";
                    break;
                case 15:
                case 16:
                case 17:
                    msg += "下午好！";
                    break;
                case 18:
                case 19:
                    msg += "新闻联播你看了吗？吃晚饭了没？";
                    break;
                case 20:
                case 21:
                case 22:
                    msg += "别工作了，找个电影看看睡觉吧？";
                    break;
                case 23:
                    msg += "不早了，快休息吧？";
                    break;
                case 0:
                    msg += "午夜时分，你可要注意身体呢！";
                    break;
            }

            //msg += "\n\n短信通上线了，支持从网站给移动、联通、小灵通发送消息，免费支持回复短信。欢迎使用：http://sms.svnhost.cn";
            return msg;
        }
    }
}
