
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using Microsoft.AspNetCore.Mvc;
using Siger.ApiCommon.Result;
using Siger.Middlelayer.Common;
using Siger.Middlelayer.Common.Extensions;
using Siger.Middlelayer.Common.Helpers;
using Siger.Middlelayer.Redis;
using Siger.Middlelayer.Repository;
using Siger.Middlelayer.Repository.Data;
using Siger.Middlelayer.Repository.Entities;
using Siger.Middlelayer.Repository.Repositories.Interface;
using Siger.Middlelayer.Repository.Request;
using Siger.Middlelayer.Repository.Response;
using Siger.Middlelayer.Utility.Helpers;

namespace Siger.ApiConfig.Controller
{
    public class ProjectUserController : BaseController
    {
        private readonly IUnitOfWork _unitOfWork;
        private readonly ISigerUserRepository _userRepository;
        private readonly ISigerProjectUserRepository _projectUserRepository;
        private readonly ISigerProjectSectionRepository _projectSectionRepository;
        private readonly ISigerProjectUserGroupRepository _projectUserGroupRepository;
        private readonly ISigerProjectLevelSectionRepository _levelSectionRepository;
        private readonly ISigerProjectShiftRepository _projectShiftRepository;
        private readonly ISigerProjectGroupRepository _projectGroupRepository;
        private readonly ISigerProjectStationRepository _projectStationRepository;
        private readonly ISigerProjectLevelSectionMachineRepository _projectLevelSectionMachineRepository;
        private readonly IWorkingCalendarRepository _calendarRepository;
        private readonly IWorkingGroupRepository _groupRepository;
        private readonly ISigerSystemConfigRepository _systemConfigRepository;

        public ProjectUserController(IUnitOfWork unitOfWork, ISigerUserRepository userRepository, ISigerProjectUserRepository projectUserRepository,
            ISigerProjectSectionRepository sectionRepository, ISigerProjectStationRepository projectStationRepository,
            ISigerProjectUserGroupRepository projectUserGroupRepository, ISigerProjectLevelSectionRepository levelSectionRepository,
            ISigerProjectShiftRepository projectShiftRepository, ISigerProjectGroupRepository projectGroupRepository,
            ISigerProjectLevelSectionMachineRepository projectLevelSectionMachineRepository, IWorkingCalendarRepository calendarRepository,
            IWorkingGroupRepository groupRepository, ISigerSystemConfigRepository systemConfigRepository)
        {
            _unitOfWork = unitOfWork;
            _userRepository = userRepository;
            _projectUserRepository = projectUserRepository;
            _projectSectionRepository = sectionRepository;
            _projectUserGroupRepository = projectUserGroupRepository;
            _levelSectionRepository = levelSectionRepository;
            _projectShiftRepository = projectShiftRepository;
            _projectGroupRepository = projectGroupRepository;
            _projectStationRepository = projectStationRepository;
            _projectLevelSectionMachineRepository = projectLevelSectionMachineRepository;
            _calendarRepository = calendarRepository;
            _groupRepository = groupRepository;
            _systemConfigRepository = systemConfigRepository;
        }

        [HttpGet]
        public IActionResult GetCurrentUserInfo()
        {
            var user = _projectUserRepository.GetCurrentUserInfo(UserId);
            if (user == null)
            {
                throw new BadRequestException(RequestEnum.UserNotFound);
            }

            var response = Mapper<CurrentUserInfo, ResponseGetCurrentUserInfo>.Map(user);

            if (!response.logo.StartsWith("http"))
            {
                var dbnameconfig = RedisCache.Instance.GetDbName(CompanyId, ProjectId);
                if (dbnameconfig != null)
                {
                    response.logo = dbnameconfig.ServerIP.ToStr().TrimEnd('/') + "/" + response.logo;
                }
            }

            return new ObjectResult(response);
        }
        /// <summary>
        /// Vue专用获取用户信息
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetCurrentUserInfoEx()
        {
            var showRainbow = _systemConfigRepository.Get(f => f.status != 0 && f.key == SystemConfigKey.ShowRainbow)?.value.ToInt() ?? 0;
            var user = _projectUserRepository.GetCurrentUserInfo(UserId);
            if (user == null)
            {
                return new ObjectResult(new ResponseGetCurrentUserInfo { showRainbow = showRainbow });
                //throw new BadRequestException(RequestEnum.UserNotFound);
            }
            var response = Mapper<CurrentUserInfo, ResponseGetCurrentUserInfo>.Map(user);
            response.user_id = response.mid;
            response.avatar = response.face;
            var access = new List<string>();
            access.Add(response.name);
            response.access = access;
            response.showRainbow = showRainbow;
            return new ObjectResult(response);
        }
        /// <summary>
        /// 获取部门信息
        /// </summary>
        /// <param name="type"> 1->生产部门 2->维修部门 3->质检部门 4->其他</param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetUserDepartment(int type)
        {
            var response = new List<ResponseIdTitle>();
            var list = _projectSectionRepository.GetList(q => q.projectid == ProjectId && q.status == (int)RowState.Valid).ToList();
            if (type != 0)
            {
                list = list.Where(f => f.type == type).ToList();
            }
            foreach (var depart in list)
            {
                response.Add(Mapper<siger_project_section, ResponseIdTitle>.Map(depart));
            }

            return new ObjectResult(response);
        }

