using System.Collections.Generic;
using System.Linq;
using Siger.Middlelayer.Common;
using Siger.Middlelayer.Common.Helpers;
using Siger.Middlelayer.Common.ModuleEnum;
using Siger.Middlelayer.Repository.Entities;
using Siger.Middlelayer.Repository.Repositories.Interface;
using Siger.Middlelayer.Repository.Response;
using Siger.Middlelayer.Utility.ImportEntities;

namespace Siger.Middlelayer.Repository.Repositories
{
    internal class SigerDictRepository : ApiConfigRepositoryBase<SigerTrDict>, ISigerDict
    {
        private readonly ApiConfigDbContext _context;
        public SigerDictRepository(ApiConfigDbContext context) : base(context)
        {
            _context = context;
        }

        public string GetDictValue(int projectId, string cat, string dkey)
        {
            var accdict = new AccDictCost();
            var propertyInfo = accdict.GetType().GetField(cat);
            var dict = propertyInfo == null ?
                _context.siger_tr_dict.FirstOrDefault(f => f.cat == cat && f.dkey == dkey && f.status == (int)RowState.Valid) :
                _context.siger_tr_dict.FirstOrDefault(f => f.projectId == projectId && f.cat == cat && f.dkey == dkey && f.status == (int)RowState.Valid);
            if (dict == null)
                return "";
            return dict.dval;
        }

        public bool CheckIsUserCanAlterDict(string cat, int projectid, int userid)
        {
            var accdict = new AccDictCostNoProjectId();
            var propertyInfo = accdict.GetType().GetField(cat);
            var user = _context.siger_user.FirstOrDefault(t => t.id == userid && t.status == (int)RowState.Valid);
            if (user == null)
            {
                return false;
            }
            if (user.type == (int)UserType.SuperAdmin)//如果是超级管理员，所有分类都可以维护
            {
                return true;
            }

            if (propertyInfo != null)
            {
                return false;//不能进行增删改查操作
            }

            return true;//可以维护的数据
        }

        public CommonImportResult ImportDict(IEnumerable<DictTemplate> dicts, int projectid, int userid)
        {
            var entities = new List<SigerTrDict>();
            var dictlist = dicts.ToList();

            var errors = new List<string>();
            var rowIndex = 1;
            foreach (var p in dictlist)
            {
                rowIndex++;
                if (!CheckIsUserCanAlterDict(p.cat, projectid, userid))
                {
                    errors.Add($"{rowIndex},{(int)RequestEnum.ManageCatOnlyBySuperAdministrator}");
                }
                var model = _context.siger_tr_dict.FirstOrDefault(t => (t.dval == p.dval && t.dkey == p.dkey || t.dkey == p.dkey) && t.projectId == projectid
                    && t.status == (int)RowState.Valid && t.cat == p.cat);
                if (model != null)
                {
                    errors.Add($"{rowIndex},{(int)RequestEnum.DataExist}");
                }

                var repeatmodel = dictlist.Where(t => (t.dval == p.dval && t.dkey == p.dkey || t.dkey == p.dkey) && t.cat == p.cat);
                if (repeatmodel.Any() && repeatmodel.Count() > 1)
                {
                    errors.Add($"{rowIndex},{(int)RequestEnum.DataExist}");
                }
            }

            if (errors.Any())
            {
                return new CommonImportResult(0, string.Join(";", errors));
            }

            foreach (var p in dictlist)
            {
                var psEntity = new SigerTrDict
                {
                    cat = p.cat ?? "",
                    dkey = p.dkey ?? "",
                    dval = p.dval ?? "",
                    createtime = UnixTimeHelper.GetNow(),
                    projectId = projectid
                };
                entities.Add(psEntity);
            }
            try
            {
                _context.siger_tr_dict.AddRange(entities);
                _context.SaveChanges();
                return new CommonImportResult(1, "1");
            }
            catch
            {
                throw;
            }
        }

        public ResponseBlock GetAllTypes(int projectId)
        {
            var funcName = _context.siger_tr_dict.Where(f => f.cat == Dict.FuncName.ToString()).OrderBy(f => f.dkey).ToList();
            var funcType = _context.siger_tr_dict.Where(f => f.cat == Dict.FuncType.ToString()).OrderBy(f => f.dkey).ToList();
            var combType = _context.siger_tr_dict.Where(f => f.cat == Dict.CombType.ToString()).OrderBy(f => f.dkey).ToList();
            var stationId = GetLevelSectionIds(0, projectId);
            var station = _context.siger_project_level_section.Where(f => stationId.Contains(f.id)).Distinct().ToList();
            var dic = new Dictionary<int, string>();
            foreach (var item in station)
            {
                dic.Add(item.id, item.title);
            }
            var response = new ResponseBlock
            {
                FuncName = funcName,
                FuncType = funcType,
                CombType = combType,
                Station = dic
            };
            return response;
        }

        public IEnumerable<SigerTrDict> GetDataByCat(string cat, int projectId)
        {
            var result = _context.siger_tr_dict.Where(f => f.cat == cat
                         && f.projectId == projectId && f.status != (int)RowState.Invalid).OrderByDescending(o => o.id);
            return result;
        }
    }
}
