using Siger.Middlelayer.KpiRespository.Repositories.Interface;
using Siger.Middlelayer.KpiRespository.Respose;
using Siger.Middlelayer.KpiRespository.Entities;
using Siger.Middlelayer.Repository.Paged;
using Siger.Middlelayer.Common;
using System;
using System.Linq;
using System.Linq.Expressions;
using Microsoft.EntityFrameworkCore;
using Siger.Middlelayer.Share.ModuleEnum;
using Siger.Middlelayer.Common.Helpers;
using Siger.Middlelayer.Repository.Extensions;
using Siger.Middlelayer.Utility.ImportEntities;
using System.Collections.Generic;
using Siger.Middlelayer.Utility.Helpers;

namespace Siger.Middlelayer.KpiRespository.Repositories
{
    internal class KpiTasklistRespository : KpiRepositoryBase<SigerProjectKpiTasklist>, ISigerKpiTasklist
    {
        private ApiKpiDbContext kpiDbContext;
        public KpiTasklistRespository(ApiKpiDbContext context) : base(context)
        {
            kpiDbContext = context;
        }

        public KpiTaskResult GetState(double ActVal, double TargetVal, siger_project_kpi_item itemObj)
        {
            var state = KpiTaskResult.NoConfg;

            switch (itemObj.Condition)
            {
                case (int)KpiCondition.Large:
                    {
                        if (ActVal > TargetVal)
                            state = KpiTaskResult.Normal;
                        else
                            state = KpiTaskResult.Exception;

                        break;
                    }
                case (int)KpiCondition.Less:
                    {
                        if (ActVal < TargetVal)
                            state = KpiTaskResult.Normal;
                        else
                            state = KpiTaskResult.Exception;

                        break;
                    }
                case (int)KpiCondition.LargeEq:
                    {
                        if (ActVal >= TargetVal)
                            state = KpiTaskResult.Normal;
                        else
                            state = KpiTaskResult.Exception;

                        break;
                    }
                case (int)KpiCondition.LessEq:
                    {
                        if (ActVal <= TargetVal)
                            state = KpiTaskResult.Normal;
                        else
                            state = KpiTaskResult.Exception;

                        break;
                    }

            }
            return state;
        }

