using FluentValidation.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.StaticFiles;
using Newtonsoft.Json;
using Performance.DtoModels;
using Performance.DtoModels.Request;
using Performance.DtoModels.Response;
using Performance.EntityModels;
using Performance.EntityModels.Entity;
using Performance.Infrastructure;
using Performance.Services;
using Performance.Services.ExtractExcelService;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

namespace Performance.Api.Controllers
{
    [Route("api/[controller]")]
    public class EmployeeController : Controller
    {
        private EmployeeService employeeService;
        private AllotService allotService;
        private ClaimService claim;
        private IWebHostEnvironment evn;
        private readonly RoleService roleService;
        private readonly UserService userService;

        public EmployeeController(EmployeeService employeeService,
            AllotService allotService,
            ClaimService claim,
            IWebHostEnvironment evn,
            RoleService roleService,
            UserService userService)
        {
            this.employeeService = employeeService;
            this.allotService = allotService;
            this.claim = claim;
            this.evn = evn;
            this.roleService = roleService;
            this.userService = userService;
        }

        /// <summary>
        /// 获取人员列表
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [Route("getlist")]
        [HttpPost]
        public ApiResponse GetEmployeeList([CustomizeValidator(RuleSet = "Select"), FromBody] EmployeeRequest request)
        {
            var employee = employeeService.GetEmployeeList(request.AllotID, claim.GetUserId());
            return new ApiResponse(ResponseType.OK, "ok", employee);
        }

        /// <summary>
        /// 新增人员
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [Route("insert")]
        [HttpPost]
        public ApiResponse Insert([CustomizeValidator(RuleSet = "Insert"), FromBody] EmployeeRequest request)
        {
            var employee = employeeService.Insert(request);
            return new ApiResponse(ResponseType.OK, "ok", employee);
        }

        /// <summary>
        /// 修改人员
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [Route("update")]
        [HttpPost]
        public ApiResponse Update([CustomizeValidator(RuleSet = "Update"), FromBody] EmployeeRequest request)
        {
            var employee = employeeService.Update(request);
            return new ApiResponse(ResponseType.OK, "ok", employee);
        }

        /// <summary>
        /// 删除人员
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [Route("delete")]
        [HttpPost]
        public ApiResponse Delete([CustomizeValidator(RuleSet = "Delete"), FromBody] EmployeeRequest request)
        {
            if (!employeeService.Delete(request))
                return new ApiResponse(ResponseType.Fail);
            return new ApiResponse(ResponseType.OK);
        }

        /// <summary>
        /// 获取临床人员列表
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [Route("clinic/getlist")]
        [HttpPost]
        public ApiResponse GetEmployeeClinicList([FromBody] im_employee_clinic request)
        {
            //if ((request.AllotID ?? 0) == 0)
            //    return new ApiResponse(ResponseType.ParameterError, "参数AllotId无效！");

            var employee = employeeService.GetEmployeeClinicList(request.AllotID, claim.GetUserId());
            return new ApiResponse(ResponseType.OK, "ok", employee);
        }

        /// <summary>
        /// 新增临床人员
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [Route("clinic/insert")]
        [HttpPost]
        public ApiResponse InsertClinic([FromBody] im_employee_clinic request)
        {
            if ((request.AllotID ?? 0) == 0)
                return new ApiResponse(ResponseType.ParameterError, "参数AllotId无效！");

            if (string.IsNullOrEmpty(request.AccountingUnit))
                return new ApiResponse(ResponseType.ParameterError, "参数AccountingUnit无效！");

            if (string.IsNullOrEmpty(request.DoctorName))
                return new ApiResponse(ResponseType.ParameterError, "参数DoctorName无效！");

            var employee = employeeService.InsertClinic(request);
            return new ApiResponse(ResponseType.OK, "ok", employee);
        }

        /// <summary>
        /// 修改临床人员
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [Route("clinic/update")]
        [HttpPost]
        public ApiResponse UpdateClinic([FromBody] im_employee_clinic request)
        {
            if ((request.AllotID ?? 0) == 0)
                return new ApiResponse(ResponseType.ParameterError, "参数AllotId无效！");

            if (string.IsNullOrEmpty(request.AccountingUnit))
                return new ApiResponse(ResponseType.ParameterError, "参数AccountingUnit无效！");

            if (string.IsNullOrEmpty(request.DoctorName))
                return new ApiResponse(ResponseType.ParameterError, "参数DoctorName无效！");
            var employee = employeeService.UpdateClinic(request);
            return new ApiResponse(ResponseType.OK, "ok", employee);
        }

        /// <summary>
        /// 删除临床人员
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [Route("clinic/delete")]
        [HttpPost]
        public ApiResponse DeleteClinic([FromBody] im_employee_clinic request)
        {
            if (request.ID == 0)
                return new ApiResponse(ResponseType.ParameterError, "参数ID无效！");

            if (!employeeService.DeleteClinic(request))
                return new ApiResponse(ResponseType.Fail);
            return new ApiResponse(ResponseType.OK);
        }

        #region 行政后勤

