using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using NPOI.HSSF.Record;
using Siger.ApiCommon.Result;
using Siger.ApiCommon.Utilities;
using Siger.Middlelayer.Common;
using Siger.Middlelayer.Common.AppSettings;
using Siger.Middlelayer.Common.Extensions;
using Siger.Middlelayer.Common.Helpers;
using Siger.Middlelayer.Common.ModuleEnum;
using Siger.Middlelayer.Log;
using Siger.Middlelayer.Repository;
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;
using Siger.Middlelayer.Utility.ImportEntities;

namespace Siger.ApiConfig.Controller
{
    public class WorkingGroupController : BaseController
    {
        private readonly IWorkingGroupRepository _groupRepository;
        //private readonly IWorkingMachineSetRepository _machineSetRepository;
        private readonly ISigerProjectUserRepository _projectUserRepository;
        private readonly ISigerProjectSectionRepository _sectionRepository;
        private readonly ISigerProjectLevelRepository _sigerProjectLevel;
        private readonly ISigerProjectMachineAttributionRepository _attributionRepository;
        private readonly ISigerProjectLevelSectionRepository _sigerProjectLevelSection;
        private readonly IWorkingCalendarRepository _calendarRepository;
        private readonly ISigerProjectShiftRepository _projectShiftRepository;
        private readonly IWorkingRelationMachineRepository _workingRelationMachine;
        private readonly IWorkingRelationUserRepository _workingRelationUser;
        private readonly IUnitOfWork _unitOfWork;

        public WorkingGroupController(IWorkingGroupRepository groupRepository,
            ISigerProjectUserRepository projectUserRepository,
            ISigerProjectSectionRepository sectionRepository, ISigerProjectLevelRepository sigerProjectLevel,
            ISigerProjectMachineAttributionRepository attributionRepository, ISigerProjectLevelSectionRepository  sigerProjectLevelSection,
            IWorkingCalendarRepository calendarRepository, ISigerProjectShiftRepository projectShiftRepository,IWorkingRelationMachineRepository workingRelationMachine,IWorkingRelationUserRepository workingRelationUser, IUnitOfWork unitOfWork)
        {
            _groupRepository = groupRepository;
          
            _projectUserRepository = projectUserRepository;
            _sectionRepository = sectionRepository;
            _sigerProjectLevel = sigerProjectLevel;
            _attributionRepository = attributionRepository;
            _sigerProjectLevelSection = sigerProjectLevelSection;
            _calendarRepository = calendarRepository;
            _projectShiftRepository = projectShiftRepository;
            _workingRelationMachine = workingRelationMachine;
            _workingRelationUser = workingRelationUser;
            _unitOfWork = unitOfWork;
        }

        [HttpPost]
        public IActionResult GetWorkingGroupList([FromBody] RequestGetWorkingGroups request)
        {
            var data = _groupRepository.GetPagedCollectionResult(request, ProjectId);

            return new PagedObjectResult(data.Data, data.Total, request.page, request.pagesize);
        }

        [HttpGet]
        public IActionResult GetAllWorkGroup(int departid = 0)
        {
            var groups = _groupRepository.GetList(q => q.project_id == ProjectId && q.status == (int) RowState.Valid
                                                                                 && (departid == 0 ||
                                                                                     q.section_id == departid))
                .Select(m => new ResponseIdName
                {
                    id = m.id,
                    name = m.name
                });
            return new ObjectResult(groups.ToList());
        }

        [HttpGet]
        public IActionResult GetAllUsersByWorkGroup(int id)
        {
            var group = _groupRepository.Get(q =>
                q.id == id && q.status == (int) RowState.Valid && q.project_id == ProjectId);
            if (group == null)
            {
                throw new BadRequestException(CommonEnum.RecordNotFound);
            }

            if (!string.IsNullOrWhiteSpace(group.user_mids))
            {
                var userIds = group.user_mids.Split(',').ToList();
                var users = _projectUserRepository.GetList(q =>
                        userIds.Contains(q.mid.ToString()) && q.projectid == ProjectId &&
                        q.status == (int) RowState.Valid)
                    .Select(m => new ResponseIdName
                    {
                        id = m.mid,
                        name = m.name
                    }).ToList();
                return new ObjectResult(users);
            }

            return new ObjectResult(CommonEnum.Succefull);
        }