        /// <summary>
        /// 获取所有人员
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetAllUser(string name)
        {
            var list = new List<siger_project_user>();
            if (!string.IsNullOrWhiteSpace(name))
            {
                list = _projectUserRepository.GetList(q => q.projectid == ProjectId && q.status == (int)RowState.Valid && q.name.Contains(name)).ToList();
            }
            else
            {
                list = _projectUserRepository.GetList(q => q.projectid == ProjectId && q.status == (int)RowState.Valid).ToList();
            }
            
            return new ObjectResult(list);
        }

        [HttpGet]
        public IActionResult GetUserUserGroup(int sectionid)
        {
            var response = new List<ResponseGetUserGroup>();

            var list = _projectUserGroupRepository.GetList(q => q.sectionid == sectionid && q.status == (int)RowState.Valid);

            foreach (var sigerProjectUsergroup in list)
            {
                response.Add(Mapper<siger_project_usergroup, ResponseGetUserGroup>.Map(sigerProjectUsergroup));
            }

            return new ObjectResult(response);
        }

        [HttpGet]
        public IActionResult GetUserInfoById(int id)
        {
            var user = _projectUserRepository.GetUserInfoById(id);
            if (user == null)
            {
                throw new BadRequestException(RequestEnum.UserNotFound);
            }
            return new ObjectResult(user);
        }

        [HttpGet]
        public IActionResult GetProjectUserItem(int id)
        {
            var user = _projectUserRepository.GetUserInfo(id);
            if (user == null)
            {
                throw new BadRequestException(RequestEnum.UserNotFound);
            }

            return new ObjectResult(user);
        }

        [HttpGet]
        public IActionResult GetProjectUserKeyValue(int id)
        {
            var list = _projectUserRepository.GetUserInfoKey(id, ProjectId);

            return new ObjectResult(list);
        }

        [HttpPost]
        public IActionResult AddProjectUserKeyValue([FromBody]AddProjectUserKeyValue request)
        {
            if (request.field == null)
            {
                throw new BadRequestException(RequestEnum.ProjectUserKeyValueIsEmpty);
            }
            var result = _projectUserRepository.AddProjectUserKeyValue(request.mid, request.field.ToList());

            if (result == ResponseKeyValueResult.Failed)
            {
                throw new BadRequestException(RequestEnum.AddProjectUserKeyValueFailed);
            }

            if (result == ResponseKeyValueResult.KeyHasExist)
            {
                throw new BadRequestException(RequestEnum.ProjectUserKeyValueIsEmpty);
            }

            return new ObjectResult(CommonEnum.Succefull);
        }

        [HttpPost]
        public IActionResult DeleteUserValueField(int id)
        {
            var result = _projectUserRepository.DeleteProjectUserKeyValue(id);

            if (!result)
            {
                throw new BadRequestException(RequestEnum.DeleteProjectUserKeyValueFailed);
            }

            return new ObjectResult(CommonEnum.Succefull);
        }