        public IPagedCollectionResult<ResponseTasklist> GetTaskItemPagedList(int section, string item, DateTime begin, DateTime end, int status, int excption, int projectid, int page, int pagesize, int taskResult = 0)
        {
            Expression<Func<ResponseTasklist, bool>> Funsection = f => true;
            Expression<Func<ResponseTasklist, bool>> FunmItem = f => true;
            Expression<Func<ResponseTasklist, bool>> Funexcption = f => true;
            Expression<Func<ResponseTasklist, bool>> Funtask = f => true;
            Expression<Func<ResponseTasklist, bool>> Fundate = f => true;
            var query = from t in kpiDbContext.siger_project_kpi_tasklist
                        join i in kpiDbContext.siger_project_kpi_item on t.ItemId equals i.id
                        join s in kpiDbContext.siger_project_section on t.Section equals s.id
                        join a in kpiDbContext.siger_project_kpi_action on t.id equals a.TaskId into atemp
                        from act in atemp.DefaultIfEmpty()
                        join u in kpiDbContext.siger_project_user on act.Reposible equals u.mid into utemp
                        from usr in utemp.DefaultIfEmpty()
                        join r in kpiDbContext.siger_project_kpi_action_result on act.id equals r.actionid into rtemp
                        from actrst in rtemp.DefaultIfEmpty()
                        where t.projectId == projectid 
                        && t.status == (int)RowState.Valid && i.status == (int)RowState.Valid && t.Type == (int)KpiTaskType.Exception
                        select new ResponseTasklist
                        {
                            Id = t.id,
                            Section = t.Section,
                            SectionDesc = s.title,
                            ConditionDate=t.Busidate,
                            Busidate = t.Busidate.ToString("yyyy-MM-dd"),
                            ItemId = t.ItemId,
                            Item = i.Item,
                            ConditionId = i.Condition,
                            Condition=i.Condition == 0?"大于":"小于",
                            Unit = i.Unit,
                            Val = t.Result == KpiTaskResult.NoConfg ? "" : Math.Round(t.ActVal, 2).ToString(),
                            Target = t.TargetVal,
                            TaskResult = (int)t.Result,
                            TaskResultDesc = "",
                            Exception = actrst!=null?(int)KpiExecption.Complated :(int)t.Excption,

                            ExceptionStatus =t.Excption!=0? EnumHelper.GetEnumDesc(t.Excption):"",
                            Remark = t.Remark,
                            Cycle = EnumHelper.GetEnumDesc(i.KpiCycle),
                            Cause = act != null ? act.Cause : "",
                            Solution =act!=null?act.Solution: "",
                            ResponsibleID = act != null ? act.Reposible : 0,
                            ResponsiblePersion = usr.name ??"",
                            Plantime = act != null ? act.Plantime.ToString("yyyy-MM-dd HH:mm:ss") : "",
                            OperaterDesc = "",
                            ResultDesc = "",
                            Operatetime = "",
                            desc1 = act != null ? act.Desc1 : "",
                            checktime= act != null ? UnixTimeHelper.ConvertIntDateTime(act.Checktime) : "",
                            excutetime = act != null ? UnixTimeHelper.ConvertIntDateTime(act.Excutetime) : "",
                            ActionId=act!=null?act.id:0,
                            reposible_sectionId = usr!= null ? usr.sectionid : 0
                        };
            if (begin!=DateTime.MinValue)
            {
                Fundate = f => f.ConditionDate >= begin && f.ConditionDate <= end;
            }
            if (section != 0)
                Funsection = f => f.Section == section;
            if (excption != 0)
                Funexcption = f => f.Exception == excption;
            if (taskResult != 0)
                Funtask = f => f.TaskResult == taskResult;

            if (!string.IsNullOrEmpty(item))
                FunmItem = f => f.Item.Contains(item);
            var predicate = Funsection.And(FunmItem).And(Funexcption).And(Funtask).And(Fundate);
            var totalCount = query.Count(predicate);
            var entities = query.Where(predicate).OrderByDescending(q => q.Id).Skip((page - 1) * pagesize).Take(pagesize).AsNoTracking().ToList();
            foreach (var obj in entities)
            {
                //    obj.Condition = EnumHelper.GetEnumDesc((KpiCondition)obj.ConditionId);
                //    obj.TaskResultDesc = EnumHelper.GetEnumDesc((KpiTaskResult)obj.TaskResult);
                //    if (obj.TaskResult == (int)KpiTaskResult.Exception)
                //    {
                //        obj.Exception = (int)KpiExecption.Default;
                //        obj.ExceptionStatus = EnumHelper.GetEnumDesc(KpiExecption.Default);
                //    }
                //    //var action = kpiDbContext.siger_project_kpi_action.OrderByDescending(d => d.id).FirstOrDefault(f => f.TaskId == obj.Id);
                //    //if (action == null)
                //    //    continue;
                //    obj.Exception = (int)KpiExecption.Processing;
                //    obj.ExceptionStatus = EnumHelper.GetEnumDesc(KpiExecption.Processing);
                //  //  var usr = kpiDbContext.siger_project_user.FirstOrDefault(f => f.mid == action.Reposible);
                //    //obj.ResponsibleDepart = usr != null ? usr.sectionid : 0;
                //    //obj.ResponsibleID = usr != null ? usr.mid : 0;
                //    //obj.ResponsiblePersion = usr != null ? usr.name : "";
                //    //obj.Plantime = action.Plantime.ToString("yyyy-MM-dd HH:mm:ss");
                //    //obj.Cause = action.Cause == null ? "" : action.Cause;
                //    //obj.Solution = action.Solution == null ? "" : action.Solution;
                //    //obj.desc1 = action.Desc1;
                //    //obj.checktime = action.Checktime == 0 ? "" : UnixTimeHelper.ConvertIntDateTime(action.Checktime);
                //    //obj.excutetime = action.Excutetime == 0 ? "" : UnixTimeHelper.ConvertIntDateTime(action.Excutetime);

                var acrionResult = kpiDbContext.siger_project_kpi_action_result.OrderByDescending(d => d.id).FirstOrDefault(f => f.TaskId == obj.Id && f.actionid==obj.ActionId);
                if (acrionResult == null)
                    continue;
                if (acrionResult.Result == 1)
                {
                    obj.Exception = (int)KpiExecption.Complated;
                    obj.ExceptionStatus = EnumHelper.GetEnumDesc(KpiExecption.Complated);
                    obj.Operatetime = acrionResult.Time.ToString("yyyy-MM-dd HH:mm:ss");
                }
                var usr2 = kpiDbContext.siger_project_user.FirstOrDefault(f => f.mid == acrionResult.Operater);
                obj.Operater = usr2 != null ? usr2.mid : 0;
                obj.OperaterDesc = usr2 != null ? usr2.name : "";

                obj.ResultDesc = acrionResult.Result == 0 ? "未解决" : "已解决";

            }
            return new PagedCollectionResult<ResponseTasklist>(entities, totalCount);
        }

