using System;
using System.Collections.Generic;
using System.ComponentModel;
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;
        private readonly DapperService dapperService;

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

        /// <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="allotId">绩效月ID</param>
        /// <param name="personnelNumber">工号</param>
        /// <param name="personnelName">姓名</param>
        /// <param name="unitType">核算组别</param>
        /// <param name="accountingUnit">核算单元</param>
        /// <param name="searchText">多字段查询；支持“工号/姓名/核算组别/核算单元”</param>
        /// <param name="pageIndex">页码 默认1</param>
        /// <param name="pageSize">行数 默认</param>
        /// <returns></returns>
        [Route("employee/list")]
        [HttpPost]
        public ApiResponse GetEmployee([FromQuery] int allotId,
                                       [FromQuery, DefaultValue("")] string personnelNumber,
                                       [FromQuery, DefaultValue("")] string personnelName,
                                       [FromQuery, DefaultValue("")] string unitType,
                                       [FromQuery, DefaultValue("")] string accountingUnit,
                                       [FromQuery, DefaultValue("")] string searchText,
                                       [FromQuery, DefaultValue(1)] int pageIndex,
                                       [FromQuery, DefaultValue(20)] int pageSize)
        {
            var list = personService.GetEmployee(allotId, personnelNumber, personnelName, unitType, accountingUnit, searchText, pageIndex, 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();
            return personService.CreatePerson(request);
        }

        /// <summary>
        /// 修改员工信息
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [Route("person/edit")]
        [HttpPost]
        public ApiResponse UpdatePerson([FromBody] PerEmployeeResponse request)
        {
            return personService.UpdatePerson(request);
        }

        /// <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>
        /// <param name="allotId"></param>
        /// <returns></returns>
        [Route("person/deleteall/{allotId}")]
        [HttpPost]
        public ApiResponse DeleteAllPerson(int allotId)
        {
            var result = personService.DeleteAllPerson(allotId);
            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="allotId"></param>
        /// <returns></returns>
        [Route("deptdic/list/{allotId}")]
        [HttpPost]
        public ApiResponse GetDepartments(int allotId)
        {
            var list = dapperService.GetDepartments(allotId);
            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="allotId">allotId</param>
        /// <param name="type">1系统科室 2标准科室 3核算单元 4行政后勤 5特殊核算组</param>
        /// <returns></returns>
        [Route("deptdic/{allotId}/dict/{type}")]
        [HttpPost]
        public ApiResponse DeptDics(int allotId, int type)
        {
            if (!new int[] { 1, 2, 3, 4, 5 }.Contains(type))
                return new ApiResponse(ResponseType.ParameterError, "参数错误！");

            var result = personService.DeptDics(allotId, 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/{allotId}")]
        public ApiResponse GetBatchPersonStructrue(int allotId)
        {
            var result = personService.GetBatchPersonStructrue(allotId);
            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)
        {
            return personService.BathSavePerson(allotId, hospitalId, request);
        }

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

        /// <summary>
        /// 批量添加科室信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Route("dept/SaveDeptHands/{allotId}")]
        public ApiResponse SaveDeptHands(int allotId, SaveCollectData request)
        {
            personService.SaveDeptDicHands(allotId, 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);
        }
    }
}
