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

namespace Cmdjy.Bll.DataQuery
{
    /// <summary>
    /// 医疗机构信息数据查询
    /// </summary>
    public interface IHospitalInfoDataQuery:IDataQuery<HospitalInfo> { }

    public class HospitalInfoDataQuery:IHospitalInfoDataQuery, IRegisterBaseInterface
    {
        public DataQueryConfig Config { get; set; }
        public ICache Cache { get; set; }
        public DjyDbContext Db { get; set; }

        public HospitalInfoDataQuery(DataQueryConfig con,ICache ca,DjyDbContext db) {
            this.Config = con; this.Cache = ca; this.Db = db;
        }

        public HospitalInfo AddNew(HospitalInfo one) {
            this.Db.Entry(one).State = EntityState.Added;
            this.Db.SaveChanges();
            this.Cache.SetData(_getKey(one.Id.ToString()),one,Config.CacheTimeSpan);
            return one;
        }

        public IEnumerable<HospitalInfo> GetAll() {
            IEnumerable<HospitalInfo> result = null;
            if(this.Config.EnableCache) {
                result = this.Cache.GetData<IEnumerable<HospitalInfo>>(_getKey());
            }
            if(result == null) {
                result = GetQuery(this.Db,null).ToList();
                this.Cache.SetData(_getKey(),result);
            }
            return result;
        }

        public HospitalInfo GetOneById(params object[] id) {
            HospitalInfo result = null;
            if(this.Config.EnableCache) {
                result = this.Cache.GetData<HospitalInfo>(_getKey(id[0].ToString()));
            }
            if(result == null) {
                result = this.Db.HospitalInfos.Find(id);
                this.Cache.SetData(_getKey(id[0].ToString()),result);
            }
            return result;
        }

        public IQueryable<HospitalInfo> GetQuery(DjyDbContext db,DataFilterBase filter) {
            return db.HospitalInfos.AsQueryable();
        }

        public HospitalInfo Remove(HospitalInfo one) {
            this.Db.Entry(one).State = EntityState.Deleted;
            this.Db.SaveChanges();
            this.Cache.RemoveData(_getKey(one.Id.ToString()));
            return one;
        }

        public HospitalInfo Updata(HospitalInfo one) {
            this.Db.Entry(one).State = EntityState.Modified;
            this.Db.SaveChanges();
            this.Cache.RemoveData(_getKey(one.Id.ToString()));
            this.Cache.SetData(_getKey(one.Id.ToString()),one);
            return one;
        }

        private string _getKey(string id) => $"HospitalInfo:Id:{id}";
        private string _getKey() => "HospitalInfo:All";
    }
}