        [HttpPost]
        public IActionResult AddProjectUser([FromBody]RequestAddProjectUser request)
        {
            if (string.IsNullOrWhiteSpace(request.password))
            {
                throw new BadRequestException(RequestEnum.PasswordIsEmpty);
            }
            var entity = _userRepository.Get(q => q.mobile == request.mobile && q.status == (int)RowState.Valid);
            if (entity != null)
            {
                throw new BadRequestException(RequestEnum.MobileHasExist);
            }
            var puser = _projectUserRepository.Get(q => q.work_code == request.work_code && q.status == (int)RowState.Valid);
            if (puser != null)
            {
                throw new BadRequestException(RequestEnum.WorkcodeHasExist);
            }

            int roleId = 0;
            if (!string.IsNullOrWhiteSpace(request.usergroupid))
            {
                var userGroup = _projectUserGroupRepository.Get(request.usergroupid.ToInt());
                if (userGroup != null)
                {
                    roleId = userGroup.role_id ?? 0;
                }
            }

            var user = new siger_user
            {
                nickname = request.name,
                password = MD5Helper.Get32MD5(request.password),
                face = request.face,
                email = request.email,
                mobile = request.mobile,
                roleid = roleId,
                type = (int)UserType.User,
                sex = request.sex
            };
            _userRepository.Insert(user);
            if (_unitOfWork.Commit() <= 0)
            {
                throw new BadRequestException(CommonEnum.SystemExcetion);
            }

            var userEntity = _userRepository.Get(q => q.mobile == request.mobile && q.status == (int)RowState.Valid);
            var projectUser = new siger_project_user
            {
                mid = userEntity.id,
                name = request.name,
                sex = request.sex,
                work_code = request.work_code,
                usergroupid = request.usergroupid,
                sectionid = request.sectionid.ToInt(),
                mobile = request.mobile,
                fixed_line = request.fixed_line,
                work_email = request.email,
                projectid = ProjectId,
                rank = request.rank,
                create_time = string.IsNullOrEmpty(request.create_time)
                    ? 0
                    : UnixTimeHelper.GetUnixByShortDate(request.create_time)
            };

            _projectUserRepository.Insert(projectUser);
            if (_unitOfWork.Commit() <= 0)
            {
                _userRepository.Delete(userEntity.id);
                throw new BadRequestException(CommonEnum.SystemExcetion);
            }
            return new ObjectResult(CommonEnum.Succefull);
        }

        [HttpPost]
        public IActionResult EditProjectUser([FromBody] RequestUpdateProjectUser request)
        {
            var user = _userRepository.Get(request.id);
            if (user == null || user.status != (int)RowState.Valid)
            {
                throw new BadRequestException(RequestEnum.UserNotFound);
            }
            var projectUser = _projectUserRepository.Get(q => q.mid == request.id && q.status == (int)RowState.Valid);
            if (projectUser == null)
            {
                throw new BadRequestException(RequestEnum.ProjectUserNotFound);
            }
            var puser = _projectUserRepository.Get(q => q.work_code == request.work_code && q.mid != projectUser.mid && q.status == (int)RowState.Valid && q.projectid == ProjectId);
            if (puser != null)
            {
                throw new BadRequestException(RequestEnum.WorkcodeHasExist);
            }
            var muser = _projectUserRepository.Get(q => q.mobile == request.mobile && q.mid != projectUser.mid && q.status == (int)RowState.Valid && q.projectid == ProjectId);
            if (muser != null)
            {
                throw new BadRequestException(RequestEnum.MobileHasExist);
            }
            int roleId = 0;
            if (!string.IsNullOrWhiteSpace(request.usergroupid))
            {
                var userGroup = _projectUserGroupRepository.Get(request.usergroupid.ToInt());
                if (userGroup != null)
                {
                    roleId = userGroup.role_id ?? 0;
                }
            }
            user.nickname = request.name;
            if (!string.IsNullOrWhiteSpace(request.password) && request.password != "******")
            {
                user.password = MD5Helper.Get32MD5(request.password);
            }
            user.face = request.face;
            user.email = request.email;
            user.mobile = request.mobile;
            user.roleid = roleId;
            user.sex = request.sex;
            _userRepository.Update(user);

            projectUser.name = request.name;
            projectUser.sex = request.sex;
            projectUser.work_code = request.work_code;
            projectUser.usergroupid = request.usergroupid;
            projectUser.sectionid = request.sectionid.ToInt();
            projectUser.mobile = request.mobile;
            projectUser.fixed_line = request.fixed_line;
            projectUser.work_email = request.email;
            projectUser.create_time = string.IsNullOrEmpty(request.create_time) ? 0 :
                UnixTimeHelper.GetUnixByShortDate(request.create_time);
            projectUser.rank = request.rank;

            _projectUserRepository.Update(projectUser);
            if (_unitOfWork.Commit() > 0)
            {
                return new ObjectResult(CommonEnum.Succefull);
            }
            throw new BadRequestException(CommonEnum.SystemExcetion);
        }

