using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using FluentValidation.AspNetCore;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.StaticFiles;
using Performance.DtoModels;
using Performance.EntityModels;
using Performance.Infrastructure;
using Performance.Infrastructure.Models;
using Performance.Services;

namespace Performance.Api.Controllers
{
    [Route("api")]
    [ApiController]
    public class PersonController : Controller
    {
        private readonly PersonService personService;
        private readonly ClaimService claimService;

        public PersonController(PersonService personService, ClaimService claimService)
        {
            this.personService = personService;
            this.claimService = claimService;
        }

        /// <summary>
        /// 获取所有员工记录
        /// </summary>
        /// <param name="allotId"></param>
        /// <param name="request"></param>
        /// <returns></returns>
        [Route("person/list/{allotId}")]
        [HttpPost]
        public ApiResponse GetPersons([FromRoute] int allotId, [FromBody] PersonParamsRequest request)
        {
            var list = personService.GetPersons(allotId, claimService.GetUserId(), request)
                ?? new PageList<per_employee>(new List<per_employee>(), 0, request.PageNumber, request.PageSize);
            return new ApiResponse(ResponseType.OK, new
            {
                list.CurrentPage,
                list.TotalPages,
                list.PageSize,
                list.TotalCount,
                list
            });
        }

        /// <summary>
        /// 新增员工信息
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [Route("person/add")]
        [HttpPost]
        public ApiResponse CreatePerson([FromBody] PerEmployeeResponse request)
        {
            request.CreateUser = claimService.GetUserId();
            var employeee = personService.CreatePerson(request);
            return employeee.Id > 0 ? new ApiResponse(ResponseType.OK, "添加成功！", employeee)
                : new ApiResponse(ResponseType.Fail, "添加失败！");
        }

        /// <summary>
        /// 修改员工信息
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [Route("person/edit")]
        [HttpPost]
        public ApiResponse UpdatePerson([FromBody] PerEmployeeResponse request)
        {
            var result = personService.UpdatePerson(request);
            return result ? new ApiResponse(ResponseType.OK, "修改成功！")
                : new ApiResponse(ResponseType.OK, "修改失败！");
        }

        /// <summary>
        /// 删除员工
        /// </summary>
        /// <param name="employeeId"></param>
        /// <returns></returns>
        [Route("person/delete/{employeeId}")]
        [HttpPost]
        public ApiResponse DeletePerson(int employeeId)
        {
            var result = personService.DeletePerson(employeeId);
            return result ? new ApiResponse(ResponseType.OK, "删除成功！")
                : new ApiResponse(ResponseType.OK, "删除失败！");
        }

        /// <summary>
        /// 下载当前测算表
        /// </summary>
        /// <returns></returns>
        [Route("person/list/download/{allotId}")]
        [HttpPost]
        public IActionResult DownloadCurrentCalculationTable([FromRoute] int allotId)
        {
            var filepath = personService.GetPersonDictFile(allotId, claimService.GetUserId());
            if (!FileHelper.IsExistFile(filepath))
                throw new PerformanceException("获取人员字典失败");

            var memoryStream = new MemoryStream();
            using (var stream = new FileStream(filepath, FileMode.Open))
            {
                stream.CopyToAsync(memoryStream).Wait();
            }
            memoryStream.Seek(0, SeekOrigin.Begin);
            var provider = new FileExtensionContentTypeProvider();
            FileInfo fileInfo = new FileInfo(filepath);
            var memi = provider.Mappings[".xlsx"];
            return File(memoryStream, memi, Path.GetFileName(fileInfo.Name));
        }

        /// <summary>
        /// 获取所有科室记录
        /// </summary>
        /// <param name="hospitalId"></param>
        /// <returns></returns>
        [Route("deptdic/list/{hospitalId}")]
        [HttpPost]
        public ApiResponse GetDepartments(int hospitalId)
        {
            var list = personService.GetDepartments(hospitalId);
            return new ApiResponse(ResponseType.OK, list);
        }

        /// <summary>
        /// 新增科室信息
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [Route("deptdic/add")]
        [HttpPost]
        public ApiResponse CreateDeptDic([FromBody] per_dept_dic request)
        {
            if (string.IsNullOrEmpty(request.Department) || string.IsNullOrEmpty(request.HISDeptName))
                return new ApiResponse(ResponseType.ParameterError, "标准科室，系统科室不可为空！");

            request.CreateUser = claimService.GetUserId();
            var employeee = personService.CreateDeptDic(request);
            return employeee.Id > 0 ? new ApiResponse(ResponseType.OK, "添加成功！", employeee)
                : new ApiResponse(ResponseType.Fail, "添加失败！");
        }