        /// <summary>
        /// 月度数据
        /// </summary>
        /// <param name="section"></param>
        /// <param name="item"></param>
        /// <param name="begin"></param>
        /// <param name="end"></param>
        /// <param name="projectid"></param>
        /// <returns></returns>
        public IEnumerable<ResponseTasklist> GetTaskItem(int section, int item, DateTime begin, DateTime end, int projectid)
        {
            Expression<Func<ResponseTasklist, bool>> FunmItem = f => true;
            var query = from t in kpiDbContext.siger_project_kpi_tasklist
                        join i in kpiDbContext.siger_project_kpi_item on t.ItemId equals i.id
                        join s in kpiDbContext.siger_project_section on t.Section equals s.id
                        where t.projectId==projectid && t.Busidate >= begin && t.Busidate <= end && t.Section == section
                        && t.status == (int)RowState.Valid && i.status == (int)RowState.Valid
                        select new ResponseTasklist
                        {
                            Id = t.id,
                            Section = t.Section,
                            SectionDesc = s.title,
                            Busidate = t.Busidate.ToString("yyyy-MM-dd"),
                            Position = i.Position,
                            Color = i.Color,
                            ItemId = i.id,
                            Item = i.Item,
                            ConditionId=i.Condition,
                            Condition= i.Condition==0?"大于":"小于",
                            Unit = i.Unit,
                            Val = Math.Round(t.ActVal,2).ToString(),
                            Target=t.TargetVal,
                            AddVal=t.AddVal,
                            TaskResult = (int)t.Result,
                            TaskResultDesc = EnumHelper.GetEnumDesc(t.Result),
                            Exception = (int)t.Excption,
                            ExceptionStatus = EnumHelper.GetEnumDesc(t.Excption),
                            Cycle =EnumHelper.GetEnumDesc(i.KpiCycle),
                            Remark=t.Remark,
                            CycleText=t.cycle,
                            
                            ResponsiblePersion = "",
                            Plantime = "",
                            OperaterDesc = "",
                            ResultDesc = "",
                            Operatetime = "",
                            desc1 = "",
                           
                            
                        };
            if (item != 0)
                FunmItem = f => f.ItemId == item;
            var entities = query.Where(FunmItem).OrderBy(q => q.Busidate).AsNoTracking().ToList();
            foreach (var obj in entities)
            {
                obj.Condition = EnumHelper.GetEnumDesc((KpiCondition)obj.ConditionId);
                obj.TaskResultDesc = EnumHelper.GetEnumDesc((KpiTaskResult)obj.TaskResult);

                var action = kpiDbContext.siger_project_kpi_action.OrderBy(d => d.id).FirstOrDefault(f => f.TaskId == obj.Id);
                if (action != null)
                {
                    obj.ActionId = action.id;
                    var usr = kpiDbContext.siger_project_user.FirstOrDefault(f => f.mid == action.Reposible);
                    obj.ResponsibleID = usr != null ? usr.mid : 0;
                    obj.ResponsiblePersion = usr != null ? usr.name : "";
                    obj.Plantime = action.Plantime.ToString();
                    obj.Solution = action.Solution;
                    obj.Cause = action.Cause;
                    obj.desc1 = action.Desc1;
                    obj.checktime = action.Checktime == 0 ? "" : UnixTimeHelper.ConvertIntDateTime(action.Checktime);
                    obj.excutetime = action.Excutetime == 0 ? "" : UnixTimeHelper.ConvertIntDateTime(action.Excutetime);
                }
                var acrionResult = kpiDbContext.siger_project_kpi_action_result.OrderByDescending(d => d.id).FirstOrDefault(f => f.TaskId == obj.Id);
                if (acrionResult != null)
                {
                    var usr2 = kpiDbContext.siger_project_user.FirstOrDefault(f => f.mid == acrionResult.Operater);
                    obj.Operater = usr2 != null ? usr2.mid : 0;
                    obj.OperaterDesc = usr2 != null ? usr2.name : "";
                    obj.Operatetime = acrionResult.Time.ToString();
                    obj.ResultDesc = acrionResult.Result == 0 ? "未解决" : "已解决";
                    obj.Exception = (int)KpiExecption.Complated;
                }
                var Exception = (KpiExecption)obj.Exception;
                obj.ExceptionStatus = EnumHelper.GetEnumDesc(Exception);
            }
            return entities;
        }