        [HttpPost]
        public IActionResult DeleteProjectUser(int id)
        {
            var user = _userRepository.Get(q => q.id == id && q.status == (int)RowState.Valid);
            if (user != null)
            {
                user.status = (int)RowState.Invalid;
                _userRepository.Update(user);
            }
            var projectUser = _projectUserRepository.Get(q => q.mid == id && q.status == (int)RowState.Valid);
            if (projectUser != null)
            {
                projectUser.status = (int)RowState.Invalid;
                _projectUserRepository.Update(projectUser);
            }

            //删除班组
            var workgroup = _groupRepository.Get(q =>
                (q.user_mids + ",").Contains(id + ",") && q.status == (int)RowState.Valid && q.project_id == ProjectId);
            if (workgroup != null)
            {
                workgroup.user_mids = workgroup.user_mids.Replace(id + ",", "");
                _groupRepository.Update(workgroup);
            }

            //删除工作日历信息
            var cals = _calendarRepository.GetList(q => q.user_mid == id).ToList();
            if (cals.Any())
            {
                foreach (var cal in cals)
                {
                    var entity = _calendarRepository.Get(q => q.id == cal.id);
                    if (entity != null)
                    {
                        _calendarRepository.Delete(entity);
                    }
                }
            }
            if (_unitOfWork.Commit() > 0)
            {
                return new ObjectResult(CommonEnum.Succefull);
            }
            throw new BadRequestException(RequestEnum.UserNotFound);
        }

        [HttpPost]
        public IActionResult DeleteProjectUsers([FromBody]RequestDeleteEntities request)
        {
            if (request.ids == null || !request.ids.Any())
            {
                throw new BadRequestException(RequestEnum.ParameterError);
            }

            foreach (var id in request.ids)
            {
                var user = _userRepository.Get(q => q.id == id && q.status == (int)RowState.Valid);
                if (user != null)
                {
                    user.status = (int)RowState.Invalid;
                    _userRepository.Update(user);
                }
                var projectUser = _projectUserRepository.Get(q => q.mid == id && q.status == (int)RowState.Valid);
                if (projectUser != null)
                {
                    projectUser.status = (int)RowState.Invalid;
                    _projectUserRepository.Update(projectUser);
                }
            }

            if (_unitOfWork.Commit() > 0)
            {
                return new ObjectResult(CommonEnum.Succefull);
            }
            throw new BadRequestException(CommonEnum.Fail);
        }

        [HttpGet]
        public IActionResult GetGroupsUsers(int groupid)
        {
            var response = new List<string>();
            var list = _projectUserGroupRepository.GetGroupsUsers(groupid);

            foreach (var userGroupTitle in list)
            {
                response.Add(userGroupTitle.usergrouptitle + ":" + userGroupTitle.name);
            }

            return new ObjectResult(response);
        }

        [HttpGet]
        public IActionResult GetUserGroupShiftInfo(int levelid, int sectionid, int groupid, int shiftid, string shiftTitle,
            int dutymid, string start_time, string end_time, int page = 1, int pagesize = PageSize)
        {
            var groupids = new List<int>();
            if (dutymid != 0)
            {
                groupids = _projectUserGroupRepository.GetUser_GroupsByMid(dutymid).Select(m => m.groupid).ToList();
                if (!groupids.Any())
                {
                    return new PagedObjectResult("", 0, page, pagesize);
                }
            }

            var levelIds = new List<int>();
            if (levelid != 0)
            {
                levelIds = _levelSectionRepository.GetLevelSectionIds(levelid, ProjectId).ToList();
            }
            var startDateTime = 0;
            var endDateTime = 0;
            if (!string.IsNullOrEmpty(start_time))
            {
                var result = DateTime.TryParse(start_time, out var date);
                if (result)
                {
                    startDateTime = (int)UnixTimeHelper.ConvertDataTimeLong(date);
                }
            }
            if (!string.IsNullOrEmpty(end_time))
            {
                var result = DateTime.TryParse(end_time, out var date);
                if (result)
                {
                    endDateTime = (int)UnixTimeHelper.ConvertDataTimeLong(date.AddDays(1).AddSeconds(-1));
                }
            }

            var response = new List<ResponseUserGroupShiftInfo>();
            var list = _projectUserRepository.GetUserGroupShiftInfo(levelIds, sectionid, groupids, groupid, shiftid, shiftTitle,
                 startDateTime, endDateTime, ProjectId, page, pagesize);

            foreach (var station in list.Data)
            {
                var titles = _levelSectionRepository.GetLevelSectionTitles(station.sectionid, ProjectId).ToList();
                var res = Mapper<UserGroupShiftInfo, ResponseUserGroupShiftInfo>.Map(station);
                res.create_time = UnixTimeHelper.ConvertIntDateTime(station.createtimeint);
                if (station.starttimeint != 0 && station.endtimeint != 0)
                {
                    res.time_rang = UnixTimeHelper.ConvertIntDate(station.starttimeint) + " - " +
                                    UnixTimeHelper.ConvertIntDate(station.endtimeint);

                    res.stationarr = titles;
                    res.stationstr = string.Join('-', titles);
                }
                response.Add(res);
            }

            return new PagedObjectResult(response, list.Total, page, pagesize);
        }

