using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using CallCenter.Utility;
using CallCenterAPI.WechatSDK;
using System.IO;

namespace CallCenterApi.Interface.Controllers.weixin
{
    public class WxReceiveController : Controller
    {
        public ActionResult Index()
        {
            Log log = LogFactory.GetLogger("log");
            string signature = Request["signature"];
            string timestamp = Request["timestamp"];
            string nonce = Request["nonce"];
            string echostr = Request["echostr"];
            //微信公众号-基本设置-服务器配置-令牌(Token)
            var token = "";
            //log.Info($"timestamp={timestamp}　\n  nonce={nonce}  \n  echostr={echostr}");
            if (!RequestString.IsPost())
            {
                if (!WxHelper.CheckSignature(signature, timestamp, nonce, token))
                    return Content("error");
                else
                    return Content(echostr);
            }
            StreamReader srResult = new StreamReader(RequestString.GetInputStream());
            string str = srResult.ReadToEnd();
            // log.Info($"str={str}");
            XmlHelper xml = new XmlHelper();
            xml.LoadFromXmlString(str);

            string openid = xml.GetValue("FromUserName");
            string type = xml.GetValue("MsgType");
            //log.Info($"openid={openid}    type={openid}    ");
            if (type != "event")
            {
                WxHelper.CreateSession(openid);
            }


            return Content("success");
        }
    }
}