
using Siger.Middlelayer.TpmRepository.Entities;
using Siger.Middlelayer.TpmRepository.Repositories.Interface;
using System;
using System.Linq.Expressions;
using System.Linq;
using Siger.Middlelayer.Common;
using Microsoft.EntityFrameworkCore;
using Siger.Middlelayer.Common.Helpers;
using Siger.Middlelayer.TpmRepository.Response;
using System.Collections.Generic;
using Siger.Middlelayer.Repository.Paged;
using Siger.Middlelayer.Common.Log;
using Siger.Middlelayer.Common.Extensions;

namespace Siger.Middlelayer.TpmRepository.Repositories
{
    /// <summary>
	/// SigerAndonProcessRepository
	/// </summary>
    internal class SigerAndonProcessRepository : TpmRepositoryBase<siger_andon_process>, ISigerAndonProcessRepository
    {
        private readonly ApiTpmDbContext _context;
        public SigerAndonProcessRepository(ApiTpmDbContext context) : base(context)
        {
            _context = context;
        }

        public IPagedCollectionResult<ResponseAndonProcess> GetAndonProcessData(string name, int projectid, int page, int pagesize)
        {
            var ret = new List<ResponseAndonProcess>();
            Expression<Func<siger_andon_process, bool>> funName = f => true;
            var query = _context.siger_andon_process.Where(f => f.projectid.Equals(projectid) && f.status == (int)RowState.Valid);
            if (!string.IsNullOrEmpty(name))
            {
                funName = f => f.name.Contains(name);
            }
            var predicates = funName;
            var total = query.Count(predicates);
            var entities = query.Where(predicates).Skip((page - 1) * pagesize).Take(pagesize).AsNoTracking().ToList();
            var userModel = _context.siger_project_user.Where(f => f.projectid.Equals(projectid) && f.status == (int)RowState.Valid).AsNoTracking().ToList();
            var groupModel = _context.siger_project_usergroup.Where(f => f.projectid.Equals(projectid) && f.status == (int)RowState.Valid).AsNoTracking().ToList();
            foreach (var item in entities)
            {
                var data = Mapper<siger_andon_process, ResponseAndonProcess>.Map(item);
                var nodeModel = _context.siger_project_plan_report_level.Where(f => f.project_id.Equals(projectid) && f.status == (int)RowState.Valid && f.process_code.Equals(item.code) && f.mode == 0).AsNoTracking().ToList();
                if (nodeModel != null && nodeModel.Any())
                {
                    var nodes = nodeModel.OrderBy(o => o.level).ToList();//usergroup_id
                    //var currentLevel = nodes.First().level;
                    foreach (var node in nodes)
                    {
                        var currentLevel = nodes.Where(f => f.level == node.level).Last().id;
                        var groupname = groupModel.FirstOrDefault(f => f.id.Equals(node.usergroup_id));
                        if (groupname != null)
                        {
                            data.node += groupname.title;
                        }
                        if (node.id != currentLevel)
                        {
                            data.node += ",";
                        }
                        else
                        {
                            data.node += "-";
                        }
                        currentLevel = node.level;
                    }
                    data.node = data.node.TrimEnd('-');
                    //ProcessLevel
                    for (int i = 1; i < 7; i++)
                    {
                        var group = new ResponseProcessLevel
                        {
                            level = i,
                            groupname = new List<string>(),
                            usergroup = new List<int>()
                        };
                        var usergroup = nodeModel.Where(f => f.level == i).Select(s => s.usergroup_id);
                        if (usergroup != null && usergroup.Any())
                        {
                            var groupdata = groupModel.Where(f => usergroup.Contains(f.id));
                            group.groupname = groupdata.Select(s => s.title).ToList();
                            group.usergroup = usergroup.ToList();
                        }
                        data.ProcessLevel.Add(group);
                    }
                }
                data.creator_name = userModel.FirstOrDefault(f => f.mid.Equals(data.creator))?.name ?? "";
                //ProcessTime
                var timeData = _context.siger_project_plan_report.Where(f => f.projectid.Equals(projectid) && f.status == (int)RowState.Valid && f.process_code.Equals(item.code) && f.mode == 0).AsNoTracking().ToList();
                if (timeData != null && timeData.Any())
                {
                    foreach (var time in timeData)
                    {
                        data.Time.Add(time.start_level.ToString() + "_" + time.type.ToString());
                        data.ProcessTime.Add(Mapper<siger_project_plan_report, ResponseProcessTime>.Map(time));
                    }
                }
                ret.Add(data);
            }
            return new PagedCollectionResult<ResponseAndonProcess>(ret, total);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="projectid"></param>
        /// <param name="mid">用户Mid</param>
        /// <param name="groupid">部门ID</param>
        /// <param name="machine">machineID</param>
        /// <returns></returns>
        public bool CheckInfo(int projectid, int mid, int groupid, int machine)
        {
            var ret = false;
            var groupData = _context.siger_project_usergroup.FirstOrDefault(f => f.id.Equals(groupid) && f.status == (int)RowState.Valid && f.projectid.Equals(projectid));
            if (groupData == null)
            {
                return ret;
            }
            var workingGroupData = _context.siger_project_working_group.Where(f => f.status == (int)RowState.Valid && f.project_id.Equals(projectid)
                                                                                         && f.section_id.Equals(groupData.sectionid) && f.start_date <= DateTime.Now);
            if (!workingGroupData.Any())
            {
                Logger.WriteLineInfo($"groupid:{groupData.parentid}没有维护班组计划！");
                return ret;
            }
            var workingGroupIds = workingGroupData.Select(s => s.id).ToList();
            var userRelation = _context.siger_project_working_relation_user.FirstOrDefault(f => f.projectid == projectid && workingGroupIds.Contains(f.workgroup_id) && f.employ==mid && f.status==(int)RowState.Valid);
            if (userRelation==null)
            {
                Logger.WriteLineInfo($"groupid:{groupData.parentid} 人员 {mid}没有！");
                return false;
            }
            var machineRelation = _context.siger_project_working_relation_machine.FirstOrDefault(f => f.projectid == projectid && f.machine == machine && f.status == (int)RowState.Valid);
            if (machineRelation == null)
            {
                Logger.WriteLineInfo($"groupid:{groupData.parentid} machine {machine}没有分配！");
                return false;
            }
            //foreach (var data in workingGroupData)
            //{
            //    if (data.user_mids.Split(',').ToList().Contains(mid.ToStr()))
            //    {
            //        var machineList = _context.siger_project_working_machine_set.Where(f => f.status == (int)RowState.Valid && f.user_mid.Equals(mid) && f.workinggroup_id.Equals(data.id)).Select(s => s.machine_id);
            //        if (machineList.Contains(machine))
            //        {
            //            ret = true;
            //        }
            //    }
            //}
            return ret;
        }
    }
}