        /// <summary>
        /// 修改科室信息
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [Route("deptdic/edit")]
        [HttpPost]
        public ApiResponse UpdateDeptDic([FromBody] DeptdicResponse request)
        {
            if (string.IsNullOrEmpty(request.Department) || string.IsNullOrEmpty(request.HISDeptName))
                return new ApiResponse(ResponseType.ParameterError, "标准科室，系统科室不可为空！");

            var result = personService.UpdateDeptDic(request);
            return result ? new ApiResponse(ResponseType.OK, "修改成功！")
                : new ApiResponse(ResponseType.OK, "修改失败！");
        }

        /// <summary>
        /// 删除科室
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [Route("deptdic/delete")]
        [HttpPost]
        public ApiResponse DeleteDeptDic([FromBody] DeptdicResponse request)
        {
            var result = personService.DeleteDeptDic(request);
            return result ? new ApiResponse(ResponseType.OK, "删除成功！")
                : new ApiResponse(ResponseType.OK, "删除失败！");
        }

        /// <summary>
        /// 系统/标准科室字典
        /// </summary>
        /// <param name="hospitalId">医院Id</param>
        /// <param name="type">1系统科室 2标准科室 3核算单元 4行政后勤 5特殊核算组</param>
        /// <returns></returns>
        [Route("deptdic/{hospitalId}/dict/{type}")]
        [HttpPost]
        public ApiResponse DeptDics(int hospitalId, int type)
        {
            if (!new int[] { 1, 2, 3, 4, 5 }.Contains(type))
                return new ApiResponse(ResponseType.ParameterError, "参数错误！");

            var result = personService.DeptDics(hospitalId, type);
            return new ApiResponse(ResponseType.OK, result);
        }

        /// <summary>
        /// 科室工作量详情
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Route("dept/workdetail")]
        public ApiResponse DeptWorkloadDetail([CustomizeValidator(RuleSet = "Select"), FromBody] WorkDetailRequest request)
        {
            var data = personService.DeptWorkloadDetail(request, claimService.GetUserId());
            return new ApiResponse(ResponseType.OK, data);
        }

        /// <summary>
        /// 门诊开单收入详情
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Route("dept/incomedetail")]
        public ApiResponse DeptIncomeDetail([CustomizeValidator(RuleSet = "Select"), FromBody] WorkDetailRequest request)
        {
            var data = personService.DeptIncomeDetail(request, claimService.GetUserId());
            return new ApiResponse(ResponseType.OK, data);
        }

        /// <summary>
        /// 批量人员字典表头
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Route("person/GetBatchPersonStructrue/{hospitalId}")]
        public ApiResponse GetBatchPersonStructrue(int hospitalId)
        {
            var result = personService.GetBatchPersonStructrue(hospitalId);
            return new ApiResponse(ResponseType.OK, result);
        }

        /// <summary>
        /// 批量添加人员信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Route("person/{allotId}/BathSavePerson/{hospitalId}")]
        public ApiResponse BathSavePerson(int allotId, int hospitalId, SaveCollectData request)
        {
            var result = personService.BathSavePerson(allotId, hospitalId, request);
            if (result)
                return new ApiResponse(ResponseType.OK);
            else
                return new ApiResponse(ResponseType.Error, "出勤天数或预留比例格式错误");
        }

        /// <summary>
        /// 批量科室字典表头
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Route("dept/GetDeptStructrue/{hospitalId}")]
        public ApiResponse GetDeptStructrue(int hospitalId)
        {
            var result = personService.GetDepartmentHands(hospitalId);
            return new ApiResponse(ResponseType.OK, result);
        }

        /// <summary>
        /// 批量添加科室信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Route("dept/SaveDeptHands/{hospitalId}")]
        public ApiResponse SaveDeptHands(int hospitalId, SaveCollectData request)
        {
            personService.SaveDeptDicHands(hospitalId, request);
            return new ApiResponse(ResponseType.OK);
        }

        /// <summary>
        /// 重新加载人员字典
        /// </summary>
        /// <param name="hospitalId"></param>
        /// <param name="allotId"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("peson/{hospitalId}/reloadPersonnel/{allotId}")]
        public ApiResponse ReloadPersonnel(int hospitalId, int allotId)
        {
            var result = personService.ReloadPersonnel(hospitalId, allotId);
            if (result)
                return new ApiResponse(ResponseType.OK, result);
            else
                return new ApiResponse(ResponseType.Error, result);
        }
    }
}
