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

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

        public CurrentUserInfo GetCurrentUserInfo(int mid)
        {
            var user = new CurrentUserInfo();
            var us = _context.siger_user.FirstOrDefault(q => q.status == (int)RowState.Valid && q.id == mid);
            if (us != null)
            {
                user.face = us.face;

                user.mobile = us.mobile;
                if (us.type == (int)UserType.SuperAdmin)
                {
                    user.mobile = us.mobile;
                    user.name = us.realname;
                    user.sex = us.sex == (int)Gender.male ? "男" : "女";
                    user.work_email = us.email;
                    return user;
                }
            }

            var projectUser = from q in _context.siger_project_user
                              join p in _context.siger_project on q.projectid equals p.id
                              join c in _context.siger_company on p.companyid equals c.id.ToString()
                              join s in _context.siger_project_section on q.sectionid equals s.id into ss
                              from sec in ss.DefaultIfEmpty()
                              join g in _context.siger_project_usergroup on q.usergroupid equals g.id.ToString() into gg
                              from gro in gg.DefaultIfEmpty()
                              where q.status == (int)RowState.Valid && q.mid == mid
                              select new CurrentUserInfo
                              {
                                  mid = q.mid,
                                  fixed_line = q.fixed_line,
                                  mobile = q.mobile,
                                  name = q.name,
                                  sectionid = q.sectionid,
                                  work_code = q.work_code,
                                  sex = q.sex == (int)Gender.male ? "男" : "女",
                                  work_email = q.work_email,
                                  company_name = c.chinesename,
                                  project_name = p.title,
                                  sectiontype = sec == null ? 0 : sec.type,
                                  sectiontitle = sec == null ? "" : sec.title,
                                  usergroupid = gro == null ? 0 : gro.id,
                                  usergrouptitle = gro == null ? "" : gro.title,
                                  logo = c.litpic,
                                  remark = c.description,
                                  face = user.face,
                                  projectId = p.id
                              };

            return projectUser.FirstOrDefault();
        }

        public ProjectUserInfo GetUserInfoById(int id)
        {
            var query = _context.siger_project_user.Where(q => q.status == (int)RowState.Valid && q.mid == id);
            var queryList = from q in query
                            join us1 in _context.siger_user on q.mid equals us1.id
                            where us1.status == (int)RowState.Valid
                            join c in _context.siger_project_section on q.sectionid equals c.id into group1
                            from c in group1.DefaultIfEmpty()
                            where c.status == (int)RowState.Valid
                            join ug1 in _context.siger_project_usergroup on q.usergroupid equals ug1.id.ToString() into userg1
                            from ug1 in userg1.DefaultIfEmpty()
                            where ug1.status == (int)RowState.Valid
                            select new ProjectUserInfo
                            {
                                account = us1.mobile,
                                face = us1 != null ? us1.face : "",
                                id = q.mid,
                                name = q.name,
                                work_code = q.work_code,
                                sex = q.sex == (int)Gender.male ? "男" : "女",
                                sectiontitle = c != null ? c.title : "",
                                usergrouptitle = ug1 != null ? ug1.title : "",
                                fixed_line = q.fixed_line,
                                mobile = q.mobile,
                                work_email = q.work_email,
                                create_time = q.create_time == 0 ? "" : UnixTimeHelper.ConvertIntDate(q.create_time)
                            };

            var userkeyvalues = from k in _context.siger_project_user_info_key
                                join va in _context.siger_project_user_info_value on k.id equals va.keyid
                                where k.status == (int)RowState.Valid && va.status == (int)RowState.Valid
                                                                       && va.mid == id
                                select new UserInfoKey
                                {
                                    id = va.id,
                                    title = k.title,
                                    value = va.value
                                };

            var user = queryList.FirstOrDefault();
            if (user != null)
            {
                var vakues = new List<UserInfoKey>();
                foreach (var userkeyvalue in userkeyvalues)
                {
                    vakues.Add(userkeyvalue);
                }

                user.fields = vakues;
            }

            if (user != null)
            {
                var now = UnixTimeHelper.GetNow();
                var titles = from s in _context.siger_project_station
                             join g in _context.siger_project_user_group on s.groupid equals g.groupid
                             join sec in _context.siger_project_level_section on s.sectionid equals sec.id
                             where s.starttime <= now && s.endtime >= now && g.mid == id && sec.status == (int)RowState.Valid
                             select sec.title;

                var title = titles.Distinct().ToList();
                user.position = title.Any() ? string.Join(",", title) : "暂无数据";
            }

            return user;
        }

        public UserInfo GetUserInfo(int mid)
        {
            var user = from q in _context.siger_project_user
                       join c in _context.siger_project_section on q.sectionid equals c.id into group1
                       from c in group1.DefaultIfEmpty()
                       join u1 in _context.siger_project_usergroup on q.usergroupid equals u1.id.ToString() into user1
                       from u1 in user1.DefaultIfEmpty()
                       join u2 in _context.siger_user on q.mid equals u2.id into user2
                       from u2 in user2.DefaultIfEmpty()
                       where q.status == (int)RowState.Valid && q.mid == mid
                       select new UserInfo
                       {
                           create_time = q.create_time == 0 ? "" : UnixTimeHelper.ConvertIntDate(q.create_time),
                           fixed_line = q.fixed_line,
                           mobile = q.mobile,
                           name = q.name,
                           sectionid = q.sectionid,
                           sectiontitle = c != null ? c.title : "",
                           sex = q.sex.ToString(),
                           usergroupid = u1 != null ? u1.id : 0,
                           usergrouptitle = u1 != null ? u1.title : "",
                           work_code = q.work_code,
                           work_email = q.work_email,
                           password = u2 != null ? u2.password : "",
                           face = u2 != null ? u2.face : "",
                           username = u2 != null ? u2.nickname : "",
                           usertype = u2 != null ? u2.type : 1,
                           rank = q.rank
                       };

            return user.FirstOrDefault();
        }
        /// <summary>
        /// 获取项目下所以人员
        /// </summary>
        /// <param name="projectId"></param>
        /// <returns></returns>
        public IEnumerable<UserInfo> GetUserInfoList(int projectId)
        {
            var query = from q in _context.siger_project_user
                       join c in _context.siger_project_section on q.sectionid equals c.id into group1
                       from c in group1.DefaultIfEmpty()
                       join u1 in _context.siger_project_usergroup on q.usergroupid equals u1.id.ToString() into user1
                       from u1 in user1.DefaultIfEmpty()
                       where q.status == (int)RowState.Valid && q.projectid == projectId
                        select new UserInfo
                       {
                           mid=q.mid,
                           create_time = q.create_time == 0 ? "" : UnixTimeHelper.ConvertIntDate(q.create_time),
                           fixed_line = q.fixed_line,
                           mobile = q.mobile,
                           name = q.name,
                           sectionid = q.sectionid,
                           sectiontitle = c != null ? c.title : "",
                           sex = q.sex.ToString(),
                           usergroupid = u1 != null ? u1.id : 0,
                           usergrouptitle = u1 != null ? u1.title : "",
                           work_code = q.work_code,
                           work_email = q.work_email,
                           rank = q.rank
                       };

            return query;
        }

        public IEnumerable<IdTitle> GetUserInfoKey(int mid, int projectid)
        {
            var idTitles = new List<IdTitle>();
            var user = _context.siger_project_user.FirstOrDefault(q => q.mid == mid && q.projectid == projectid && q.status == (int)RowState.Valid);
            if (user != null)
            {
                var usergroupId = int.Parse(user.usergroupid);
                var list = _context.siger_project_user_info_key.Where(q =>
                    q.projectid == projectid && q.usergroupid == usergroupId &&
                    q.status == (int)RowState.Valid);

                foreach (var sigerProjectUserInfoKey in list)
                {
                    idTitles.Add(new IdTitle { id = sigerProjectUserInfoKey.id, title = sigerProjectUserInfoKey.title });
                }
            }
            return idTitles;
        }

        public ResponseKeyValueResult AddProjectUserKeyValue(int mid, IList<ProjectUserKeyValue> keyValues)
        {
            try
            {
                var keys =
                    _context.siger_project_user_info_value.Where(q => q.mid == mid && q.status == (int)RowState.Valid)
                        .Select(q => q.keyid);
                foreach (var projectUserKeyValue in keyValues)
                {
                    if (keys.Contains(projectUserKeyValue.kid))
                    {
                        return ResponseKeyValueResult.KeyHasExist;
                    }
                }

                var list = new List<siger_project_user_info_value>();
                foreach (var projectUserKeyValue in keyValues)
                {
                    var userInfoValue = new siger_project_user_info_value
                    {
                        mid = mid,
                        keyid = projectUserKeyValue.kid,
                        value = projectUserKeyValue.kvalue,
                        status = (int)RowState.Valid
                    };
                    list.Add(userInfoValue);
                }
                _context.siger_project_user_info_value.AddRange(list);
                if (_context.SaveChanges() > 0)
                {
                    return ResponseKeyValueResult.Successful;
                }
            }
            catch
            {
                return ResponseKeyValueResult.Failed;
            }
            return ResponseKeyValueResult.Failed;
        }

        public bool DeleteProjectUserKeyValue(int id)
        {
            var entity = _context.siger_project_user_info_value.FirstOrDefault(q => q.id == id && q.status == (int)RowState.Valid);
            if (entity != null)
            {
                entity.status = (int)RowState.Invalid;
                _context.siger_project_user_info_value.Update(entity);
                if (_context.SaveChanges() > 0)
                {
                    return true;
                }
            }

            return false;
        }

        public IEnumerable<ProjectUserInfo> GetUsersBySectionid(int sectionId, int projectId)
        {
            var query = from q in _context.siger_project_user
                        join c in _context.siger_project_section on q.sectionid equals c.id
                        join u1 in _context.siger_project_usergroup on q.usergroupid equals u1.id.ToString()
                        where q.status == (int)RowState.Valid && c.status == (int)RowState.Valid && u1.status == (int)RowState.Valid
                              && q.projectid == projectId && q.sectionid == sectionId
                        select new ProjectUserInfo
                        {
                            id = q.mid,
                            name = q.name,
                            work_code = q.work_code,
                            sex = q.sex.ToString(),
                            sectiontitle = c != null ? c.title : "",
                            usergrouptitle = u1 != null ? u1.title : "",
                            create_time = q.create_time.ToString(),
                            fixed_line = q.fixed_line,
                            mobile = q.mobile,
                            work_email = q.work_email,
                        };

            return query.ToList();
        }

        public IPagedCollectionResult<UserGroupShiftInfo> GetUserGroupShiftInfo(List<int> levelids, int sectionid, List<int> groupids, int groupid, int shiftid,
            string shiftTitle, int startTime, int endTime, int projectid, int page, int pagesize)
        {
            var now = UnixTimeHelper.GetUnixByShortDate(DateTime.Now.ToShortDateString());
            var query = _context.siger_project_station.Where(q => q.endtime >= now && q.status == (int)RowState.Valid);

            var querylist = from st in query
                            join gr in _context.siger_project_group on st.groupid equals gr.id
                            join sh in _context.siger_project_shift on st.shiftid equals sh.id
                            join se in _context.siger_project_section on gr.departid equals se.id
                            where gr.projectid == projectid && sh.projectid == projectid && se.projectid == projectid && gr.projectid == projectid
                            orderby st.endtime descending, st.shiftid, st.groupid, st.id
                            select new UserGroupShiftInfo
                            {
                                id = st.id,
                                dutymid = st.dutymid,
                                sectionid = st.sectionid,
                                departid = st.departid,
                                groupid = st.groupid,
                                starttimeint = st.starttime,
                                endtimeint = st.endtime,
                                groupname = gr.name,
                                shiftid = sh.id,
                                shifttitle = sh.title,
                                sectiontitle = se.title,
                                createtimeint = st.created_at
                            };

            Expression<Func<UserGroupShiftInfo, bool>> levelIdsExpression = q => true;
            if (levelids.Any())
            {
                levelIdsExpression = q => levelids.Contains(q.sectionid);
            }
            Expression<Func<UserGroupShiftInfo, bool>> groupidsExpression = q => true;
            if (groupids.Any())
            {
                groupidsExpression = q => groupids.Contains(q.groupid);
            }
            Expression<Func<UserGroupShiftInfo, bool>> sectionIdExpression = q => true;
            if (sectionid != 0)
            {
                sectionIdExpression = q => q.departid == sectionid;
            }
            Expression<Func<UserGroupShiftInfo, bool>> groupIdExpression = q => true;
            if (groupid != 0)
            {
                groupIdExpression = q => q.groupid == groupid;
            }

            Expression<Func<UserGroupShiftInfo, bool>> shiftIdExpression = q => true;
            if (shiftid != 0)
            {
                shiftIdExpression = q => q.shiftid == shiftid;
            }
            Expression<Func<UserGroupShiftInfo, bool>> shiftTitleExpression = q => true;
            if (!string.IsNullOrWhiteSpace(shiftTitle) && shiftTitle != "0" && shiftTitle != "0x")
            {
                shiftTitleExpression = q => q.shifttitle.Contains(shiftTitle);
            }
            Expression<Func<UserGroupShiftInfo, bool>> timeExpression = q => true;
            if (startTime != 0 && endTime != 0)
            {
                timeExpression = q => q.starttimeint <= endTime && q.endtimeint >= startTime;
            }

            var predicate = levelIdsExpression.And(groupidsExpression).And(sectionIdExpression).And(groupIdExpression)
                .And(shiftIdExpression).And(shiftTitleExpression).And(timeExpression);

            var totalCount = querylist.Count(predicate);
            var entities = querylist.Where(predicate).Skip((page - 1) * pagesize).Take(pagesize).AsNoTracking().ToList();

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

        public IEnumerable<SectionGroupShift> GetSectionGroupShifts(int departid, int sectionid, int unixNow, int projectid)
        {
            var query = from q in _context.siger_project_station
                        join sta in _context.siger_project_group on q.groupid equals sta.id into station
                        from sta in station.DefaultIfEmpty()
                        join sec in _context.siger_project_section on sta.departid equals sec.id into section
                        from sec in section.DefaultIfEmpty()
                        where q.sectionid == sectionid && sta.projectid == projectid && sta.departid == departid &&
                              q.endtime >= unixNow && q.status == (int)RowState.Valid && sec.status == (int)RowState.Valid
                        select new SectionGroupShift
                        {
                            sectionid = q.sectionid,
                            shiftid = q.shiftid,
                            groupid = q.groupid,
                            starttime = q.starttime,
                            endtime = q.endtime,
                            title = sec != null ? sec.title : "",
                            name = sta != null ? sta.name : "",
                            code = q.starttime + "-" + q.endtime
                        };
            return query.OrderBy(q => q.starttime).ToList();
        }

        public ResponseGetUserShiftById GetUserShiftById(int id)
        {
            var query = from q in _context.siger_project_station
                        join sta in _context.siger_project_group on q.groupid equals sta.id into station
                        from sta in station.DefaultIfEmpty()
                        join sec in _context.siger_project_level_section on q.sectionid equals sec.id into section
                        from sec in section.DefaultIfEmpty()
                        where q.status == (int)RowState.Valid && sec.status == (int)RowState.Valid && sta.status == (int)RowState.Valid
                        select new ResponseGetUserShiftById
                        {
                            name = sta != null ? sta.name : "",
                            departmentid = sta != null ? sta.departid : 0,
                            sectiontitle = sec != null ? sec.title : ""
                        };
            return query.FirstOrDefault();
        }

        public IEnumerable<ResponseGetProductionUser> GetProductionUsers(int projectId, int typeId)
        {
            var query = from q in _context.siger_project_user
                        join s in _context.siger_project_section on q.sectionid equals s.id into sec
                        from ss in sec.DefaultIfEmpty()
                        where q.projectid == projectId && q.status == (int)RowState.Valid && ss.type == typeId &&
                              ss.status == (int)RowState.Valid
                        select new ResponseGetProductionUser
                        {
                            mid = q.mid,
                            name = q.name,
                            work_code = q.work_code
                        };

            return query.AsEnumerable();
        }

        public int UpdateUserAppKey(int mid, string appKey, int projectId)
        {
            //每个appkey 当前对应 对应一个用户

            //var entity = _context.siger_app_project_user.FirstOrDefault(q => q.projectId == projectId && q.mid == mid);
            //if (entity != null)
            //{
            //    entity.appkey = appKey;
            //    entity.status = (int)RowState.Valid;
            //    entity.refresh_time = DateTime.Now;
            //    _context.siger_app_project_user.Update(entity);
            //    return _context.SaveChanges();
            //}
            var entitys = _context.siger_app_project_user.Where(q => q.appkey == appKey).ToList();
            if (entitys.Any())
            {
                foreach(var entity in entitys)
                {
                    _context.siger_app_project_user.Remove(entity);
                    _context.SaveChanges();
                }
            }
            var entityUsrs = _context.siger_app_project_user.Where(q => q.mid == mid).ToList();
            if (entityUsrs.Any())
            {
                foreach (var entity in entityUsrs)
                {
                    _context.siger_app_project_user.Remove(entity);
                    _context.SaveChanges();
                }
            }

            var user = new siger_app_project_user
            {
                appkey = appKey,
                mid = mid,
                projectId = projectId,
                refresh_time = DateTime.Now,
                status = (int)RowState.Valid
            };
            _context.siger_app_project_user.Add(user);
            return _context.SaveChanges();
        }

        public string GetUserAppKey(int mid, int projectId)
        {
            var entity = _context.siger_app_project_user.FirstOrDefault(q => q.projectId == projectId && q.mid == mid && q.status == (int)RowState.Valid);
            if (entity != null)
            {
                return entity.appkey;
            }

            return string.Empty;
        }

        public string GetUserMobile(int mid, int projectId)
        {
            var entity = _context.siger_project_user.FirstOrDefault(q => q.projectid == projectId && q.mid == mid && q.status == (int)RowState.Valid);
            if (entity != null)
            {
                return entity.mobile;
            }

            return string.Empty;
        }

        public int RefreshOnLine(int mid, int projectId)
        {
            var entity = _context.siger_app_project_user.FirstOrDefault(q => q.projectId == projectId && q.mid == mid);
            if (entity != null)
            {
                entity.status = (int)RowState.Valid;
                entity.refresh_time = DateTime.Now;
                _context.siger_app_project_user.Update(entity);
                return _context.SaveChanges();
            }

            return 0;
        }

        public bool IsOnlie(int mid, int projectId, string key)
        {
            var intervalMinutes = 5;
            var config = _context.siger_system_config.FirstOrDefault(q => q.key == key && q.status == (int)RowState.Valid);
            if (config != null)
            {
                var interval = config.value.ToInt();
                if (interval > 0)
                {
                    intervalMinutes = interval;
                }
            }

            var entity = _context.siger_app_project_user.FirstOrDefault(q => q.projectId == projectId && q.mid == mid && q.status == (int)RowState.Valid);
            if (entity != null)
            {
                if (entity.refresh_time != null)
                {
                    if (DateTime.Now.Subtract(entity.refresh_time.Value).TotalMinutes <= intervalMinutes)
                    {
                        return true;
                    }
                }

                return false;
            }

            return false;
        }

        public IEnumerable<UserGroupShiftInfo> GetUserGroupShiftList(List<int> groupids, int groupid, int shiftid, int startTime, int endTime)
        {
            var now = UnixTimeHelper.GetUnixByShortDate(DateTime.Now.ToShortDateString());
            var query = _context.siger_project_station.Where(q => q.endtime >= now && q.status == (int)RowState.Valid);

            var querylist = from st in query
                            join gr in _context.siger_project_group on st.groupid equals gr.id
                            join sh in _context.siger_project_shift on st.shiftid equals sh.id
                            join se in _context.siger_project_section on gr.departid equals se.id
                            orderby st.endtime descending, st.shiftid, st.groupid, st.id
                            select new UserGroupShiftInfo
                            {
                                id = st.id,
                                dutymid = st.dutymid,
                                sectionid = st.sectionid,
                                departid = st.departid,
                                groupid = st.groupid,
                                starttimeint = st.starttime,
                                endtimeint = st.endtime,
                                groupname = gr.name,
                                shiftid = sh.id,
                                shifttitle = sh.title,
                                sectiontitle = se.title,
                                createtimeint = st.created_at
                            };

            Expression<Func<UserGroupShiftInfo, bool>> groupidsExpression = q => true;
            if (groupids.Any())
            {
                groupidsExpression = q => groupids.Contains(q.groupid);
            }
            Expression<Func<UserGroupShiftInfo, bool>> shiftIdExpression = q => true;
            if (shiftid != 0)
            {
                shiftIdExpression = q => q.shiftid == shiftid;
            }
            Expression<Func<UserGroupShiftInfo, bool>> timeExpression = q => true;
            if (startTime != 0 && endTime != 0)
            {
                timeExpression = q => q.starttimeint <= endTime && q.endtimeint >= startTime;
            }

            var predicate = groupidsExpression.And(shiftIdExpression).And(timeExpression);

            var entities = querylist.Where(predicate).AsNoTracking().ToList();

            return entities;
        }

        public IEnumerable<ResponseGetUserList> GetProjectUserList(int type, int sectionType, int projectId)
        {
            var projectUsers = _context.siger_project_user.Where(t => t.status == (int)RowState.Valid && t.projectid == projectId);

            var query = from q in projectUsers
                        join p in _context.siger_user on q.mid equals p.id
                        join s in _context.siger_project_section on q.sectionid equals s.id
                        into sec
                        from s in sec.DefaultIfEmpty()
                        select new ResponseGetUserList
                        {
                            id = q.mid,
                            realname = q.name,
                            nickname = q.name,
                            roleid = p.roleid > 0 ? p.roleid : 0,
                            sectiontype = s.type > 0 ? s.type : 0,
                            type = p.type > 0 ? p.type : 0,
                            mobile = q.mobile,
                            usergroupid = q.usergroupid.ToInt()
                        };

            Expression<Func<ResponseGetUserList, bool>> typeExpression = q => true;
            if (type > 0)
            {
                typeExpression = q => q.type == type;
            }
            Expression<Func<ResponseGetUserList, bool>> sectionTypeExpression = q => true;
            if (sectionType > 0)
            {
                sectionTypeExpression = q => q.sectiontype == sectionType;
            }

            var entities = query.Where(sectionTypeExpression).AsNoTracking().ToList();
            return entities;
        }

        public IEnumerable<ResponseGetSectionUserList> GetSectionUserList(int sectionId, int projectId)
        {
            var query = from q in _context.siger_project_user
                        join s in _context.siger_project_section on q.sectionid equals s.id
                        join us in _context.siger_project_usergroup on q.usergroupid equals us.id.ToString()
                        where q.sectionid == sectionId && q.projectid == projectId && q.status == (int)RowState.Valid
                        select new ResponseGetSectionUserList
                        {
                            id = q.mid,
                            name = q.name,
                            mobile = q.mobile,
                            work_email = q.work_email,
                            sectiontitle = s.title,
                            usergrouptitle = us.title,
                            work_code = q.work_code,
                            isvalid = q.status,
                            create_time = UnixTimeHelper.ConvertIntDateTime(q.create_time)
                        };
            return query.ToList();
        }
        /// <summary>
        /// 根据mid获取当前用户所管辖的设备信息
        /// </summary>
        /// <param name="pid"></param>
        /// <param name="mid"></param>
        /// <returns></returns>
        public List<siger_project_machine> GetMachinesByMid(int pid, int mid)
        {
            var ret = new List<siger_project_machine>();
            var user = _context.siger_project_user.FirstOrDefault(f => f.projectid == pid && f.status != 0 && f.mid == mid);
            if (user == null)
            {
                return ret;
            }
            var groupdata = _context.siger_project_working_group.Where(f => f.section_id == user.sectionid && f.status != 0 && f.project_id == pid && f.start_date <= DateTime.Now);
            if (groupdata == null)
            {
                return ret;
            }
            foreach (var item in groupdata)
            {
                if (item.user_mids.Split(',').Contains(mid.ToStr()))
                {
                    var machineids = _context.siger_project_working_machine_set.Where(f => f.status == (int)RowState.Valid && f.user_mid==mid && f.workinggroup_id.Equals(item.id)).Select(s => s.machine_id).ToList();
                    if (machineids.Any())
                    {
                        return _context.siger_project_machine.Where(f => f.status != 0 && machineids.Contains(f.id) && f.projectid == pid).ToList();
                    }
                }
            }
            return ret;
        }

        public UserInfo GetUserInfoByName(string name)
        {
            var user = from q in _context.siger_project_user
                       join c in _context.siger_project_section on q.sectionid equals c.id into group1
                       from c in group1.DefaultIfEmpty()
                       join u1 in _context.siger_project_usergroup on q.usergroupid equals u1.id.ToString() into user1
                       from u1 in user1.DefaultIfEmpty()
                       where q.name.Contains(name)
                       select new UserInfo
                       {
                           name = q.name,
                           sectionid = c != null ? c.id : 0,
                           sectiontitle = c != null ? c.title : "",
                           usergroupid = u1 != null ? u1.id : 0,
                           usergrouptitle = u1 != null ? u1.title : ""
                       };
            return user.FirstOrDefault();
        }

        public siger_project_user GetProjectManager(int projectId)
        {
            var adminuser = _context.siger_user.Where(f => f.type == (int)UserType.Admin).Select(s => s.id).ToList();
            return _context.siger_project_user.FirstOrDefault(f => adminuser.Contains(f.mid) && f.projectid == projectId);
        }
    }
}