        [HttpPost]
        public IActionResult AddWorkingGroup([FromBody] RequestAddWorkingGroup request)
        {
            //不同部门下班组不能重名
            var isExist = _groupRepository.Get(q =>
                q.section_id == request.section_id.ToInt() && q.project_id == ProjectId && q.name == request.name &&
                q.status == (int) RowState.Valid);
            if (isExist != null)
            {
                throw new BadRequestException(RequestEnum.NameHasExist);
            }

            //同一个人只能在一个班组
            var userids = request.user_mids.Split(',');
            foreach (var userid in userids)
            {
                if (_groupRepository.IsExist(q =>
                    (q.user_mids + ",").Contains(userid + ",") && q.status == (int) RowState.Valid &&
                    q.project_id == ProjectId
                    && q.start_date <= DateTime.Now))
                {
                    throw new BadRequestException(RequestEnum.UserWorkGroupHasDuplicate);
                }
            }

            //实体检查
            var entity = new siger_project_working_group
            {
                name = request.name,
                section_id = request.section_id.ToInt(),
                user_mids = request.user_mids,
                interval = request.interval.ToInt(),
                shift_ids = request.shift_ids,
                start_date = request.start_date.ToDateTime(),
                creator_mid = UserId,
                project_id = ProjectId
            };

            _groupRepository.Insert(entity);
            if (_unitOfWork.Commit() > 0)
            {
                return new ObjectResult(CommonEnum.Succefull);
            }

            throw new BadRequestException(CommonEnum.Fail);
        }

        [HttpGet]
        public IActionResult GetWorkingMachine(int sectionId, int workinggroupId)
        {
            //var list = _machineSetRepository.GetList(q =>
            //    q.section_id == sectionId && q.workinggroup_id == workinggroupId && q.project_id == ProjectId);

            //var userIds = new List<int>();
            //var stationIds = new List<int>();
            //foreach (var set in list.ToList())
            //{
            //    if (!userIds.Contains(set.user_mid))
            //    {
            //        userIds.Add(set.user_mid);
            //    }

            //    if (!stationIds.Contains(set.station_id))
            //    {
            //        stationIds.Add(set.station_id);
            //    }
            //}

            //var response = new ResponseGetWorkingMachine
            //{
            //    user_mids = string.Join(',', userIds),
            //    machine_ids = string.Join(',', stationIds),
            //    section_id = sectionId,
            //    workgroup_id = workinggroupId
            //};
            var response = new ResponseGetWorkingMachine
            {
                machine_ids = "",
                user_mids = "",
                section_id = sectionId,
                workgroup_id = workinggroupId
            };

            var machineSet = _workingRelationUser.Get(f => f.projectid == ProjectId && f.section == sectionId && f.workgroup_id == workinggroupId && f.status == (int)RowState.Valid);
            response.machine_ids =machineSet!=null? string.Join(',', machineSet.stations):"";
            var userSet = _workingRelationMachine.Get(f => f.projectid == ProjectId && f.section == sectionId && f.workgroup_id == workinggroupId && f.status == (int)RowState.Valid);
            response.user_mids = userSet != null ? string.Join(',', userSet.employs) : "";
            return new ObjectResult(response);
        }