        /// <summary>
        /// 导入实际值
        /// </summary>
        /// <param name="items"></param>
        /// <param name="projectId"></param>
        /// <returns></returns>
        public CommonImportResult ImportKpiTaskAct(IEnumerable<ImportKpiTaskAct> items, int projectId)
        {
            var busidateStr = DateTime.Now.ToString("yyyy-MM-dd");
            DateTime.TryParse(busidateStr, out DateTime busidate);
            var entities = new List<SigerProjectKpiTasklist>();
            foreach (var it in items)
            {
                var depart = kpiDbContext.siger_project_section.FirstOrDefault(f => f.title == it.Department);
                if (depart == null)
                    continue;
                var item = kpiDbContext.siger_project_kpi_item.FirstOrDefault(f => f.projectId == projectId && f.Section == depart.id);
                if (item == null)
                    continue;
                var taskObj = kpiDbContext.siger_project_kpi_tasklist.FirstOrDefault(f => f.projectId == projectId && f.Busidate == busidate && f.Section == depart.id && f.ItemId == item.id);
                if (taskObj == null)
                    continue;

                taskObj.ActVal = it.ActVal;
                taskObj.Result = GetState(it.ActVal,taskObj.TargetVal,item);
                if (taskObj.Result == KpiTaskResult.Exception)
                    taskObj.Type = (int)KpiTaskType.Exception;
                entities.Add(taskObj);
            }

            try
            {
                kpiDbContext.siger_project_kpi_tasklist.UpdateRange(entities);
                kpiDbContext.SaveChanges();
                return new CommonImportResult(1, "1");
            }
            catch
            {
                throw;
            }

        }

