﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Runtime.Serialization;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.UI;
using ICaiBan.BLL.Job;
using ICaiBan.Framework.Core;
using ICaiBan.ModelAPI;
using ICaiBan.Remoting.Client;
using ICaiBan.Utility;

namespace ICaiBan.API.Job
{
    public partial class JobAPI : System.Web.UI.Page
    {
        readonly ICaiBan.IBLL.IJob _ibll = (ICaiBan.IBLL.IJob)InvokeRemoting.GetObj<ICaiBan.IBLL.IJob>();

        protected void Page_Load(object sender, EventArgs e)
        {
            ICaiBan.Framework.Core.IO.LogStep.Init("调度接口");

            ReturnData result = Main();
            string resultJso = ReturnData.ToJson(result);
            ICaiBan.Framework.Core.IO.LogStep.Add("调度日志返回", "返回信息：" + resultJso);
            Response.ContentType = "application/json";
            Response.Write(resultJso); //响应信息
            Response.End();
        }

        ReturnData Main()
        {
            var response = new ReturnData { Status = { State = ReturnState.M00 } };
            ICaiBan.Framework.Core.IO.LogStep.Add("调度日志", "请求记录：" + HttpUtility.UrlDecode(Request.Form.ToString())); //记录请求日志

            try
            {
                //Post请求，消息内容：key=xxxxxx&method=Get&p=
                string key = Request.Form["key"]; //请求凭证
                string method = Request.Form["method"]; //请求的方法
                string p = Request.Form["p"]; //方法参数


                //验证非空及请求凭证
                if (!(string.IsNullOrWhiteSpace(key) || string.IsNullOrWhiteSpace(method) || !Regex.IsMatch(method, @"^([a-z_A-Z])+$") || key != Config.GetConfig().GetConnString("JOBKEY")))
                {
                    Type type = _ibll.GetType();
                    MethodInfo mi = type.GetMethod(method);
                    if (mi != null)
                    {
                        var paramObj = ParamBase.ParseFormJsonCheck(Type.GetType(string.Format("ICaiBan.ModelAPI.Job.{0}Param,ICaiBan.ModelAPI", method), true, true), p);
                        var contextType = typeof(ParamContext<>).MakeGenericType(new[] { paramObj.GetType() });
                        var pContext = Activator.CreateInstance(contextType, paramObj);
                        mi.Invoke(_ibll, new object[] { pContext });
                    }
                    else
                    {
                        ICaiBan.Framework.Core.IO.LogStep.Add("调度日志", "方法不存在或无效");
                        response.Status.State = ReturnState.M106;
                        response.Status.StateDesc = "方法不存在或无效";
                    }
                }
                else
                {
                    ICaiBan.Framework.Core.IO.LogStep.Add("调度日志", "验证失败");
                    response.Status.State = ReturnState.M106;
                    response.Status.StateDesc = "验证失败";
                }
            }
            catch (JsonException ex)
            {
                response.Status.State = ReturnState.M1000;
                response.Status.StateDesc = ex.Message;
                ICaiBan.Framework.IO.Log.WriteError("调度错误日志", ex);
                return response;
            }
            catch (SerializationException ex)
            {
                response.Status.State = ReturnState.M1000;
                response.Status.StateDesc = ex.Message;
                ICaiBan.Framework.IO.Log.WriteError("调度错误日志", ex);
                return response;
            }
            catch (Exception ex)
            {
                response.Status.State = ReturnState.M1000;
                ICaiBan.Framework.IO.Log.WriteError("调度错误日志", ex);
                if (ex is MessageException)
                {
                    MessageException tpex = (MessageException)ex;
                    response.Status.StateDesc = tpex.Message;
                    return response;
                }
                else if (ex.InnerException is MessageException)
                {
                    MessageException tpex = (MessageException)ex.InnerException;
                    response.Status.StateDesc = tpex.Message;
                    return response;
                }
                else
                {
                    response.Status.State = ReturnState.M1000;
                    return response;
                }
            }
            return response;
        }
    }
}