        [HttpPost]
        public async Task<IActionResult> SetWorkingMachine([FromBody] RequestSetWorkingMachine request)
        {
            //先按照部门和组别删除
            var sectionId = request.section_id.ToInt();
            var reqStationIds = request.machine_ids.Split(',').Distinct().ToList().ConvertAll(i => i.ToInt());
            var userIds = request.user_mids.Split(',').Distinct().ToList().ConvertAll(i => i.ToInt());

            var lastlevel = _sigerProjectLevel.GetList(f => f.projectid == ProjectId, "id");
            if (!lastlevel.Any())
            {
                throw new BadRequestException(ConfigEnum.UserLevelNull);
            }
            var lastLevelObj = lastlevel.FirstOrDefault();

            //1.设备与人员关系
            var relationMachinelst = _workingRelationMachine.GetList(f => f.projectid == ProjectId && f.section == sectionId && f.workgroup_id==request.workgroup_id.ToInt() && f.status == (int)RowState.Valid).ToList();
            foreach(var machine in relationMachinelst)
            {
                _workingRelationMachine.Delete(machine.id);
            }


            var machineIds = new List<int>();
            var errors = new List<string>();
            foreach (var station in reqStationIds)
            {
                var levelSection = _sigerProjectLevelSection.Get(f => f.projectid == ProjectId && f.id == station && f.status == (int)RowState.Valid);
                if (levelSection == null)
                {
                    throw new BadRequestException(ConfigEnum.UserLevelNull);
                }
                if (levelSection.levelid != lastLevelObj.id)
                {
                    //不是最后一级 ：工位跳过
                    continue;
                }

                var stationMachine = _attributionRepository.Get(f => f.station == station && f.attribution==1 && f.status == (int)RowState.Valid);

                if (stationMachine == null)
                {
                    var levelSetion = _sigerProjectLevelSection.Get(f => f.projectid == ProjectId && f.id == station && f.status == (int)RowState.Valid);
                    var opTitle = levelSetion != null ? levelSetion.title : station.ToString();
                    errors.Add($"{opTitle}: 未绑定设备");
                    continue;
                }
                machineIds.Add(stationMachine.machine);
                _workingRelationMachine.Insert(new siger_project_working_relation_machine
                {
                    projectid = ProjectId,
                    section = sectionId,
                    workgroup_id = request.workgroup_id.ToInt(),
                    machine = stationMachine.machine,
                    station=station,
                    employs= request.user_mids,
                    status=(int)RowState.Valid
                });
            }
            if (errors.Any())
            {
                return new ImportObjectResult((int)CommonEnum.Fail, string.Join(";", errors));
            }
            //2.人员 与设备关系
            var relationUserlst = _workingRelationUser.GetList(f => f.projectid == ProjectId && f.section == sectionId && f.workgroup_id == request.workgroup_id.ToInt() && f.status == (int)RowState.Valid).ToList();
            foreach (var relUser in relationUserlst)
            {
                _workingRelationUser.Delete(relUser.id);
            }
            foreach(var mid in userIds)
            {
                _workingRelationUser.Insert(new siger_project_working_relation_user
                {
                    projectid=ProjectId,
                    section=sectionId,
                    workgroup_id=request.workgroup_id.ToInt(),
                    employ=mid,
                    stations=request.machine_ids,
                    machines= string.Join(',', machineIds),
                    status=(int)RowState.Valid
                });
            }

            //var list = _machineSetRepository.GetList(q =>
            //    q.section_id == sectionId && q.workinggroup_id == request.workgroup_id.ToInt() &&
            //    q.project_id == ProjectId);
            //foreach (var sigerProjectWorkingMachineSet in list.ToList())
            //{
            //    _machineSetRepository.Delete(sigerProjectWorkingMachineSet.id);
            //}

            //var stations = _attributionRepository.GetList(q => reqStationIds.Contains(q.station) && q.projectid == ProjectId && q.status == (int)RowState.Valid);
            //foreach (var userId in userIds)
            //{
            //    foreach (var stationId in reqStationIds)
            //    {
            //        var station = stations.FirstOrDefault(q => q.station == stationId);
            //        if (station == null) continue;
            //        var entity = new siger_project_working_machine_set
            //        {
            //            section_id = sectionId,
            //            machine_id = station.machine,
            //            station_id = stationId,
            //            project_id = ProjectId,
            //            user_mid = userId,
            //            workinggroup_id = request.workgroup_id.ToInt()
            //        };
            //        _machineSetRepository.Insert(entity);
            //    }
            //}

            if (_unitOfWork.Commit() > 0)
            {
                if (await SetWorkingCalendar(reqStationIds, userIds, request.workgroup_id.ToInt()))
                {
                    return new ObjectResult(CommonEnum.Succefull);
                }
            }
            throw new BadRequestException(CommonEnum.Fail);
        }

