using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Transactions;
using System.Data;
using System.Data.Common;
using IL.Common;
using MediII.Adapter.ReceiveToScanModel;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;

namespace MediII.Adapter.BizComponent.ADT
{
    /// <summary>
    /// 病案首页信息
    /// </summary>
    public class ADT_A90_Handler : ADTHandler
    {
        public override void Handler(TaskMessage m)
        {
            //初始化
            var rtnMsg = string.Empty;
            var msgHead = string.Empty;
            var msgBody = string.Empty;
            var resultCode = string.Empty;
            var result = string.Empty;
            string guid = MediII.Common.GUIDHelper.NewGUID();
            Restful server = new Restful();
            string jbody = "{\"Request\":{\"Head\":{\"LicId\":\"6F9619FF-8B86-D011-B66D-00C04FC966FF\",\"RecAppId\":\"HIS\",\"ContentType\":\"text/json\",\"TranCode\":\"{0}\",\"Timestamp\":\"{5}\",\"OrgId\":\"991797\",\"AppId\":\"WiNEX\",\"Version\":\"1.1\",\"ServiceVersion\":\"1.0\",\"RecOrgId\":\"991797\",\"IPAddress\":\"100.100.100.100\",\"AppType\":\"PC\",\"MessageId\":\"{4}\"},\"Body\":{\"end_date\":\"{3}\",\"size\":1,\"begin_date\":\"{2}\",\"page\":\"{6}\",\"patient_no\":\"\",\"patient_name\":\"\",}}}";

            var token = JToken.Parse(jbody);
            var jtimestamp = token.SelectToken("Request.Head.Timestamp");
            jtimestamp.Replace(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
            var jTranCode = token.SelectToken("Request.Head.TranCode");
            jTranCode.Replace("v_medrecord_firstpage");
            var jMessageId = token.SelectToken("Request.Head.MessageId");
            jMessageId.Replace(guid);
            var jend_date = token.SelectToken("Request.Body.end_date");
            jend_date.Replace(m.Parameter2);
            var jbegin_date = token.SelectToken("Request.Body.begin_date");
            jbegin_date.Replace(m.Parameter1);
            var jpage = token.SelectToken("Request.Body.page");
            jpage.Replace(m.Parameter3);
            var jsize = token.SelectToken("Request.Body.size");
            jsize.Replace(m.Reserve3);
            //读取配置的url
            var url = System.Configuration.ConfigurationManager.AppSettings["Post_url"];
            string responseMsg = string.Empty;

            responseMsg = server.Post(url, JsonConvert.SerializeObject(token));
            if (string.IsNullOrWhiteSpace(responseMsg))
                throw new Exception("无返回数据," + responseMsg);

            //解析body，
            var jRequestBody = JObject.Parse(responseMsg);
            var jRequest = jRequestBody["Response"];
            var jBody = jRequest["Body"];
            var jHead = jRequest["Head"];
            var head = JsonConvert.DeserializeObject<ResponseHead>(jHead.ToString());
            var jdata = jBody["data"];

            if (head.AckCode != "100")
                throw new Exception("返回错误：" + head.AckMessage);
            if ((string)jdata["total"] != "0")
            {
                using (TransactionScope scope = new TransactionScope(TransactionScopeOption.RequiresNew))
                {
                    var isql = @"INSERT INTO TaskResponse(TaskID, TaskType, `Status`, Content, ErrNm, ResolvingMsg, ResolvingTime, RemarkContent) 
VALUES(@TaskID,@TaskType,1,@Content,0,null,null,@RemarkContent)";
                    //住院就诊
                    var cmd = ctx.DBGetSqlStringCommand(isql);
                    MySqlDataAccess.AddInParameter(ctx, cmd, "TaskID", DbType.AnsiString, m.TaskID);
                    MySqlDataAccess.AddInParameter(ctx, cmd, "TaskType", DbType.AnsiString, m.TaskType);
                    MySqlDataAccess.AddInParameter(ctx, cmd, "Content", DbType.AnsiString, responseMsg);
                    MySqlDataAccess.AddInParameter(ctx, cmd, "RemarkContent", DbType.AnsiString, JsonConvert.SerializeObject(token));
                    MySqlDataAccess.ExecuteNonQuery(ctx, cmd);

                    scope.Complete();
                }
                SetNextTask(m);
            }
        }
    }
}