        /// <summary>
        /// 获取有异常的数据
        /// </summary>
        /// <param name="section"></param>
        /// <param name="item"></param>
        /// <param name="begin"></param>
        /// <param name="end"></param>
        /// <param name="projectid"></param>
        /// <returns></returns>
        public IEnumerable<ResponseTasklist> GetTaskItemRepeat(int section, int item, DateTime begin, DateTime end, int projectid)
        {
            var query = from t in kpiDbContext.siger_project_kpi_tasklist
                        join s in kpiDbContext.siger_project_section on t.Section equals s.id
                        join i in kpiDbContext.siger_project_kpi_item on t.ItemId equals i.id
                        join a in kpiDbContext.siger_project_kpi_action on t.id equals a.TaskId into atemp
                        from ac in atemp.DefaultIfEmpty()
                        join u in kpiDbContext.siger_project_user on ac.Reposible equals u.mid into ustemp
                        from usr1 in ustemp.DefaultIfEmpty()
                        join r in kpiDbContext.siger_project_kpi_action_result on t.id equals r.TaskId into temp
                        from rs in temp.DefaultIfEmpty()
                        join u2 in kpiDbContext.siger_project_user on rs.Operater equals u2.mid into utemp
                        from usr2 in utemp.DefaultIfEmpty()
                        where t.projectId==projectid && t.Section == section && t.ItemId == item && t.projectId == projectid &&
                        t.Busidate >= begin && t.Busidate <= end &&
                        t.Result == KpiTaskResult.Exception
                        select new ResponseTasklist
                        {
                            Id = t.id,
                            Busidate = t.Busidate.ToString("yyyy-MM-dd"),
                            Section = t.Section,
                            SectionDesc = s.title,
                            ItemId = i.id,
                            Item = i.Item,
                            //Target = i.TargetVal,
                            Target = t.TargetVal,
                            Unit = i.Unit,
                            Val = Math.Round(t.ActVal, 2).ToString(),
                            Color = i.Color,
                            Position = i.Position,
                            Condition = i.Condition == (int)KpiCondition.Large ? EnumHelper.GetEnumDesc(KpiCondition.Large) : EnumHelper.GetEnumDesc(KpiCondition.Less),
                            TaskResult = (int)t.Result,
                            ActionId=ac!=null?ac.id:0,
                            ResponsibleID = ac != null ? ac.Reposible : 0,
                            ResponsiblePersion = usr1 != null ? usr1.name : "",
                            Plantime = ac != null ? ac.Plantime.ToString() : "",
                            Operater = rs != null ? rs.Operater : 0,
                            OperaterDesc = usr2.name,
                            //Exception = (int)t.Excption,
                            Exception = rs != null ? (int)KpiExecption.Complated : (int)t.Excption,
                            Result = rs != null ? rs.Result : 0,
                            Operatetime = rs != null ? rs.Time.ToString() : "",
                            Solution = ac != null ? ac.Solution : "",
                            Cause =ac!=null?ac.Cause:"",
                            TaskType=t.Type,
                            Remark=t.Remark,
                            CycleText=t.cycle

                        };
            var entitys = query.OrderBy(o => o.Id).ToList();
            foreach (var obj in entitys)
            {
                obj.ResultDesc = obj.Result == 0 ? "未解决" : "已解决";
                obj.TaskResultDesc = EnumHelper.GetEnumDesc((KpiTaskResult)obj.TaskResult);
                obj.ExceptionStatus = EnumHelper.GetEnumDesc((KpiExecption)obj.Exception);
                if (obj.Exception != (int)KpiExecption.Complated)
                   obj.Operatetime = "";
            }
            return entitys;
        }

        public double GetKpiValue(int itemid, int projectId, DateTime sdate, DateTime edate)
        {
            var item = from q in kpiDbContext.siger_project_kpi_tasklist
                where q.ItemId == itemid && q.projectId == projectId && q.status == (int) RowState.Valid
                && q.Busidate >= sdate && q.Busidate < edate && q.Result > KpiTaskResult.NoConfg 
                       select q;
            var items = item.AsEnumerable();
            if (items.Any())
            {
                var value = Math.Round(items.Sum(m => m.ActVal) / items.Count(), 0);
                return (100 - value) < 0 ? 100 : (100 - value);
            }

            return 100;
        }