        /// <summary>
        /// 设置工作日历 - 数据量大移到定时任务处理
        /// </summary>
        private async Task<bool> SetWorkingCalendar(List<int> stationIds, List<int> userMids, int workguoupId)
        {
            var workGroup = _groupRepository.Get(workguoupId);
            if (workGroup == null)
                return false;

            return await System.Threading.Tasks.Task.Run(() =>
            {

                var sets = _calendarRepository.GetList(q => q.project_id==ProjectId && q.working_group == workguoupId).ToList();
                foreach (var calendar in sets)
                {
                    _calendarRepository.Delete(calendar);
                }
                if (_unitOfWork.Commit() < 0)
                {
                    throw new BadRequestException(CommonEnum.Fail);
                }

                var startDate = workGroup.start_date;
                var endDate = DateTime.Now.ToString(ParameterConstant.MouthFirstDay).ToDateTime().AddMonths(1).AddDays(-1).Date;
                var shiftIds = workGroup.shift_ids.TrimEnd(',').Split(',').Select(x => x.ToInt()).ToList();
                foreach (var userId in userMids)
                {
                    DateTime dtDay;
                    var i = 0;
                    for (dtDay = startDate; dtDay.CompareTo(endDate) <= 0; dtDay = dtDay.AddDays(1).Date)
                    {
                        if (i == workGroup.interval)
                        {
                            i = 0;
                        }

                        var cal = new siger_project_working_calendar
                        {
                            user_mid = userId,
                            //machine_id = machineId,
                            date = dtDay.Date,
                            project_id = ProjectId,
                            shift_id = shiftIds[i],
                            working_group = workguoupId
                        };
                        _calendarRepository.Insert(cal);
                        i++;
                    }

                }
                if (_unitOfWork.Commit() > 0)
                    return true;
                else
                    return false;

            });

            //var machineIds = _attributionRepository.GetList(q => stationIds.Contains(q.station) && q.sparepart_id == 0
            //                                                && q.status == (int)RowState.Valid
            //                                                && q.projectid == ProjectId).ToList()
            //    .Select(m => m.machine).Distinct();
            //if (!machineIds.Any())
            //{
            //    return false;
            //}

            //var workGroup = _groupRepository.Get(workguoupId);
            //if (workGroup == null)
            //{
            //    return false;
            //}

            //return await System.Threading.Tasks.Task.Run(() =>
            //{
            //    foreach (var userId in userMids)
            //    {
            //        var sets = _calendarRepository.GetList(q => q.user_mid == userId && q.date.Date >= DateTime.Now.Date).ToList();
            //        foreach (var calendar in sets)
            //        {
            //            _calendarRepository.Delete(calendar);
            //        }
            //    }

            //    if (_unitOfWork.Commit() < 0)
            //    {
            //        throw new BadRequestException(CommonEnum.Fail);
            //    }

            //    var startDate = workGroup.start_date;
            //    var endDate = DateTime.Now.ToString(ParameterConstant.MouthFirstDay).ToDateTime().AddMonths(1).AddDays(-1).Date;
            //    var shiftIds = workGroup.shift_ids.TrimEnd(',').Split(',').Select(x => x.ToInt()).ToList();
            //    foreach (var userId in userMids)
            //    {
            //        foreach (var machineId in machineIds)
            //        {
            //            DateTime dtDay;
            //            var i = 0;
            //            for (dtDay = startDate; dtDay.CompareTo(endDate) <= 0; dtDay = dtDay.AddDays(1).Date)
            //            {
            //                if (i == workGroup.interval)
            //                {
            //                    i = 0;
            //                }

            //                var cal = new siger_project_working_calendar
            //                {
            //                    user_mid = userId,
            //                    //machine_id = machineId,
            //                    date = dtDay.Date,
            //                    project_id = ProjectId,
            //                    shift_id = shiftIds[i],
            //                    working_group = workguoupId
            //                };
            //                _calendarRepository.Insert(cal);
            //                i++;
            //            }
            //        }
            //    }

            //    if (_unitOfWork.Commit() < 0)
            //    {
            //        return false;
            //    }

            //    return true;
            //});
        }