        /// <summary>
        /// 获取临床人员列表
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [Route("logistics/getlist")]
        [HttpPost]
        public ApiResponse GetEmployeeLogisticsList([FromBody] im_employee_clinic request)
        {
            //if ((request.AllotID ?? 0) == 0)
            //    return new ApiResponse(ResponseType.ParameterError, "参数AllotId无效！");

            var employee = employeeService.GetEmployeeLogisticsList(request.AllotID, claim.GetUserId());
            return new ApiResponse(ResponseType.OK, "ok", employee);
        }

        /// <summary>
        /// 新增临床人员
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [Route("logistics/insert")]
        [HttpPost]
        public ApiResponse InsertLogistics([FromBody] im_employee_logistics request)
        {
            if ((request.AllotID ?? 0) == 0)
                return new ApiResponse(ResponseType.ParameterError, "参数AllotId无效！");

            if (string.IsNullOrEmpty(request.AccountingUnit))
                return new ApiResponse(ResponseType.ParameterError, "参数AccountingUnit无效！");

            if (string.IsNullOrEmpty(request.DoctorName))
                return new ApiResponse(ResponseType.ParameterError, "参数DoctorName无效！");

            var employee = employeeService.InsertLogistics(request);
            return new ApiResponse(ResponseType.OK, "ok", employee);
        }

        /// <summary>
        /// 修改临床人员
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [Route("logistics/update")]
        [HttpPost]
        public ApiResponse UpdateLogistics([FromBody] im_employee_logistics request)
        {
            if ((request.AllotID ?? 0) == 0)
                return new ApiResponse(ResponseType.ParameterError, "参数AllotId无效！");

            if (string.IsNullOrEmpty(request.AccountingUnit))
                return new ApiResponse(ResponseType.ParameterError, "参数AccountingUnit无效！");

            if (string.IsNullOrEmpty(request.DoctorName))
                return new ApiResponse(ResponseType.ParameterError, "参数DoctorName无效！");
            var employee = employeeService.UpdateLogistics(request);
            return new ApiResponse(ResponseType.OK, "ok", employee);
        }

        /// <summary>
        /// 删除临床人员
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [Route("logistics/delete")]
        [HttpPost]
        public ApiResponse DeleteLogistics([FromBody] im_employee_clinic request)
        {
            if (request.ID == 0)
                return new ApiResponse(ResponseType.ParameterError, "参数ID无效！");

            if (!employeeService.DeleteLogistics(request))
                return new ApiResponse(ResponseType.Fail);
            return new ApiResponse(ResponseType.OK);
        }

        #endregion 行政后勤

        /// <summary>
        /// 人事科修改参数后提交
        /// </summary>
        /// <param name="allotid"></param>
        /// <returns></returns>
        [Route("manage/audit/{allotid}")]
        [HttpPost]
        public ApiResponse Audit(int allotid)
        {
            var result = employeeService.Audit(allotid);
            return result ? new ApiResponse(ResponseType.OK, "提交成功") : new ApiResponse(ResponseType.Fail, "提交失败");
        }


        #region 医院其他绩效
        /// <summary>
        /// 获取医院其他绩效列表
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [Route("apr/getlist")]
        [HttpPost]
        public ApiResponse GetAprList([FromBody] AprAmountAuditRequest request)
        {
            if (request.AllotId == 0)
                return new ApiResponse(ResponseType.ParameterError, "参数AllotId无效！");

            var employee = employeeService.GetAprByTypeInDepartment(request.AllotId, request.TypeInDepartment, request.CreateDate);
            return new ApiResponse(ResponseType.OK, "ok", employee);
        }

        /// <summary>
        /// 医院其他绩效审核
        /// </summary>
        /// <param name="isAudit">0 其他绩效列表 1 审核列表</param>
        /// <param name="request"></param>
        /// <returns></returns>
        [Route("apr/getdeptlist/{isAudit}")]
        [HttpPost]
        public ApiResponse GetAprGroupList([FromRoute] int isAudit, [FromBody] AllotIdRequest request)
        {
            if (request.AllotId == 0)
                return new ApiResponse(ResponseType.ParameterError, "参数AllotId无效！");

            var result = employeeService.GetAprList(request.AllotId, claim.GetUserId(), isAudit);
            return new ApiResponse(ResponseType.OK, "ok", result);
        }

        /// <summary>
        /// 医院其他绩效提交
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [Route("apr/submitdeptlist")]
        [HttpPost]
        public ApiResponse SubmitDeptList([FromBody] SubmitAmountRequest request)
        {
            if (employeeService.SubmitDeptList(request))
                return new ApiResponse(ResponseType.OK, "提交成功");
            else
                return new ApiResponse(ResponseType.Fail, "提交失败");
        }
        /// <summary>
        /// 医院其他绩效审核详情
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [Route("apr/getdeptdetail")]
        [HttpPost]
        public ApiResponse GetAprDetail([FromBody] AprAmountAuditRequest request)
        {
            if (request.AllotId == 0)
                return new ApiResponse(ResponseType.ParameterError, "参数AllotId无效！");

            var employee = employeeService.GetAprList(request.AllotId, request.TypeInDepartment, date: request.CreateDate);
            if (employee == null || !employee.Any())
                return new ApiResponse(ResponseType.OK, "ok", employee);

            var result = employee
                .GroupBy(t => new { t.AccountingUnit, t.PersonnelNumber, t.DoctorName })
                .Select(t => new
                {
                    PersonnelNumber = t.Key.PersonnelNumber,
                    DoctorName = t.Key.DoctorName,
                    AccountingUnit = t.Key.AccountingUnit,
                    Status = t.Any(s => s.Status == 2) ? 2 : t.Any(s => s.Status == 4) ? 4 : t.FirstOrDefault().Status,
                    Detail = t.GroupBy(group => group.PerforType).Select(s => new
                    {
                        Title = string.IsNullOrEmpty(s.Key) ? "未知" : s.Key,
                        Value = s.Sum(sum => sum.Amount ?? 0),
                        Remark = string.Join(";", s.Where(w => !string.IsNullOrEmpty(w.Remark)).Select(w => w.Remark).Distinct()),
                    })
                });
            return new ApiResponse(ResponseType.OK, "ok", result);
        }