        /// <summary>
        /// 客户投诉次数，嘉定工厂本月累计
        /// </summary>
        /// <param name="itemid"></param>
        /// <param name="projectId"></param>
        /// <param name="sdate"></param>
        /// <param name="edate"></param>
        /// <returns></returns>
        public double GetKpiComplaint(int itemid, int projectId, DateTime sdate, DateTime edate)
        {
            var item = from q in kpiDbContext.siger_project_kpi_tasklist
                where q.ItemId == itemid && q.projectId == projectId && q.status == (int)RowState.Valid
                      && q.Busidate >= sdate && q.Busidate < edate && q.Result > KpiTaskResult.NoConfg && q.ActVal > 0
                       select q;  
            var items = item.AsEnumerable();
            if (items.Any())
            {
                return Math.Round(items.Sum(m => m.ActVal), 0);
            }

            return 0;
        }

        /// <summary>
        /// 安全天数，取最近一次可记录事故数有值的那一天到当前的间隔天数，如果之前任意一天都没有值，则从年初算到现在
        /// </summary>
        /// <param name="itemid"></param>
        /// <param name="projectId"></param>
        /// <returns></returns>
        public double GetKpiSafeDay(int itemid, int projectId)
        {
            var item = from q in kpiDbContext.siger_project_kpi_tasklist
                where q.ItemId == itemid && q.projectId == projectId && q.status == (int)RowState.Valid
                       && q.Result > KpiTaskResult.NoConfg && q.ActVal > 0
                       select q;
            var task = item.OrderByDescending(q => q.Busidate).FirstOrDefault();
            if (task != null)
            {
                return DateTime.Now.Date.Subtract(task.Busidate.Date).Days;
            }

            return DateTime.Now.DayOfYear;
        }

        public double GetKpiTarget(int itemid, int projectId)
        {
            var item = from q in kpiDbContext.siger_project_kpi_item
                where q.id == itemid && q.projectId == projectId && q.status == (int)RowState.Valid
                select q;
            var value = item.FirstOrDefault();
            return value == null ? 100 : 100 - value.TargetVal;
        }