        [HttpPost]
        public IActionResult MyWorkSliceTime([FromBody]RequestGetSliceWorkTime req)
        {
            var mouthlist = new List<MyWorkSliceTime>();
            var time = DateTime.Now.ToString(ParameterConstant.MouthFirstDay).ToDateTime();
            if (!string.IsNullOrWhiteSpace(req.yearmouth) && req.yearmouth.Length == 6)
            {
                if (!string.IsNullOrWhiteSpace(req.yearmouth) && DateTime.TryParse(req.yearmouth, out DateTime _time))
                {
                    time = _time;
                }
            }
            var startTime = (int)UnixTimeHelper.ConvertDataTimeLong(time);
            var endTime = (int)UnixTimeHelper.ConvertDataTimeLong(time.AddMonths(1).ToString(ParameterConstant.MouthFirstDay + ParameterConstant.TimeFromZero).ToDateTime());

            for (var day = startTime; day < endTime; day += 86400)
            {
                var date = UnixTimeHelper.ConvertStringDateTime(day.ToString());
                var cal = _calendarRepository.Get(q => q.user_mid == UserId && q.date == date && q.project_id == ProjectId && q.status == (int)RowState.Valid);
                if (cal != null)
                {
                    var shift = _projectShiftRepository.Get(q => q.id == cal.shift_id && q.projectid == ProjectId);
                    var mouthmodel = new MyWorkSliceTime
                    {
                        shifttitle = shift.title,
                        daytime = date.ToString(ParameterConstant.DateFormat)
                    };
                    mouthlist.Add(mouthmodel);
                }
                else
                {
                    var mouthmodel = new MyWorkSliceTime
                    {
                        shifttitle = "",
                        daytime = date.ToString(ParameterConstant.DateFormat)
                    };
                    mouthlist.Add(mouthmodel);
                }
            }
            var shifts = new List<MyDayWorkTime>();
            var user = _projectUserRepository.GetCurrentUserInfo(UserId);
            var shiftlist = _projectShiftRepository
                .GetList(q => q.status == (int)RowState.Valid && q.projectid == ProjectId)
                .Where(t => t.sectionid == user.sectionid)
                .GroupBy(t => t.title).Select(t => t.FirstOrDefault()).ToList();
            foreach (var shift in shiftlist)
            {
                shifts.Add(new MyDayWorkTime
                {
                    shifttitle = shift.title,
                    starttime = UnixTimeHelper.GetTimeByUnix(shift.start_time),
                    endtime = UnixTimeHelper.GetTimeByUnix(shift.end_time),
                });
            }

            var res = new ResponseGetMyWorkSliceTime
            {
                mouthtime = mouthlist,
                daytime = shifts
            };

            return new ObjectResult(res);
        }

        [HttpGet]
        public IActionResult GetSectionGroupShifts(int departid, int sectionid)
        {
            if (departid == 0)
            {
                throw new BadRequestException(RequestEnum.SectionIDNotNull);
            }

            var response = new SectionGroupShiftResult();

            var shift = _projectShiftRepository.GetList(q => q.sectionid == departid && q.projectid == ProjectId && q.status == (int)RowState.Valid)
                .OrderBy(m => m.id).ToList();
            foreach (var sigerProjectShift in shift)
            {
                response.shift.Add(new SectionShiftInfo { id = sigerProjectShift.id, title = sigerProjectShift.title });
            }

            var projectGroup = _projectGroupRepository.GetList(q => q.departid == departid && q.projectid == ProjectId && q.status == (int)RowState.Valid);
            foreach (var group1 in projectGroup.ToList())
            {
                response.group.Add(new SectionGroupInfo { id = group1.id, text = group1.name });
            }

            if (sectionid == 0)
            {
                response.msg = CommonEnum.Succefull;
                response.ret = 1;
                return response;
            }

            var now = UnixTimeHelper.GetUnixByShortDate(DateTime.Now.ToShortDateString());
            var list = _projectUserRepository.GetSectionGroupShifts(departid, sectionid, now, ProjectId).ToList();

            foreach (var sectionGroupShift in list)
            {
                var shiftGroup = new SectionShiftGroup();
                if (!response.data.Select(m => m.code).Contains(sectionGroupShift.code))
                {
                    shiftGroup.time = UnixTimeHelper.ConvertIntDate(sectionGroupShift.starttime)
                                      + " - " + UnixTimeHelper.ConvertIntDate(sectionGroupShift.endtime);
                    shiftGroup.code = sectionGroupShift.code;

                    var shiftIds = list.Where(m => m.starttime == sectionGroupShift.starttime
                                                   && m.endtime == sectionGroupShift.endtime).Select(m => m.shiftid).OrderBy(m => m).Distinct();
                    foreach (var shiftId in shiftIds)
                    {
                        var groupIds = list.Where(m => m.shiftid == shiftId
                                                        && m.starttime == sectionGroupShift.starttime
                                                        && m.endtime == sectionGroupShift.endtime).Select(m => m.groupid).Distinct();
                        var group = new SectionShiftGroupInfo();
                        group.shiftid = shiftId;
                        group.groupids = groupIds;

                        shiftGroup.group.Add(group);
                    }

                    response.data.Add(shiftGroup);
                }
            }

            response.msg = CommonEnum.Succefull;
            response.ret = 1;

            return response;
        }

