using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Services;
using Cmdjy.Bll;
using Cmdjy.Dal;
using CommonHelper;
using Newtonsoft.Json;
using WsdInterfaceModels;

namespace Cmdjy.ws
{
    /// <summary>
    /// 万仕达，服务调用接口
    /// </summary>
    [WebService(Namespace = "http://Djy.wondersgroup.com/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务，请取消注释以下行。 
    // [System.Web.Script.Services.ScriptService]
    public class WsdInterface:WebService
    {

        [WebMethod(Description = "获取代煎药处方信息")]
        public string GetData(WsdRequest info) {
            var result = new WsdResult {
                Code = EnumCode.Success,
            };
            string cKey = null;
            using(var db = DbContextFactory.CreateDbContext()) {
                var companyInfo = db.CompanyInfos.Where(m => m.Id.ToString() == info.CompanyCode);
                if(companyInfo.Any()) {
                    cKey = companyInfo.First().SecurityKey;
                }
            }
            if(string.IsNullOrEmpty(cKey)) {
                result.Code = EnumCode.Exception;
                result.Msg = "CompanyCode值错误";
            }
            //获取数据
            int start = 0;
            if(!int.TryParse(info.StartNo,out start)) {
                result.Code = EnumCode.Exception;
                result.Msg = "Start值错误";
            }
            int count = 0;
            if(!int.TryParse(info.MaxCount,out count)) {
                result.Code = EnumCode.Exception;
                result.Msg = "MaxCount值错误";
            }
            if(count <= 0) {
                result.Code = EnumCode.Exception;
                result.Msg = "Count值错误。";
            }
            if(result.Code != EnumCode.Exception) {
                result.Prescriptions = new List<WsdPrescriptionInfo>();
                count = count > WebSettings.WsdMaxCount ? WebSettings.WsdMaxCount : count;
                var cache = CacheFactory.Cache;
                for(int i = start;i < start + count;i++) {
                    //从缓存获取
                    var pkey = $"Company:Id:{info.CompanyCode}:Pre:Id:{i}";
                    var one = cache.GetData<WsdPrescriptionInfo>(pkey);
                    if(one == null) {
                        //从数据库获取处方信息
                        one = getPrescriptionInfoFromDb(info.CompanyCode,i);
                        //判断是否为
                        //获取药品信息
                        if(one != null) one.Drugs = getDrugInfoFromDb(one.Id);
                        //存缓存
                        if(one != null) cache.SetData(pkey,one);
                    }
                    //对应代煎药厂商
                    if(one == null) {
                        one = new WsdPrescriptionInfo {
                            Type = WsdPrescriptionType.NullOrder,Id = i,
                        };
                    }
                    result.Prescriptions.Add(one);
                }
                result.Code = EnumCode.Success;
                result.Count = result.Prescriptions.Where(m => m.Type != WsdPrescriptionType.NullOrder).Count();
                result.Msg = "";
                using(var db = DbContextFactory.CreateDbContext()) {
                    result.More = db.PrescriptionInfos.Max(m => m.Id) > (start + count);
                }
            }
            //编码：json串 +  加密信息
            try {
                var resStr = JsonConvert.SerializeObject(result);
                var mw = DesHelper.GetHelper().Encrypty(cKey,resStr);
                logWsdRequest(info,result,resStr,mw);
                return mw;
            }
            catch(Exception ex) {
                return ex.ToString();
            }
        }
        /// <summary>
        /// 记录日志
        /// </summary>
        /// <param name="info">请求信息</param>
        /// <param name="result">响应对象</param>
        /// <param name="resStr">响应字符串</param>
        /// <param name="mw">响应密文</param>
        private void logWsdRequest(WsdRequest info,WsdResult result,string resStr,string mw) {
            using(var db = DbContextFactory.CreateDbContext()) {
                if(result != null && result.Prescriptions != null) {
                    foreach(var p in result.Prescriptions) {
                        if(p.Drugs != null) {
                            foreach(var d in p.Drugs) {
                                db.WsdRequestLogs.Add(new Dal.Tables.WsdRequestLog {
                                    StartNo = info.StartNo,MaxCount = info.MaxCount,
                                    ClientAddress = this.Context.Request.UserHostAddress,
                                    LogDatatime = DateTime.Now,DrugId = d.Id.ToString(),
                                    PrescriptionId = p.Id.ToString(),
                                    Code = result.Code.ToString(),Msg = result.Msg,
                                });
                            }
                        }
                    }
                }
                db.SaveChanges();
            }
        }

        /// <summary>
        /// 从数据库获取药品列表
        /// </summary>
        /// <param name="id">处方号</param>
        private static List<WsdDrugInfo> getDrugInfoFromDb(int id) {
            List<WsdDrugInfo> result = null;
            using(var db = DbContextFactory.CreateDbContext()) {
                var qu = db.DrugInfos.Where(m => m.PrescriptionId == id);
                if(qu.Any()) {
                    result = new List<WsdDrugInfo>();
                    foreach(var item in qu) {
                        var od = new WsdDrugInfo();
                        od.CopyFrom(item);
                        result.Add(od);
                    }
                }
            }
            return result;
        }
        /// <summary>
        /// 从数据库获取处方
        /// </summary>
        /// <param name="i">处方号</param>
        private static WsdPrescriptionInfo getPrescriptionInfoFromDb(string cId,int i) {
            WsdPrescriptionInfo result = null;
            using(var db = DbContextFactory.CreateDbContext()) {
                var qu = db.PrescriptionInfos
                    .Where(m => m.Id == i && m.CompanyCode == cId)
                    .Where(m => m.Type == Dal.Tables.PrescriptionType.Order || m.Type == Dal.Tables.PrescriptionType.CancelOrder);
                if(qu.Any()) {
                    var fir = qu.First();
                    result = new WsdPrescriptionInfo();
                    result.CopyFrom(fir);
                }
            }
            return result;
        }
    }
}
