using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using Cmdjy.Bll;
using Cmdjy.Dal.Tables;

namespace Cmdjy.Dal.Queryes
{
    /// <summary>
    /// 对药品的数据查询接口
    /// </summary>
    public interface IHisDrugQuery:IDbQuery<HisDrugInfo>
    {
        IEnumerable<HisDrugInfo> GetDataByPrescriptionId(int pId);
    }

    public class HisDrugQuery:IHisDrugQuery
    {

        public Lazy<ICache> Cache { get; set; }

        public HisDrugQuery() {
            this.Cache = new Lazy<ICache>(() => CacheFactory.Cache);
        }


        public IEnumerable<HisDrugInfo> GetAll() {
            using(var db = DbContextFactory.CreateDbContext()) {
                return GetQuery(db).ToList();
            }
        }

        public IEnumerable<HisDrugInfo> GetDataByPrescriptionId(int pId) {
            var key = getPKey(pId.ToString());
            var val = this.Cache.Value.GetData<IEnumerable<HisDrugInfo>>(key);
            if(val == null) {
                using(var db = DbContextFactory.CreateDbContext()) {
                    val = GetQuery(db).Where(m => m.PrescriptionId == pId).ToList();
                    if(val != null) this.Cache.Value.SetData(key,val);
                }
            }
            return val;
        }

        public HisDrugInfo GetOne<TKey>(TKey id) {
            var key = getKey(id.ToString());
            var val = this.Cache.Value.GetData<HisDrugInfo>(key);
            if(val == null) {
                using(var db = DbContextFactory.CreateDbContext()) {
                    val = db.DrugInfos.Find(id);
                    if(val != null) this.Cache.Value.SetData(key,val);
                }
            }
            return val;
        }

        public IQueryable<HisDrugInfo> GetQuery(DjyDbContext db) {
            return db.DrugInfos.AsQueryable();
        }

        public void Insert(HisDrugInfo obj) {
            using(var db = DbContextFactory.CreateDbContext()) {
                db.Entry(obj).State = EntityState.Added;
                db.SaveChanges();
            }
            var key = getKey(obj.Id.ToString());
            this.Cache.Value.SetData(key,obj);
            var pkey = getPKey(obj.PrescriptionId.ToString());
            var val = this.Cache.Value.GetData<IEnumerable<HisDrugInfo>>(key);
            if(val == null) val = new List<HisDrugInfo>();
            val.ToList().Add(obj);
            this.Cache.Value.SetData(pkey,val);
        }

        private string getKey(string id) {
            return $"Db:HisDrugInfo:Id:{id}";
        }

        private string getPKey(string pId) {
            return $"Db:HisDrugInfo:PrescriptionId:{pId}";
        }

    }
}