        /// <summary>
        /// 新增医院其他绩效
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [Route("apr/insert")]
        [HttpPost]
        public ApiResponse InsertApr([FromBody] per_apr_amount request)
        {
            if (request.AllotId == 0)
                return new ApiResponse(ResponseType.ParameterError, "参数AllotId无效！");
            if (request.Amount == 0)
                return new ApiResponse(ResponseType.ParameterError, "金额不能是0！");

            var result = employeeService.InsertApr(request, claim.GetUserId());
            return result ? new ApiResponse(ResponseType.OK, "添加成功", request) :
                new ApiResponse(ResponseType.Fail, "添加失败");
        }

        /// <summary>
        /// 修改医院其他绩效
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [Route("apr/update")]
        [HttpPost]
        public ApiResponse UpdateApr([FromBody] per_apr_amount request)
        {
            if (request.AllotId == 0)
                return new ApiResponse(ResponseType.ParameterError, "参数AllotId无效！");

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

        /// <summary>
        /// 删除医院其他绩效
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [Route("apr/delete")]
        [HttpPost]
        public ApiResponse DeleteApr([FromBody] IdRequest request)
        {
            if (request.Id == 0)
                return new ApiResponse(ResponseType.ParameterError, "参数无效！");

            if (!employeeService.DeleteApr(request.Id))
                return new ApiResponse(ResponseType.Fail);
            return new ApiResponse(ResponseType.OK);
        }

        /// <summary>
        /// 医院其他绩效提交、撤销
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Route("apr/commit")]
        public ApiResponse CommitResult([FromBody] AprAmountAuditRequest request)
        {
            if (request.AllotId == 0)
                return new ApiResponse(ResponseType.ParameterError, "参数AllotId无效！");

            var result = employeeService.CommitApr(request.AllotId, request.TypeInDepartment, request.Status, request.CreateDate);
            return new ApiResponse(ResponseType.OK);
        }

        /// <summary>
        /// 医院其他绩效审核;驳回、成功
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Route("apr/audit")]
        public ApiResponse AuditResult([FromBody] AprAmountAuditRequest request)
        {
            var userid = claim.GetUserId();
            return employeeService.ConfirmAudit(userid, request);
        }