        [HttpGet]
        public IActionResult GetUserShiftById(int id)
        {
            var response = _projectUserRepository.GetUserShiftById(id);

            return new ObjectResult(response);
        }

        [HttpGet]
        public IActionResult GetUserListsBySectionId(int sectionid)
        {
            var list = _projectUserRepository.GetUsersBySectionid(sectionid, ProjectId);

            return new ObjectResult(list);
        }

        [HttpGet]
        public IActionResult GetShifts(int departid)
        {
            var shifts = _projectShiftRepository.GetList(q => q.sectionid == departid && q.projectid == ProjectId && q.status == (int)RowState.Valid).ToList();

            var groups = _projectGroupRepository.GetList(q => q.departid == departid && q.projectid == ProjectId && q.status == (int)RowState.Valid).ToList();

            var result = new SectionShiftResult();
            foreach (var sigerProjectGroup in groups)
            {
                result.group.Add(new SectionGroupInfo { id = sigerProjectGroup.id, text = sigerProjectGroup.name });
            }

            result.data = shifts;
            result.msg = CommonEnum.Succefull;
            result.ret = (int)CommonEnum.Succefull;
            return result;
        }

        [HttpPost]
        public IActionResult SetSectionShiftGroups([FromBody]RequestAddSectionShiftGroup request)
        {
            var sectionIds = request.sectionid.Split(',', StringSplitOptions.RemoveEmptyEntries).Select(t => t.ToInt()).Distinct().ToList();
            var departId = request.departid.ToInt();
            if (!sectionIds.Any() || departId == 0)
            {
                throw new BadRequestException(RequestEnum.SectionIDNotNull);
            }

            var now = UnixTimeHelper.GetUnixByShortDate(DateTime.Now.ToShortDateString());
            var entities = new List<siger_project_station>();
            //没有数据，删除            
            var levelSectionIds = _projectLevelSectionMachineRepository.GetLastSection(ProjectId).Where(t => sectionIds.Contains(t.id)).Select(t => t.id).ToList();

            var SectionIds = new List<int>();

            foreach (var SectionId in levelSectionIds)
            {
                if (request.shifts == null || !request.shifts.Any())
                {
                    var deleteEntities = _projectStationRepository.GetList(q =>
                        q.departid == departId && q.sectionid == SectionId && q.status == (int)RowState.Valid
                        && q.endtime >= now);
                    foreach (var sigerProjectStation in deleteEntities)
                    {
                        sigerProjectStation.status = (int)RowState.Invalid;
                        _projectStationRepository.Update(sigerProjectStation);
                    }
                }
                else
                {
                    //check time
                    var times = new List<TimeCompare>();
                    foreach (var requestShift in request.shifts.ToList())
                    {
                        times.Add(new TimeCompare
                        {
                            StartTime = DateTime.Parse(requestShift.starttime),
                            EndTime = DateTime.Parse(requestShift.endtime)
                        });
                    }

                    for (var i = 0; i < times.Count - 1; i++)
                    {
                        if (times[i].EndTime >= times[i + 1].StartTime)
                        {
                            throw new BadRequestException(RequestEnum.ShiftTimeRangeError);
                        }
                        if (times[i].StartTime == times[i + 1].StartTime)
                        {
                            throw new BadRequestException(RequestEnum.ShiftTimeRangeError);
                        }
                    }

                    var compareResult = _userRepository.CheckShiftTimes(times, SectionId, departId);
                    if (!compareResult)
                    {
                        throw new BadRequestException(RequestEnum.ShiftTimeRangeErrorInDb);
                    }

                    foreach (var requestShift in request.shifts.ToList())
                    {
                        foreach (var selectedShift in requestShift.sg)
                        {
                            if (selectedShift.selectval != null && selectedShift.selectval.Any())
                            {
                                foreach (var groupId in selectedShift.selectval)
                                {
                                    var station = new siger_project_station
                                    {
                                        starttime = UnixTimeHelper.GetUnixByShortDate(requestShift.starttime),
                                        endtime = UnixTimeHelper.GetUnixByShortDate(requestShift.endtime + " 23:59:59"),
                                        departid = departId,
                                        sectionid = SectionId,
                                        shiftid = selectedShift.shiftid,
                                        groupid = groupId
                                    };
                                    entities.Add(station);
                                    SectionIds.Add(SectionId);
                                }
                            }
                        }
                    }
                }
            }
            if (entities.Any())
            {
                var deleteEntities = _projectStationRepository.GetList(q =>
                    q.departid == departId && SectionIds.Contains(q.sectionid) && q.status == (int)RowState.Valid
                    && q.endtime >= now);
                foreach (var sigerProjectStation in deleteEntities)
                {
                    sigerProjectStation.status = (int)RowState.Invalid;
                    _projectStationRepository.Update(sigerProjectStation);
                }
                _projectStationRepository.Insert(entities);
            }
            if (_unitOfWork.Commit() > 0)
            {
                return new ObjectResult(CommonEnum.Succefull);
            }
            throw new BadRequestException(CommonEnum.Fail);
        }