        /// <summary>
        /// 获取KPI item 编辑行
        /// </summary>
        /// <param name="section"></param>
        /// <param name="itemId"></param>
        /// <param name="kpiCycle"></param>
        /// <param name="projectId"></param>
        /// <param name="begin"></param>
        /// <param name="end"></param>
        /// <param name="page"></param>
        /// <param name="pagesize"></param>
        /// <returns></returns>
        public IPagedCollectionResult<ResponseInputTasklist> GetInputTasklists(int section, int itemId, KpiCycleEnum kpiCycle, int projectId, DateTime begin, DateTime end,int page, int pagesize)
        {
            var query = from t in kpiDbContext.siger_project_kpi_tasklist
                        join i in kpiDbContext.siger_project_kpi_item on t.ItemId equals i.id
                        where t.projectId == projectId && i.KpiCycle == kpiCycle && t.Busidate >= begin && t.Busidate <= end &&
                        t.Section == section && t.ItemId == itemId && i.KpiCycle == kpiCycle
                        select new ResponseInputTasklist
                        {
                            Busidate = t.Busidate,
                            TaskId = t.id,
                            ItemId = t.ItemId,
                            Title = t.cycle,
                            //TargetVal = i.TargetVal,
                            TargetVal= t.Result == KpiTaskResult.NoConfg ? Math.Round(i.TargetVal,2).ToString() : Math.Round(t.TargetVal,2).ToString(),
                            ActVal =t.Result==KpiTaskResult.NoConfg?"": Math.Round(t.ActVal,2).ToString(),
                            Remark = t.Remark,
                            Condition = i.Condition,
                            KpiCycle = i.KpiCycle,
                            AddVal= t.Result == KpiTaskResult.NoConfg ? "" :Math.Round( t.AddVal,2).ToString()
                        };

            var totalCount = query.Count();
            var data = query.OrderByDescending(d=>d.Busidate).ToList();
           

            foreach(var d in data)
            {
                if (string.IsNullOrEmpty(d.Title))
                    d.Title = GetTitle(d.Busidate, d.KpiCycle);
                var cnd = (KpiCondition)d.Condition;
                //removed
                //var action = kpiDbContext.siger_project_kpi_action.FirstOrDefault(f => f.TaskId == d.TaskId);
                //if (action!=null)
                //    d.Enable = 0;
                d.ConditionDesc = EnumHelper.GetEnumDesc(cnd);
            }
            return new PagedCollectionResult<ResponseInputTasklist>(data, totalCount);
        }
        string GetTitle(DateTime cDate, KpiCycleEnum kpiCycle)
        {
            var title = string.Empty;
            switch (kpiCycle)
            {
                case KpiCycleEnum.Year:
                    {
                        title = cDate.Year.ToString();
                        break;
                    }
                case KpiCycleEnum.Quarter:
                    {
                        var querter = DateTimeHelper.GetQuarterByMonth(cDate.Month);
                        title = $"{cDate.Year.ToString()}Q{querter}";
                        break;
                    }
                case KpiCycleEnum.Month:
                    {
                        title = $"{cDate.Year}-{cDate.Month}";
                        break;
                    }
                case KpiCycleEnum.Week:
                    {
                        var weekofYear = DateTimeHelper.GetWeekOfYear(cDate);
                        title = $"{cDate.Year.ToString()}W{weekofYear}";
                        break;
                    }
                case KpiCycleEnum.Day:
                    {
                        title = title = $"{cDate.Year}-{cDate.Month}-{cDate.Day}";
                        break;
                    }
            }

            return title;
        }
        /// <summary>
        /// 客户投诉TOP5
        /// </summary>
        /// <param name="itemid"></param>
        /// <param name="projectId"></param>
        /// <returns></returns>
        public List<SigerProjectKpiTasklist> GetKpiComplaints(int itemid, int projectId)
        {
            var item = from q in kpiDbContext.siger_project_kpi_tasklist
                where q.ItemId == itemid && q.projectId == projectId && q.status == (int)RowState.Valid 
                      && q.Remark != "" && q.ActVal > 0
                select q;
            return item.AsEnumerable().OrderByDescending(q => q.Busidate).Take(5).ToList();
        }