        [HttpPost]
        public IActionResult DeleteWorkingGroup(int id)
        {

            var group = _groupRepository.Get(q => q.id == id && q.status == (int)RowState.Valid && q.project_id == ProjectId);
            if (group == null)
            {
                throw new BadRequestException(CommonEnum.RecordNotFound);
            }
            _groupRepository.Delete(group.id);
            var machinelst = _workingRelationMachine.GetList(f => f.projectid == ProjectId && f.workgroup_id == id).ToList();
            foreach(var m in machinelst)
            {
                _workingRelationMachine.Delete(m.id);
            }
            var userlst = _workingRelationUser.GetList(f => f.projectid == ProjectId && f.workgroup_id == id).ToList();
            foreach(var u in userlst)
            {
                _workingRelationUser.Delete(u.id);
            }

            var calenderLst = _calendarRepository.GetList(f => f.project_id == ProjectId && f.working_group == id).ToList();
            foreach(var cal in calenderLst)
            {
                _calendarRepository.Delete(cal.id);
            }
            //group.status = (int) RowState.Invalid;
            //_groupRepository.Update(group);

            ////删除设置
            //var list = _machineSetRepository.GetList(q => q.workinggroup_id == id && q.project_id == ProjectId && q.status == (int)RowState.Valid);
            //foreach (var set in list.ToList())
            //{
            //    _machineSetRepository.Delete(set);
            //}
            ////删除全部的排班
            //var userIds = group.user_mids.Split(',').ToList();
            //var clas = _calendarRepository.GetList(q => userIds.Contains(q.user_mid.ToString()) && q.project_id == ProjectId);
            //if (clas.Any())
            //{
            //    foreach (var calendar in clas)
            //    {
            //        _calendarRepository.Delete(calendar);
            //    }
            //}
            if (_unitOfWork.Commit() > 0)
            {
                return new ObjectResult(CommonEnum.Succefull);
            }
            throw new BadRequestException(CommonEnum.Fail);
        }

        [HttpGet]
        public IActionResult GetWorkingGroup(int id)
        {
            var group = _groupRepository.Get(q => q.id == id && q.status == (int)RowState.Valid && q.project_id == ProjectId);
            if (group == null)
            {
                throw new BadRequestException(CommonEnum.RecordNotFound);
            }
            var section = _sectionRepository.Get(q => q.id == group.section_id && q.status == (int)RowState.Valid);
            if (section == null)
            {
                throw new BadRequestException(RequestEnum.SectionNotFound);
            }

            var response = Mapper<siger_project_working_group, ResponseGetWorkingGroup>.Map(group);
            response.start_time = group.start_date.ToString(ParameterConstant.DateFormat);
            response.section_name = section.title;

            return new ObjectResult(response);
        }