        [HttpPost]
        public IActionResult EditCurrentUserInfo([FromBody]RequestUpdateCurrentUser request)
        {
            var user = _userRepository.Get(UserId);
            if (user == null || user.status != (int)RowState.Valid)
            {
                throw new BadRequestException(RequestEnum.UserNotFound);
            }
            var projectUser = _projectUserRepository.Get(q => q.mid == UserId && q.status == (int)RowState.Valid);
            if (projectUser == null)
            {
                throw new BadRequestException(RequestEnum.ProjectUserNotFound);
            }

            user.nickname = request.name;
            if (!string.IsNullOrWhiteSpace(request.password))
            {
                user.password = MD5Helper.Get32MD5(request.password);
            }
            user.face = request.face;
            user.email = request.work_email;
            _userRepository.Update(user);

            projectUser.name = request.name;
            projectUser.sex = request.sex;
            projectUser.fixed_line = request.fixed_line;
            projectUser.work_email = request.work_email;

            _projectUserRepository.Update(projectUser);
            if (_unitOfWork.Commit() > 0)
            {
                return new ObjectResult(CommonEnum.Succefull);
            }
            throw new BadRequestException(CommonEnum.SystemExcetion);
        }
        /// <summary>
        /// 获取人员信息
        /// </summary>
        /// <param name="name"></param>
        /// <param name="type"> 1->生产部门 2->维修部门 3->质检部门 4->其他</param>
        /// <param name="department"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetAllUserByCurrentProjectId(string name, int type, int department)
        {
            var user = _projectUserRepository.Get(f => f.projectid == ProjectId && f.status == (int)RowState.Valid);
            if (user == null)
            {
                return new ObjectResult(CommonEnum.Succefull);
            }
            var response = _projectUserRepository
                .GetList(f => f.projectid == ProjectId && f.status == (int)RowState.Valid).Select(f =>
                   new ResponseAllUserByCurrentUserProjectId
                   {
                       id = f.id,
                       mid = f.mid,
                       name = f.name,
                       work_code = f.work_code,
                       sectionid = f.sectionid
                   }).ToList();
            if (!response.Any())
            {
                return new ObjectResult(CommonEnum.Succefull);
            }
            if (!string.IsNullOrEmpty(name))
            {
                response = response.Where(f => f.name.Contains(name)).ToList();
            }
            if (type != 0)
            {
                var sections = _projectSectionRepository.GetList(f => f.projectid == ProjectId && f.status != 0 && f.type == type).Select(s => s.id).ToList();
                response = response.Where(f => sections.Contains(f.sectionid)).ToList();
            }
            if (department != 0)
            {
                response = response.Where(f => f.sectionid == department).ToList();
            }
            return new ObjectResult(response);
        }

        /// <summary>
        /// 获取项目用户，type=1:生产部门 type=2:维修部门
        /// </summary>
        /// <param name="typeId"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetProductionUsers(int typeId)
        {
            var users = _projectUserRepository.GetProductionUsers(ProjectId, typeId);

            return new ObjectResult(users);
        }

        [HttpGet]
        public IActionResult GetWorkByKeyword(string keyword)
        {
            var response = _projectUserRepository
                .GetList(f => f.projectid == ProjectId && f.status == (int)RowState.Valid)
                .Select(f => new ResponseAllUserByCurrentUserProjectId
                {
                    id = f.id,
                    mid = f.mid,
                    name = f.name,
                    work_code = f.work_code
                });

            if (!string.IsNullOrWhiteSpace(keyword))
            {
                response = response.Where(q => q.name.Contains(keyword) || q.work_code.Contains(keyword));
            }
            return new ObjectResult(response.ToList());
        }