        public IPagedCollectionResult<ResponseTasklist> GetTaskItemMoblie(int section, string item, DateTime begin, DateTime end, int status, int excption, int projectid, int page, int pagesize)
        {
            Expression<Func<ResponseTasklist, bool>> Funsection = f => true;
            Expression<Func<ResponseTasklist, bool>> FunmItem = f => true;
            Expression<Func<ResponseTasklist, bool>> Funexcption = f => true;
            Expression<Func<ResponseTasklist, bool>> Funtask = f => true;
            var query = from t in kpiDbContext.siger_project_kpi_tasklist
                        join i in kpiDbContext.siger_project_kpi_item on t.ItemId equals i.id
                        join s in kpiDbContext.siger_project_section on t.Section equals s.id
                        where t.projectId == projectid && t.Busidate >= begin && t.Busidate <= end
                        && t.status == (int)RowState.Valid && i.status == (int)RowState.Valid
                        select new ResponseTasklist
                        {
                            Id = t.id,
                            Section = t.Section,
                            SectionDesc = s.title,
                            Busidate = t.Busidate.ToString("yyyy-MM-dd"),
                            ItemId = t.ItemId,
                            Item = i.Item,
                            ConditionId = i.Condition,
                            Unit = i.Unit,
                            Val = t.Result == KpiTaskResult.NoConfg ? "" : Math.Round(t.ActVal, 2).ToString(),
                            Target = t.TargetVal,
                            TaskResult = (int)t.Result,
                            Exception = (int)t.Excption,
                            Cycle = EnumHelper.GetEnumDesc(i.KpiCycle),
                            Remark = t.Remark
                        };
            if (section != 0)
                Funsection = f => f.Section == section;
            if (excption != 0)
                Funexcption = f => f.Exception == excption;


            if (!string.IsNullOrEmpty(item))
                FunmItem = f => f.Item.Contains(item);
            var predicate = Funsection.And(FunmItem).And(Funexcption).And(Funtask);
            var totalCount = query.Count(predicate);
            var entities = query.Where(predicate).OrderByDescending(q => q.Id).Skip((page - 1) * pagesize).Take(pagesize).AsNoTracking().ToList();
            foreach (var obj in entities)
            {
                obj.Condition = EnumHelper.GetEnumDesc((KpiCondition)obj.ConditionId);
                obj.TaskResultDesc = EnumHelper.GetEnumDesc((KpiTaskResult)obj.TaskResult);
                if (obj.TaskResult == (int)KpiTaskResult.Exception)
                {
                    obj.Exception = (int)KpiExecption.Default;
                    obj.ExceptionStatus = EnumHelper.GetEnumDesc(KpiExecption.Default);
                }
                var action = kpiDbContext.siger_project_kpi_action.OrderByDescending(d => d.id).FirstOrDefault(f => f.TaskId == obj.Id);
                if (action == null)
                    continue;
                obj.Exception = (int)KpiExecption.Processing;
                obj.ExceptionStatus = EnumHelper.GetEnumDesc(KpiExecption.Processing);
                var usr = kpiDbContext.siger_project_user.FirstOrDefault(f => f.mid == action.Reposible);
                obj.ResponsibleDepart = usr != null ? usr.sectionid : 0;
                obj.ResponsibleID = usr != null ? usr.mid : 0;
                obj.ResponsiblePersion = usr != null ? usr.name : "";
                obj.Plantime = action.Plantime.ToString("yyyy-MM-dd HH:mm:ss");
                obj.Cause = action.Cause;
                obj.Solution = action.Solution;
                var acrionResult = kpiDbContext.siger_project_kpi_action_result.OrderByDescending(d => d.id).FirstOrDefault(f => f.TaskId == obj.Id);
                if (acrionResult == null)
                    continue;
                if (acrionResult.Result == 1)
                {
                    obj.Exception = (int)KpiExecption.Complated;
                    obj.ExceptionStatus = EnumHelper.GetEnumDesc(KpiExecption.Complated);
                    obj.Operatetime = acrionResult.Time.ToString("yyyy-MM-dd HH:mm:ss");
                }
                var usr2 = kpiDbContext.siger_project_user.FirstOrDefault(f => f.mid == acrionResult.Operater);
                obj.Operater = usr2 != null ? usr2.mid : 0;
                obj.OperaterDesc = usr2 != null ? usr2.name : "";

                obj.ResultDesc = acrionResult.Result == 0 ? "未解决" : "已解决";

            }


            return new PagedCollectionResult<ResponseTasklist>(entities, totalCount);
        }

        public IEnumerable<ResponseKpiActionInfo> GetActionResult(int projectId, List<int> taskIds)
        {
            var query = from a in kpiDbContext.siger_project_kpi_action
                        join r in kpiDbContext.siger_project_kpi_action_result on a.TaskId equals r.TaskId
                        where a.projectId == projectId && taskIds.Contains(a.TaskId)
                        select new ResponseKpiActionInfo
                        {
                            Id=a.id,
                            TaskId=a.TaskId,
                            Plantime=a.Plantime,
                            Resultime=r.Time,
                            Expire=r.Time>a.Plantime?1:0
                            
                        };

            return query.GroupBy(g=>g.Id).Select(s=>s.FirstOrDefault());

        }
    }
}
