using FluentValidation.AspNetCore;
using Hangfire;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Internal;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Performance.DtoModels;
using Performance.DtoModels.AppSettings;
using Performance.EntityModels;
using Performance.Infrastructure;
using Performance.Services;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;

// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace Performance.Api.Controllers
{
    /// <summary>
    /// 科室二次分配
    /// </summary>
    [Route("api/[controller]")]
    public class AgainAllotController : Controller
    {
        private AgainAllotService againAllotService;
        private RoleService roleService;
        private ComputeService computeService;
        private ClaimService claimService;
        private AllotService allotService;
        private IHostingEnvironment env;
        private ConfigService configService;
        private Application application;
        public AgainAllotController(AgainAllotService againAllotService,
              RoleService roleService,
             ClaimService claimService,
             AllotService allotService,
             IHostingEnvironment env,
             ConfigService configService,
             ComputeService computeService,
             IOptions<Application> options)
        {
            this.againAllotService = againAllotService;
            this.roleService = roleService;
            this.claimService = claimService;
            this.allotService = allotService;
            this.env = env;
            this.configService = configService;
            this.computeService = computeService;
            this.application = options.Value;
        }

        /// <summary>
        /// 返回当前用户医院下绩效列表
        /// </summary>
        /// <returns></returns>
        [Route("allotlist")]
        [HttpPost]
        public ApiResponse AllotList()
        {
            var userId = claimService.GetUserId();
            var list = againAllotService.GetAllotList(userId);
            return new ApiResponse(ResponseType.OK, list);
        }

        /// <summary>
        /// 上传文件
        /// </summary>
        /// <param name="form"></param>
        /// <returns></returns>
        [Route("import")]
        [HttpPost]
        public ApiResponse Import([FromForm] IFormCollection form)
        {
            var againid = form.ToDictionary().GetValue("againid", 0);
            if (againid <= 0)
                return new ApiResponse(ResponseType.Fail, "参数错误", "againid无效");

            var file = ((FormFileCollection)form.Files).FirstOrDefault();
            if (file == null)
                return new ApiResponse(ResponseType.Fail, "参数错误", "文件无效");

            var again = againAllotService.GetAgainallot(againid);
            if (again == null)
                return new ApiResponse(ResponseType.Fail, "二次绩效记录不存在");
            var allot = allotService.GetAllot(again.AllotID.Value);
            if (allot == null)
                return new ApiResponse(ResponseType.Fail, "一次绩效记录不存在");

            var name = FileHelper.GetFileNameNoExtension(file.FileName) + DateTime.Now.ToString("yyyyMMddHHmmssfff");
            var ext = FileHelper.GetExtension(file.FileName);
            var dpath = Path.Combine(env.ContentRootPath, "Files", $"{allot.HospitalId}", $"{allot.Year}{allot.Month.ToString().PadLeft(2, '0')}");
            FileHelper.CreateDirectory(dpath);

            var path = Path.Combine(dpath, $"{name}{ext}");

            using (var stream = file.OpenReadStream())
            {
                byte[] bytes = new byte[stream.Length];
                stream.Read(bytes, 0, bytes.Length);
                if (!FileHelper.CreateFile(path, bytes))
                    return new ApiResponse(ResponseType.Fail, $"{file.FileName}上传失败");
                allot.Path = path;
                allot.Remark = EnumHelper.GetDescription(AllotStates.FileUploaded);

                if (!againAllotService.Update(allot, againid))
                    return new ApiResponse(ResponseType.Fail, $"{file.FileName}上传成功，修改状态失败");
                configService.ClearAgain(againid);
            }

            return new ApiResponse(ResponseType.OK);
        }

        /// <summary>
        /// 查看科室绩效
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [Route("departmentdetail")]
        [HttpPost]
        public ApiResponse DepartmentDetail([CustomizeValidator(RuleSet = "Generate"), FromBody]AgainAllotRequest request)
        {
            var userId = claimService.GetUserId();
            var roles = roleService.GetUserRole(userId);
            var department = claimService.GetUserClaim(JwtClaimTypes.Department);

            var again = againAllotService.GetAgainallot(request.AgainAllotID);
            if (again == null)
                return new ApiResponse(ResponseType.Fail, "当前二次绩效ID无效");
            if (roles.First().Type == application.DirectorRole)
            {
                var detail = computeService.GetDepartmentDetail(again.AllotID.Value, department, 1);
                return new ApiResponse(ResponseType.OK, detail);
            }
            else if (roles.First().Type == application.NurseRole)
            {
                var detail = computeService.GetDepartmentDetail(again.AllotID.Value, department, 2);
                return new ApiResponse(ResponseType.OK, detail);
            }
            return new ApiResponse(ResponseType.Fail, "当前用户角色无法识别");
        }

        /// <summary>
        /// 生成绩效
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [Route("generate")]
        [HttpPost]
        public ApiResponse Generate([CustomizeValidator(RuleSet = "Generate"), FromBody]AgainAllotRequest request)
        {
            var userId = claimService.GetUserId();
            var department = claimService.GetUserClaim(JwtClaimTypes.Department);
            var result = againAllotService.Generate(request, userId, department);
            return new ApiResponse(ResponseType.OK);
        }

        /// <summary>
        /// 查看绩效详情
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [Route("detail")]
        [HttpPost]
        public ApiResponse Detail([CustomizeValidator(RuleSet = "Generate"), FromBody]AgainAllotRequest request)
        {
            var result = againAllotService.Detail(request);
            return new ApiResponse(ResponseType.OK, new { result.AgainSituation, result.SheetExport });
        }
    }
}