        /// <summary>
        /// 医院其他绩效审计
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Route("apr/mark")]
        public ApiResponse AprMark([FromBody] AprAmountMarkRequest request)
        {
            var userid = claim.GetUserId();
            return employeeService.AprMark(userid, request);
        }

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

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

            if (!ExtractHelper.IsXlsxFile(file.FileName))
                return new ApiResponse(ResponseType.Fail, "文件格式错误", "文件暂只支持xlsx文件");

            var allot = allotService.GetAllot(allotid);
            if (allot == null)
                return new ApiResponse(ResponseType.Fail, "allotid不存在");

            var name = FileHelper.GetFileNameNoExtension(file.FileName) + DateTime.Now.ToString("yyyyMMddHHmmssfff");
            var ext = FileHelper.GetExtension(file.FileName);
            var dpath = Path.Combine(evn.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}上传失败");
            }
            var result = employeeService.ImportAprEmployees(allotid, path, claim.GetUserId());
            return result;
        }

        /// <summary>
        /// 绩效类型字典
        /// </summary>
        /// <param name="allotId"></param>
        /// <returns></returns>
        [HttpPost("apr/perfortype/{allotId}")]
        public ApiResponse<List<TitleValue>> GetPerforTypeDict([FromRoute] int allotId)
        {
            var result = employeeService.GetPerforTypeDict(allotId);
            return new ApiResponse<List<TitleValue>>(ResponseType.OK, "绩效类型字典", result);
        }

        /// <summary>
        /// 医院其他绩效统计
        /// </summary>
        /// <param name="allotId"></param>
        /// <returns></returns>
        [Route("apr/overview/{allotId}")]
        [HttpPost]
        public ApiResponse AprOverview(int allotId)
        {
            //var roleType = new[] { 3, 4, 9, 10 };
            //var userid = claim.GetUserId();
            //var user = userService.GetUser(userid);
            //var role = roleService.GetUserRole(user.UserID);

            //var result = new List<Dictionary<string, string>>();

            //if (role.Any(t => roleType.Contains(t.Type.Value)))
            //result = employeeService.GetOtherPerStats(allotId, user.Department ?? "");
            //else
            //    result = employeeService.GetOtherPerStats(allotId);

            //return new ApiResponse(ResponseType.OK, result);
            if (allotId == 0)
                return new ApiResponse(ResponseType.ParameterError, "参数AllotId无效！");

            var employees = employeeService.GetAprList(allotId, "", 3);
            if (employees == null || !employees.Any())
                return new ApiResponse(ResponseType.OK, "ok", employees);

            var roleType = new[] { (int)Role.护士长, (int)Role.科主任, (int)Role.特殊科室, (int)Role.行政科室, };
            var userid = claim.GetUserId();
            var user = userService.GetUser(userid);
            var role = roleService.GetUserRole(user.UserID);

            if (role.Any(t => roleType.Contains(t.Type.Value)))
                employees = employees.Where(w => w.AccountingUnit == user.Department).ToList();

            var result = employees
                .GroupBy(t => new { t.AccountingUnit, t.PersonnelNumber, t.DoctorName })
                .Select(t => new
                {
                    PersonnelNumber = t.Key.PersonnelNumber,
                    DoctorName = t.Key.DoctorName,
                    AccountingUnit = t.Key.AccountingUnit,
                    Status = t.Any(s => s.Status == 2) ? 2 : t.Any(s => s.Status == 4) ? 4 : t.FirstOrDefault().Status,
                    Detail = t.GroupBy(group => group.PerforType).Select(s => new
                    {
                        Title = string.IsNullOrEmpty(s.Key) ? "未知" : s.Key,
                        Remark = string.Join(";", s.Where(w => !string.IsNullOrEmpty(w.Remark)).Select(w => w.Remark).Distinct()),
                        Value = s.Sum(sum => sum.Amount ?? 0)
                    })
                });
            return new ApiResponse(ResponseType.OK, "ok", result);
        }
        /// <summary>
        /// 医院其他绩效统计下载
        /// </summary>
        /// <param name="allotId"></param>
        /// <returns></returns>
        [Route("apr/overview/download/{allotId}")]
        [HttpPost]
        public IActionResult AprOverviewDownload(int allotId)
        {
            if (allotId == 0)
                return Ok(new ApiResponse(ResponseType.ParameterError, "参数AllotId无效！"));

            var userid = claim.GetUserId();
            var amounts = employeeService.GetAprList(allotId, "", 3) ?? new List<view_per_apr_amount>();

            if (!amounts?.Any() == true)
            {
                return Ok(new ApiResponse(ResponseType.Fail, "数据为空"));
            }
            var filepath = employeeService.AprListDownload("医院其他绩效统计下载", userid, amounts);

            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="request"></param>
        /// <returns></returns>
        [HttpPost("apr/clear")]
        public ApiResponse<List<TitleValue>> ClearAprData([FromBody] AprAmountAuditRequest request)
        {
            var result = employeeService.ClearAprData(request);
            return result ? new ApiResponse<List<TitleValue>>(ResponseType.OK, "删除成功")
               : new ApiResponse<List<TitleValue>>(ResponseType.OK, "删除失败");
        }
        #endregion

        /// <summary>
        /// 自动获取人员信息
        /// </summary>
        /// <remarks>
        /// Sample request:
        ///
        ///     POST /Todo
        ///     {
        ///       "allotid": 7,
        ///       "personnelnumber": "***************(用户输入信息)"
        ///     }
        ///
        /// </remarks>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost("autocomplate")]
        public ApiResponse<List<AutocomplateEmployeeResponse>> GetEmployeeMessage([FromBody] per_apr_amount request)
        {
            var userId = claim.GetUserId();
            var user = userService.GetUserIdentity(userId);
            var result = employeeService.GetEmployeeMessage(request.AllotId, request.PersonnelNumber, request.DoctorName, userId);
            var res = result.Select(t => new AutocomplateEmployeeResponse
            {
                AllotId = request.AllotId,
                PersonnelNumber = t.PersonnelNumber,
                DoctorName = t.DoctorName,
                TypeInDepartment = user.Department,
                AccountingUnit = t.AccountingUnit,
                PermanentStaff = t.PermanentStaff,
            }).ToList();

            return new ApiResponse<List<AutocomplateEmployeeResponse>>(ResponseType.OK, "人员信息", res);
        }

        /// <summary>
        /// 材料科室考核
        /// </summary>
        /// <returns></returns>
        [Route("deptAssessment/{allotId}")]
        [HttpPost]
        public ApiResponse GetDeptAssessment(int allotId)
        {
            if (allotId <= 0)
                return new ApiResponse(ResponseType.ParameterError, "参数AllotId无效！");

            var result = employeeService.GetDeptAssessment(allotId);
            return new ApiResponse(ResponseType.OK, result);
        }

        #region 不公示其他绩效
        /// <summary>
        /// 获取不公示其他绩效列表
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [Route("apr/hide/getlist")]
        [HttpPost]
        public ApiResponse GetAprHideList([FromBody] AprAmountAuditRequest request)
        {
            if (request.AllotId == 0)
                return new ApiResponse(ResponseType.ParameterError, "参数AllotId无效！");

            var employee = employeeService.GetAprHideByTypeInDepartment(request.AllotId, request.TypeInDepartment, request.CreateDate);
            if (employee != null && employee.Any())
                employee = employee.OrderByDescending(o => o.CreateDate).ToList();
            return new ApiResponse(ResponseType.OK, "ok", employee);
        }

        /// <summary>
        /// 不公示其他绩效审核
        /// </summary>
        /// <param name="isAudit"></param>
        /// <param name="request"></param>
        /// <returns></returns>
        [Route("apr/hide/getdeptlist/{isAudit}")]
        [HttpPost]
        public ApiResponse GetAprHideGroupList([FromRoute] int isAudit, [FromBody] AllotIdRequest request)
        {
            if (request.AllotId == 0)
                return new ApiResponse(ResponseType.ParameterError, "参数AllotId无效！");

            var result = employeeService.GetAprHideList(request.AllotId, claim.GetUserId(), isAudit);
            return new ApiResponse(ResponseType.OK, "ok", result);
        }


        /// <summary>
        /// 不公示其他绩效提交
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [Route("apr/submithidegrouplist")]
        [HttpPost]
        public ApiResponse SubmitHideGroupList([FromBody] SubmitAmountRequest request)
        {
            if (employeeService.SubmitHideDeptList(request))
                return new ApiResponse(ResponseType.OK, "提交成功");
            else
                return new ApiResponse(ResponseType.Fail, "提交失败");
        }

        /// <summary>
        ///不公示其他绩效审核详情
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [Route("apr/hide/getdeptdetail")]
        [HttpPost]
        public ApiResponse GetAprHideDetail([FromBody] per_apr_amount request)
        {
            if (request.AllotId == 0)
                return new ApiResponse(ResponseType.ParameterError, "参数AllotId无效！");

            var employee = employeeService.GetAprHideList(request.AllotId, request.TypeInDepartment, date: request.CreateDate);
            if (employee == null || !employee.Any())
                return new ApiResponse(ResponseType.OK, "ok", employee);

            var result = employee
                .GroupBy(t => new { t.AccountingUnit, t.PersonnelNumber, t.DoctorName })
                .Select(t => new
                {
                    PersonnelNumber = t.Key.PersonnelNumber,
                    DoctorName = t.Key.DoctorName,
                    AccountingUnit = t.Key.AccountingUnit,
                    Status = t.Any(s => s.Status == 2) ? 2 : t.Any(s => s.Status == 4) ? 4 : t.FirstOrDefault().Status,
                    Detail = t.GroupBy(group => group.PerforType).Select(s => new
                    {
                        Title = string.IsNullOrEmpty(s.Key) ? "未知" : s.Key,
                        Value = s.Sum(sum => sum.Amount ?? 0),
                        Remark = string.Join(";", s.Where(w => !string.IsNullOrEmpty(w.Remark)).Select(w => w.Remark).Distinct()),
                    })
                });
            return new ApiResponse(ResponseType.OK, "ok", result);
        }
        /// <summary>
        /// 新增不公示其他绩效
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [Route("apr/hide/insert")]
        [HttpPost]
        public ApiResponse InsertAprHide([FromBody] per_apr_amount_hide request)
        {
            if (request.AllotId == 0)
                return new ApiResponse(ResponseType.ParameterError, "参数AllotId无效！");
            if (request.Amount == 0)
                return new ApiResponse(ResponseType.ParameterError, "金额不能是0！");

            var result = employeeService.InsertAprHide(request, claim.GetUserId());
            return result ? new ApiResponse(ResponseType.OK, "添加成功", request) :
                new ApiResponse(ResponseType.Fail, "添加失败");
        }

        /// <summary>
        /// 修改不公示其他绩效
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [Route("apr/hide/update")]
        [HttpPost]
        public ApiResponse UpdateAprHide([FromBody] per_apr_amount_hide request)
        {
            if (request.AllotId == 0)
                return new ApiResponse(ResponseType.ParameterError, "参数AllotId无效！");

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

        /// <summary>
        /// 删除不公示其他绩效
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [Route("apr/hide/delete")]
        [HttpPost]
        public ApiResponse DeleteAprHide([FromBody] IdRequest request)
        {
            if (request.Id == 0)
                return new ApiResponse(ResponseType.ParameterError, "参数无效！");

            if (!employeeService.DeleteAprHide(request.Id))
                return new ApiResponse(ResponseType.Fail);
            return new ApiResponse(ResponseType.OK);
        }


        /// <summary>
        /// 医院其他绩效提交、撤销
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Route("apr/hide/commit")]
        public ApiResponse CommitResultHide([FromBody] AprAmountAuditRequest request)
        {
            if (request.AllotId == 0)
                return new ApiResponse(ResponseType.ParameterError, "参数AllotId无效！");

            var result = employeeService.CommitAprHide(request.AllotId, request.TypeInDepartment, request.Status, request.CreateDate);
            return new ApiResponse(ResponseType.OK);
        }

        /// <summary>
        /// 不公示其他绩效审核;驳回、成功
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Route("apr/hide/audit")]
        public ApiResponse AuditResultHide([FromBody] AprAmountAuditRequest request)
        {
            var userid = claim.GetUserId();
            return employeeService.ConfirmAuditHide(userid, request);
        }

        /// <summary>
        /// 不公示其他绩效审计
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Route("apr/hide/mark")]
        public ApiResponse AprMarkHide([FromBody] AprAmountMarkRequest request)
        {
            var userid = claim.GetUserId();
            return employeeService.AprMarkHide(userid, request);
        }

        /// <summary>
        /// 上传不公示其他绩效
        /// </summary>
        /// <param name="form"></param>
        /// <returns></returns>
        [Route("apr/hide/import")]
        [HttpPost]
        public ApiResponse ImportAprHide([FromForm] IFormCollection form)
        {
            var allotid = form.ToDictionary().GetValue("allotid", 0);
            if (allotid <= 0)
                return new ApiResponse(ResponseType.Fail, "参数错误", "allotid无效");

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

            if (!ExtractHelper.IsXlsxFile(file.FileName))
                return new ApiResponse(ResponseType.Fail, "文件格式错误", "文件暂只支持xlsx文件");

            var allot = allotService.GetAllot(allotid);
            if (allot == null)
                return new ApiResponse(ResponseType.Fail, "allotid不存在");

            var name = FileHelper.GetFileNameNoExtension(file.FileName) + DateTime.Now.ToString("yyyyMMddHHmmssfff");
            var ext = FileHelper.GetExtension(file.FileName);
            var dpath = Path.Combine(evn.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}上传失败");
            }
            var res = employeeService.ImportAprHideEmployees(allotid, path, claim.GetUserId());
            return res;
        }

        /// <summary>
        /// 不公示其他绩效类型字典
        /// </summary>
        /// <param name="allotId"></param>
        /// <returns></returns>
        [HttpPost("apr/hide/perfortype/{allotId}")]
        public ApiResponse<List<TitleValue>> GetPerforTypeDictHide([FromRoute] int allotId)
        {
            var result = employeeService.GetPerforTypeDictHide(allotId);
            return new ApiResponse<List<TitleValue>>(ResponseType.OK, "绩效类型字典", result);
        }

        /// <summary>
        /// 不公示其他绩效统计
        /// </summary>
        /// <param name="allotId"></param>
        /// <returns></returns>
        [Route("apr/hide/overview/{allotId}")]
        [HttpPost]
        public ApiResponse AprHideOverview(int allotId)
        {
            //var relust = employeeService.GetOtherPerStatsHide(allotId);
            //return new ApiResponse(ResponseType.OK, relust);

            if (allotId == 0)
                return new ApiResponse(ResponseType.ParameterError, "参数AllotId无效！");

            var employees = employeeService.GetAprHideList(allotId, "", 3);
            if (employees == null || !employees.Any())
                return new ApiResponse(ResponseType.OK, "ok", employees);

            var roleType = new[] { (int)Role.护士长, (int)Role.科主任, (int)Role.特殊科室, (int)Role.行政科室, };
            var userid = claim.GetUserId();
            var user = userService.GetUser(userid);
            var role = roleService.GetUserRole(user.UserID);

            if (role.Any(t => roleType.Contains(t.Type.Value)))
                employees = employees.Where(w => w.AccountingUnit == user.Department).ToList();

            var result = employees
                .GroupBy(t => new { t.AccountingUnit, t.PersonnelNumber, t.DoctorName })
                .Select(t => new
                {
                    PersonnelNumber = t.Key.PersonnelNumber,
                    DoctorName = t.Key.DoctorName,
                    AccountingUnit = t.Key.AccountingUnit,
                    Status = t.Any(s => s.Status == 2) ? 2 : t.Any(s => s.Status == 4) ? 4 : t.FirstOrDefault().Status,
                    Detail = t.GroupBy(group => group.PerforType).Select(s => new
                    {
                        Title = string.IsNullOrEmpty(s.Key) ? "未知" : s.Key,
                        Remark = string.Join(";", s.Where(w => !string.IsNullOrEmpty(w.Remark)).Select(w => w.Remark).Distinct()),
                        Value = s.Sum(sum => sum.Amount ?? 0)
                    })
                });
            return new ApiResponse(ResponseType.OK, "ok", result);
        }
        /// <summary>
        /// 不公示其他绩效统计下载
        /// </summary>
        /// <param name="allotId"></param>
        /// <returns></returns>
        [Route("apr/hide/overview/download/{allotId}")]
        [HttpPost]
        public IActionResult AprHideOverviewDownload(int allotId)
        {
            var userid = claim.GetUserId();
            if (allotId == 0)
                return Ok(new ApiResponse(ResponseType.ParameterError, "参数AllotId无效！"));

            var amounts = employeeService.GetAprHideList(allotId, "", 3);
            if (!amounts?.Any() == true)
                return Ok(new ApiResponse(ResponseType.Fail, "数据为空"));

            var filepath = employeeService.AprListDownload("不公示其他绩效统计表下载", userid, amounts);

            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="request"></param>
        /// <returns></returns>
        [HttpPost("apr/hide/clear")]
        public ApiResponse<List<TitleValue>> ClearAprHideData([FromBody] AprAmountAuditRequest request)
        {
            var result = employeeService.ClearAprHideData(request);
            return result ? new ApiResponse<List<TitleValue>>(ResponseType.OK, "删除成功")
               : new ApiResponse<List<TitleValue>>(ResponseType.OK, "删除失败");
        }
        #endregion

        /// <summary>
        /// 实发绩效比对
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [Route("getComparison")]
        [HttpPost]
        public ApiResponse GetDeptComparison([FromBody] ComparisonPagingRequest request)
        {
            var allot = allotService.GetAllot(request.AllotId);
            if (allot == null)
                return new ApiResponse(ResponseType.ParameterError, "allotId无效");

            var relust = employeeService.GetComparison(request);
            return new ApiResponse(ResponseType.OK, relust);
        }

        /// <summary>
        /// 实发绩效校验
        /// </summary>
        /// <param name="allotId"></param>
        /// <returns></returns>
        [Route("getDeptComparisonTotal/{allotId}")]
        [HttpPost]
        public ApiResponse GetDeptComparisonTotal([FromRoute] int allotId)
        {
            var allot = allotService.GetAllot(allotId);
            if (allot == null)
                return new ApiResponse(ResponseType.ParameterError, "allotId无效");

            var relust = employeeService.GetDeptComparisonTotal(allotId);
            return new ApiResponse(ResponseType.OK, relust);
        }
        #region 手工录入

        /// <summary>
        /// 手工录入 - 下拉列表
        /// </summary>
        /// <param name="gather"></param>
        /// <returns></returns>
        [Route("getgatherdrop")]
        [HttpPost]
        public ApiResponse GetGatherDrop([FromBody] Gather gather)
        {
            if (gather.AllotId <= 0)
                return new ApiResponse(ResponseType.Fail, "参数错误", "allotid无效");

            var relust = employeeService.GetGatherDrop(gather);
            return new ApiResponse(ResponseType.OK, relust);
        }


        /// <summary>
        /// 手工录入 - 录入界面
        /// </summary>
        /// <param name="allotId"></param>
        /// <param name="request"></param>
        /// <returns></returns>
        [Route("getgatherhands/{allotId}")]
        [HttpPost]
        public ApiResponse GetGatherHands([FromRoute] int allotId, [FromBody] GatherRequest request)
        {
            if (allotId <= 0)
                return new ApiResponse(ResponseType.Fail, "参数错误", "allotid无效");
            var relust = employeeService.GetGatherHands(allotId, request);
            return new ApiResponse(ResponseType.OK, relust);
        }

        /// <summary>
        /// 保存手工录入
        /// </summary>
        /// <param name="allotId"></param>
        /// <param name="request"></param>
        /// <returns></returns>
        [Route("savegatherhands/{allotId}")]
        [HttpPost]
        public ApiResponse SaveGatherHands([FromRoute] int allotId, [FromBody] SaveGatherData request)
        {
            if (allotId <= 0)
                return new ApiResponse(ResponseType.Fail, "参数错误", "allotid无效");

            if (request.Data == null || !request.Data.Any())
                return new ApiResponse(ResponseType.Fail, "用户提交数据为空");

            request.UserId = claim.GetUserId();
            return employeeService.SaveGatherHands(allotId, request);
        }

        /// <summary>
        /// 手工录入列表 - 明细
        /// </summary>
        /// <param name="gather"></param>
        /// <returns></returns>
        [Route("getgather")]
        [HttpPost]
        public ApiResponse GetGather([FromBody] Gather gather)
        {
            if (gather.AllotId <= 0 || string.IsNullOrEmpty(gather.Source) || string.IsNullOrEmpty(gather.Category) || string.IsNullOrEmpty(gather.Department))
                return new ApiResponse(ResponseType.Fail, "参数错误", "请检查allotId,source,category,department是否正确");

            var result = employeeService.GetGather(gather);

            return new ApiResponse(ResponseType.OK, result);

        }

        /// <summary>
        /// 手工录入列表 - 汇总 
        /// </summary>
        /// <param name="gather"></param>
        /// <returns></returns>
        [Route("getgathertotal")]
        [HttpPost]
        public ApiResponse GetGatherTotal([FromBody] Gather gather)
        {
            if (gather.AllotId <= 0)
                return new ApiResponse(ResponseType.Fail, "参数错误", "allotid无效");

            var result = employeeService.GetGatherTotal(gather);

            return new ApiResponse(ResponseType.OK, result);
        }

        /// <summary>
        /// 手工录入列表 - 删除
        /// </summary>
        /// <param name="gather"></param>
        /// <returns></returns>
        [Route("deleteGather")]
        [HttpPost]
        public ApiResponse DeleteGather([FromBody] Gather gather)
        {
            if (gather.AllotId <= 0 || string.IsNullOrEmpty(gather.Source) || string.IsNullOrEmpty(gather.Category) || string.IsNullOrEmpty(gather.Department))
                return new ApiResponse(ResponseType.Fail, "参数错误", "请检查allotId,source,category,department是否正确");

            var result = employeeService.DeleteGather(gather);
            if (result) return new ApiResponse(ResponseType.OK, "删除成功");
            else return new ApiResponse(ResponseType.Fail, "删除失败");

        }
        /// <summary>
        /// 批量审核
        /// </summary>
        /// <param name="gather"></param>
        /// <returns></returns>
        [Route("auditGather")]
        [HttpPost]
        public ApiResponse AuditGather([FromBody] List<Gather> gather)
        {
            employeeService.AuditGather(gather);
            return new ApiResponse(ResponseType.OK, "");
        }


        /// <summary>
        /// 上传手工录入文件
        /// </summary>
        /// <param name="gather"></param>
        /// <param name="file"></param>
        /// <returns></returns>
        [Route("uploadgatherfile")]
        [HttpPost]
        public ApiResponse UploadGatherFile([FromForm] Gather gather, [FromForm] IFormFile file)
        {
            if (!file.FileName.EndsWith(".xlsx"))
                return new ApiResponse(ResponseType.Fail, "请上传xlsx文件");
            var dpath = Path.Combine(evn.ContentRootPath, "Files", "GatherFile");
            FileHelper.CreateDirectory(dpath);

            var fileName = string.Concat(gather.Source, gather.Category, gather.Department, Path.GetFileName(file.FileName));
            string path = Path.Combine(dpath, fileName);

            var result = employeeService.UploadGatherFile(path, gather);
            if (!string.IsNullOrEmpty(result))
                return new ApiResponse(ResponseType.Fail, result);

            if (!string.IsNullOrEmpty(path) && FileHelper.IsExistFile(path))
                FileHelper.DeleteFile(path);

            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, "上传失败");
            }
            return new ApiResponse(ResponseType.OK, "上传成功");
        }

        /// <summary>
        /// 下载手工录入上传文件
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        [Route("downloadgatherfile")]
        [HttpPost]
        public IActionResult DownloadGatherFile(string path)
        {
            if (string.IsNullOrEmpty(path))
                throw new PerformanceException("尚未提交文件");

            if (!FileHelper.IsExistFile(path))
                throw new PerformanceException("测算表文件路径无效");

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

        #region 医院其他绩效类型
        /// <summary>
        /// 医院其他绩效类型清单
        /// </summary>
        /// <param name="allotId"></param>
        /// <returns></returns>
        [Route("apr/type/list/{allotId}")]
        [HttpPost]
        public ApiResponse<List<per_apr_amount_type>> GetAprTypeList([FromRoute] int allotId)
        {

            return employeeService.GetAprTypeList(allotId);
        }

        /// <summary>
        /// 医院其他绩效列表清单添加
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [Route("apr/type/insert")]
        [HttpPost]
        public ApiResponse<AprTypeRequest> InsertAprType([FromBody] AprTypeRequest request)
        {

            var createUser = claim.GetUserId();
            return employeeService.InsertAprType(createUser, request);

        }

        /// <summary>
        /// 医院其他绩效列表清单修改
        /// </summary>
        /// <param name="typeId"></param>
        /// <param name="request"></param>
        /// <returns></returns>
        [Route("apr/type/update")]
        [HttpPost]
        public ApiResponse<AprTypeRequest> UpdateAprType([FromQuery] int typeId, [FromBody] AprTypeRequest request)
        {
            return employeeService.UpdateAprType(typeId, request);
        }

        /// <summary>
        /// 医院其他绩效列表清单删除
        /// </summary>
        /// <param name="typeId"></param>
        /// <returns></returns>
        [Route("apr/type/delete")]
        [HttpPost]
        public ApiResponse DeleteAprType([FromQuery] int typeId)
        {
            return employeeService.DeleteAprType(typeId);
        }
        #endregion


        #region 不公示医院其他绩效类型
        /// <summary>
        /// 不公示医院其他绩效类型清单
        /// </summary>
        /// <param name="allotId"></param>
        /// <returns></returns>
        [Route("apr/hide/type/list/{allotId}")]
        [HttpPost]
        public ApiResponse<List<per_apr_amount_hide_type>> GetAprTypeListHide([FromRoute] int allotId)
        {

            return employeeService.GetAprTypeListHide(allotId);
        }

        /// <summary>
        /// 不公示医院其他绩效列表清单添加
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [Route("apr/hide/type/insert")]
        [HttpPost]
        public ApiResponse<AprTypeRequest> InsertAprTypeHide([FromBody] AprTypeRequest request)
        {

            var createUser = claim.GetUserId();
            return employeeService.InsertAprTypeHide(createUser, request);

        }

        /// <summary>
        /// 不公示医院其他绩效列表清单修改
        /// </summary>
        /// <param name="typeId"></param>
        /// <param name="request"></param>
        /// <returns></returns>
        [Route("apr/hide/type/update")]
        [HttpPost]
        public ApiResponse<AprTypeRequest> UpdateAprTypehide([FromQuery] int typeId, [FromBody] AprTypeRequest request)
        {
            return employeeService.UpdateAprTypeHide(typeId, request);
        }

        /// <summary>
        /// 不公示医院其他绩效列表清单删除
        /// </summary>
        /// <param name="typeId"></param>
        /// <returns></returns>
        [Route("apr/hide/type/delete")]
        [HttpPost]
        public ApiResponse DeleteAprTypeHide([FromQuery] int typeId)
        {
            return employeeService.DeleteAprTypeHide(typeId);
        }
        #endregion
    }
}