        [HttpPost]
        public IActionResult UpdateWorkingGroup([FromBody]RequestUpdateWorkingGroup request)
        {
            var group = _groupRepository.Get(q => q.id == request.id && q.status == (int)RowState.Valid && q.project_id == ProjectId);
            if (group == null)
            {
                throw new BadRequestException(CommonEnum.RecordNotFound);
            }

            //不同部门下班组不能重名
            var isExist = _groupRepository.Get(q =>
                q.section_id == request.sectionid && q.project_id == ProjectId && q.name == request.name &&
                q.status == (int)RowState.Valid && q.id != request.id);
            if (isExist != null)
            {
                throw new BadRequestException(RequestEnum.NameHasExist);
            }

            group.name = request.name;
            group.user_mids = request.user_mids.TrimEnd(',');
            group.start_date = request.start_date.ToDateTime();

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

        [HttpGet]
        public IActionResult GetWokingGroupDate(string date)
        {
            var dt = date.ToDateTime() == DateTime.MinValue ? DateTime.Now : date.ToDateTime();
            var response = new List<ResponseDateList>();
            var days = DateTime.DaysInMonth(dt.Year, dt.Month);
            for (var i = 1; i <= days; i++)
            {
                var datemodel = new ResponseDateList
                {
                    day = i,
                    week = (int)DateTime.Parse(dt.Year + "-" + dt.Month + "-" + i).DayOfWeek
                };
                response.Add(datemodel);
            }
            return new ObjectResult(response);
        }

        [HttpPost]
        public IActionResult UpdateUserWokingGroup([FromBody]RequestUpdateUserWokingGroup request)
        {
            var dt = request.date.ToDateTime();
            var cals = _calendarRepository.GetList(q =>
                    q.user_mid == request.usermid && q.date.Date == dt.Date
                                                  && q.project_id == ProjectId && q.status == (int) RowState.Valid)
                .ToList();
            foreach (var cal in cals)
            {
                cal.shift_id = request.shiftid;
                _calendarRepository.Update(cal);
            }

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

        [HttpGet]
        public IActionResult GetSectionWokingGroup(int sectionId, string date, int page = PageIndex, int pagesize = PageSize, int toexcel = 0)
        {
            if (sectionId == 0)
            {
                throw new BadRequestException(RequestEnum.SectionIsEmpty);
            }
            var dt = date.ToDateTime() == DateTime.MinValue ? DateTime.Now : date.ToDateTime();
            var dtstart = dt.ToString(ParameterConstant.MouthFirstDay).ToDateTime();
            var dtend = DateTime.Parse(dt.ToString(ParameterConstant.MouthFirstDay)).AddMonths(1).AddDays(-1);

            var responses = new List<ResponseGetSectionWokingGroup>();
            var allusers = _projectUserRepository.GetUsersBySectionid(sectionId, ProjectId);
            var users = allusers.Skip((page - 1) * pagesize).Take(pagesize);
            var userids = users.Select(m => m.id);
            var cals = _calendarRepository.GetList(q =>
                userids.Contains(q.user_mid) && q.date >= dtstart && q.date <= dtend 
                && q.project_id == ProjectId && q.status == (int)RowState.Valid);
            var allshifts = _projectShiftRepository.GetList(q => q.projectid == ProjectId && q.status == (int) RowState.Valid);

            foreach (var projectUser in users)
            {
                var response = new ResponseGetSectionWokingGroup
                {
                    usermid = projectUser.id,
                    usergroupname = projectUser.usergrouptitle,
                    username = projectUser.name
                };

                var shifts = cals.Where(q => q.user_mid == projectUser.id);
                if (shifts.Any())
                {
                    for (var day = dtstart; day <= dtend; day = day.AddDays(1))
                    {
                        var shift = shifts.FirstOrDefault(q => q.date == day.Date);
                        if (shift != null)
                        {
                            var shiftname = allshifts.FirstOrDefault(q => q.id == shift.shift_id);
                            response.shifts.Add(new ResponseShiftinfo
                            {
                                shiftid = shift.shift_id,
                                shiftname = shiftname == null ? "" : shiftname.title,
                            });
                        }
                        else
                        {
                            response.shifts.Add(new ResponseShiftinfo
                            {
                                shiftid = 0,
                                shiftname = "",
                            });
                        }
                    }
                }
                responses.Add(response);
            }

            if (toexcel == 0)
            {
                return new PagedObjectResult(responses, allusers.Count(), page, pagesize);
            }

            return ExportWorkGroup(responses, dt);
        }

        [HttpGet]
        private IActionResult ExportWorkGroup(List<ResponseGetSectionWokingGroup> responses, DateTime dt)
        {
            var rootDir = FileSystemHelper.GetPhysicalFolders(FileSystemHelper.CommonFileSetting.PhysicalFolder, FileSystemHelper.ExportFileName);

            var temporaryFileName = $"schedule_{DateTime.Now:yyyyMMddHHmmss}.xlsx";
            var fileName = Path.Combine(rootDir, temporaryFileName);

            var helper = new EpPlusForWorkGroupHelper();
            try
            {
                var userList = new List<SectionWokingGroupList>();
                var index = 1;
                foreach (var projectUser in responses)
                {
                    var user = new SectionWokingGroupList
                    {
                        UserName = projectUser.username,
                        GroupName = projectUser.usergroupname,
                        Dates = projectUser.shifts.Select(m => m.shiftname).ToList()
                    };
                    userList.Add(user);
                    index++;
                }

                var columns = new List<string>
                {
                    "岗位",
                    "姓名"
                };
                var days = DateTime.DaysInMonth(dt.Year, dt.Month);
                for (var i = 1; i <= days; i++)
                {
                    var date = dt.Year + "-" + dt.Month + "-" + i;
                    var weekname = DateTimeHelper.GetWeekName((int) DateTime.Parse(date).DayOfWeek);
                    columns.Add(date + "(" + weekname + ")");
                }
                helper.GenerateExcel(userList, columns, fileName);
                return new ObjectResult($"{FileSystemHelper.CommonFileSetting.RequestPath}/{FileSystemHelper.ExportFileName}/{temporaryFileName}");
            }
            catch (Exception e)
            {
                Logger.WriteLineError("ExportWorkGroup failed, error: " + e.Message);
                throw new BadRequestException(RequestEnum.ExportFailed);
            }
            finally
            {
                helper.Dispose();
            }
        }
    }
}