        /// <summary>
        /// 刷新在线时间
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public IActionResult RefreshOnline()
        {
            var result = _projectUserRepository.RefreshOnLine(UserId, ProjectId);
            return new ObjectResult(result);
        }

        /// <summary>
        /// 修改密码
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public IActionResult UpdatePassWord([FromBody]RequestUpdatePassWord req)
        {
            if (string.IsNullOrWhiteSpace(req.password) || string.IsNullOrEmpty(req.oldpassword))
            {
                throw new BadRequestException(RequestEnum.PasswordIsEmpty);
            }
            var regex1 = new Regex(@"
                (?=.*[a-zA-Z])                  #必须包含小写或大写字母
                (?=([\x21-\x7e]+)[^a-zA-Z0-9])  #必须包含特殊符号
                .{6,16}                         #至少8个字符，最多30个字符
                ", RegexOptions.Multiline | RegexOptions.IgnorePatternWhitespace);
            var regex2 = new Regex(@"
                (?=.*[0-9])                     #必须包含数字
                (?=([\x21-\x7e]+)[^a-zA-Z0-9])  #必须包含特殊符号
                .{6,16}                         #至少8个字符，最多30个字符
                ", RegexOptions.Multiline | RegexOptions.IgnorePatternWhitespace);
            var regex3 = new Regex(@"
                (?=.*[0-9])                     #必须包含数字
                (?=.*[a-zA-Z])                  #必须包含小写或大写字母
                .{6,16}                         #至少8个字符，最多30个字符
                ", RegexOptions.Multiline | RegexOptions.IgnorePatternWhitespace);
            var regex = "[\u4e00-\u9fa5]|([\u3000])|([\u0020])";//中文 半角全角空格
            if (Regex.IsMatch(req.password, regex))
            {
                throw new BadRequestException(RequestEnum.PassWordFormatError);
                //Console.WriteLine("不能含有中文和空格");
            }
            if (regex1.IsMatch(req.password) || regex2.IsMatch(req.password) || regex3.IsMatch(req.password))
            {
                var user = _userRepository.Get(t => t.id == UserId);
                if (user != null)
                {
                    var pd = MD5Helper.Get32MD5(req.password);
                    var oldpd = MD5Helper.Get32MD5(req.oldpassword);
                    if (user.password == oldpd)
                    {
                        user.password = pd;
                        _userRepository.Update(user);
                        if (_unitOfWork.Commit() > 0)
                        {
                            return new ObjectResult(CommonEnum.Succefull);
                        }
                    }
                    else
                    {
                        throw new BadRequestException(RequestEnum.OldPassWordError);
                    }
                }
            }
            else
            {
                throw new BadRequestException(RequestEnum.PassWordFormatError);
            }
            throw new BadRequestException(CommonEnum.Fail);
        }


        /// <summary>
        /// <param name="type">用户类型0超级管理员1普通用户2管理员</param>
        /// <param name="section">部门属性 1 生产部门 2维修部门</param>
        /// <returns></returns>
        /// </summary> 
        [HttpGet]
        public IActionResult GetProjectUserList(int type, int section)
        {
            var res = _projectUserRepository.GetProjectUserList(type, section, ProjectId);
            return new ObjectResult(res.ToList());
        }

        [HttpGet]
        public IActionResult GetEmails()
        {

            var eUser = new List<ResponseUserEmailInfo>();
            var projectUser = _projectUserRepository.GetList(f => f.projectid == ProjectId && f.status == (int)RowState.Valid && !string.IsNullOrEmpty(f.work_email), "mid", false);

            foreach (var u in projectUser)
            {
                eUser.Add(new ResponseUserEmailInfo
                {
                    Mid = u.mid,
                    Name = u.name,
                    Email = u.work_email
                });
            }
            return new ObjectResult(eUser);
        }
        /// <summary>
        /// 合作维修
        /// </summary>
        /// <param name="sectionid"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetAppProjectUsers(int sectionid)
        {
            var responses = new List<ResponseGetAppProjectUser>();
            var users = _projectUserRepository.GetSectionUserList(sectionid, ProjectId).ToList();
            if (!users.Any())
            {
                return new ObjectResult(responses);
            }

            foreach (var projectUser in users)
            {
                var response = new ResponseGetAppProjectUser
                {
                    name = projectUser.name,
                    employee_id = projectUser.id,
                    position = projectUser.usergrouptitle,
                    phonetic = PinYinHelper.ToPinYin(projectUser.name)
                };
                responses.Add(response);
            }

            return new ObjectResult(responses);
        }
    }
}