using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore.Internal;
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.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 WorkingCostController : BaseController
    {
        private readonly IUnitOfWork _unitOfWork;
        private readonly ISigerProjectWorkingCostRepository _projectWorkingCostRepository;
        private readonly ISigerProjectSectionRepository _projectSectionRepository;
        private readonly ISigerProjectUserGroupRepository _userGroupRepository;

        public WorkingCostController(IUnitOfWork unitOfWork, ISigerProjectWorkingCostRepository projectWorkingCostRepository,
            ISigerProjectSectionRepository projectSectionRepository, ISigerProjectUserGroupRepository userGroupRepository)
        {
            _unitOfWork = unitOfWork;
            _projectWorkingCostRepository = projectWorkingCostRepository;
            _projectSectionRepository = projectSectionRepository;
            _userGroupRepository = userGroupRepository;
        }
        /// <summary>
        /// 获取工时费列表
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        [ProducesResponseType(typeof(RequestSearchWorkingCost), 200)]
        public IActionResult GetData([FromBody]RequestSearchWorkingCost request)
        {
            var data = _projectWorkingCostRepository.GetData(request, ProjectId);
            return new PagedObjectResult(data.Data, data.Total, request.page, request.pagesize);
        }
        /// <summary>
        /// 修改添加工时费信息
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [ProducesResponseType(typeof(RequestAddWorkingCost), 200)]
        [HttpPost]
        public IActionResult SetData([FromBody]RequestAddWorkingCost request)
        {
            if (request.id == 0)
            {
                if (_projectWorkingCostRepository.Get(f => f.projectid == ProjectId && f.status != 0 && f.usergroup_id == request.usergroup_id) != null)
                {
                    throw new BadRequestException(CommonEnum.RecordExits);
                }
                _projectWorkingCostRepository.Insert(new siger_project_working_cost
                {
                    create_time = DateTime.Now,
                    usergroup_id = request.usergroup_id,
                    creator = UserId,
                    editor = UserId,
                    projectid = ProjectId,
                    complex_id = request.complex_id,
                    complex_name = request.complex_name,
                    work_cost = request.work_cost
                });
            }
            else
            {
                var model = _projectWorkingCostRepository.Get(f => f.projectid == ProjectId && f.status != 0 && f.id == request.id);
                if (model == null)
                {
                    throw new BadRequestException(CommonEnum.NoData);
                }
                model.editor = UserId;
                model.complex_id = request.complex_id;
                model.complex_name = request.complex_name;
                model.work_cost = request.work_cost;
                model.usergroup_id = request.usergroup_id;
                _projectWorkingCostRepository.Update(model);
            }
            if (_unitOfWork.Commit() > 0)
            {
                return new ObjectResult(CommonEnum.Succefull);
            }
            throw new BadRequestException(CommonEnum.Fail);
        }
        /// <summary>
        /// 删除工时费信息
        /// </summary>
        /// <param name="ids">要删除的ids</param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult DelData(string ids)
        {
            var idList = ids.Split(',');
            if (!idList.Any())
            {
                throw new BadRequestException(CommonEnum.NoData);
            }
            foreach (var id in idList)
            {
                var model = _projectWorkingCostRepository.Get(f => f.projectid == ProjectId && f.status != 0 && f.id == id.ToInt());
                if (model == null)
                {
                    throw new BadRequestException(CommonEnum.NoData);
                }
                model.status = (int)RowState.Invalid;
                _projectWorkingCostRepository.Update(model);
            }
            if (_unitOfWork.Commit() > 0)
            {
                return new ObjectResult(CommonEnum.Succefull);
            }
            throw new BadRequestException(CommonEnum.Fail);
        }

        [ProducesResponseType(typeof(RequestAddWorkingCost), 200)]
        [HttpPost]
        public IActionResult ExportData([FromBody] RequestSearchWorkingCost request)
        {
            var data = _projectWorkingCostRepository.GetData(request, ProjectId);
          
            var rootDir = FileSystemHelper.GetPhysicalFolders(FileSystemHelper.CommonFileSetting.PhysicalFolder, FileSystemHelper.ExportFileName);
            var list = data.Data;
            if (!list.Any())
            {
                throw new BadRequestException(CommonEnum.RecordNotFound);
            }
            var dataList = Mapper<ResponseSearchWorkingCost, ImportWorkingCost>.MapList(list);
            var temporaryFileName = $"WorkingCost_{DateTime.Now:yyyyMMddHHmmss}.xlsx";
            var fileName = Path.Combine(rootDir, temporaryFileName);
            var helper = new EpPlusExcelHelper<ImportWorkingCost>();
            try
            {
                helper.GenerateExcel(dataList, fileName);
                return new ObjectResult($"{FileSystemHelper.CommonFileSetting.RequestPath}/{FileSystemHelper.ExportFileName}/{temporaryFileName}");
            }
            catch (Exception e)
            {
                Logger.WriteLineError("Export WorkingCost failed, error: " + e.Message);
                throw new BadRequestException(RequestEnum.ExportFailed);
            }
            finally
            {
                helper.Dispose();
            }
        }
        /// <summary>
        /// 获取维修部门岗位
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetUserGroup()
        {
            var list = _projectSectionRepository.GetList(q => q.type == 2 && q.projectid == ProjectId && q.status == (int)RowState.Valid).Select(s => s.id).ToList();
            if (list.Any())
            {
                return new ObjectResult(_userGroupRepository.GetList(f => list.Contains(f.sectionid)));
            }
            else
            {
                return new ObjectResult(new List<siger_project_usergroup>());
            }
        }
    }
}