using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using FluentValidation.AspNetCore;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Performance.DtoModels;
using Performance.DtoModels.AppSettings;
using Performance.Infrastructure;
using Performance.Services;

namespace Performance.Api.Controllers
{
    [Route("api/modextract")]
    [ApiController]
    public class ExConfigController : Controller
    {
        private ILogger logger;
        private WebapiUrl options;
        private ExConfigService configService;

        public ExConfigController(
            ILogger<ExConfigController> logger,
            IOptions<WebapiUrl> options,
            ExConfigService configService)
        {
            this.logger = logger;
            this.options = options.Value;
            this.configService = configService;
        }

        /// <summary>
        /// 绩效数据抽取模板
        /// </summary>
        /// <returns></returns>
        [Route("scheme")]
        [HttpPost]
        public ApiResponse Extract([CustomizeValidator(RuleSet = "Query"), FromBody] ModModuleRequest request)
        {
            if (request.HospitalId == null || request.HospitalId.Value == 0)
                return new ApiResponse(ResponseType.ParameterError, "HospitalId 不存在，请重新选择！");
            if (request.ExecuteType == null || !request.ExecuteType.Any())
                return new ApiResponse(ResponseType.ParameterError, "ExecuteType 不存在，请重新选择！");

            var list = configService.ExtractScheme(request.HospitalId.Value, request.ExecuteType, request.SheetType);
            return new ApiResponse(ResponseType.OK, list);
        }

        /// <summary>
        /// 费用类型
        /// </summary>
        /// <returns></returns>
        [Route("type")]
        [HttpPost]
        public ApiResponse FeeType()
        {
            var list = configService.FeeType();
            return new ApiResponse(ResponseType.OK, list);
        }

        /// <summary>
        /// 绩效考核项费用来源
        /// </summary>
        /// <returns></returns>
        [Route("source")]
        [HttpPost]
        public ApiResponse FeeSource([FromBody] ModModuleRequest request)
        {
            if (request.HospitalId == null || request.HospitalId.Value == 0)
                return new ApiResponse(ResponseType.ParameterError, "HospitalId 参数错误！");

            bool isSingle = false;
            configService.QueryHosConfigs(request.ModuleId.Value, ref isSingle, out int sheetType);

            ModFeeResponse response;
            if (isSingle)
            {
                response = configService.FeeSource(request);
            }
            else
            {
                var http = new RestSharpHelper();
                var url = http.SetUrl(options.HttpPost, "modextract/source");
                var req = http.CreatePostRequest(JsonHelper.Serialize(request));
                var res = http.GetResponse(url, req);
                var ret = http.GetContent<ApiResponse<ModFeeResponse>>(res);
                response = ret.Data;
            }
            return new ApiResponse(ResponseType.OK, response);
        }

        /// <summary>
        /// 费用字典新增
        /// </summary>
        /// <returns></returns>
        [Route("addmodule")]
        [HttpPost]
        public ApiResponse AddModule([CustomizeValidator(RuleSet = "Add"), FromBody] ModModuleRequest request)
        {
            if (request.HospitalId == null || request.HospitalId.Value == 0)
                return new ApiResponse(ResponseType.ParameterError, "HospitalId 参数错误！");

            var entity = configService.AddModule(request);
            return new ApiResponse(ResponseType.OK, "添加成功！", entity);
        }

        /// <summary>
        /// 费用字典（绩效模板）
        /// </summary>
        /// <returns></returns>
        [Route("modules")]
        [HttpPost]
        public ApiResponse Module([CustomizeValidator(RuleSet = "Query"), FromBody] ModModuleRequest request)
        {
            if (request.HospitalId == null || request.HospitalId.Value == 0)
                return new ApiResponse(ResponseType.ParameterError, "HospitalId 不存在，请重新选择！");

            var list = configService.QueryModule(request.HospitalId.Value);
            return new ApiResponse(ResponseType.OK, list);
        }

        /// <summary>
        /// 绩效模板修改
        /// </summary>
        /// <returns></returns>
        [Route("editmodule")]
        [HttpPost]
        public ApiResponse EditModule([FromBody] ModModuleRequest request)
        {
            if (request.ModuleId == null || request.ModuleId == 0)
                return new ApiResponse(ResponseType.ParameterError, "ModuleId 参数错误！");

            var entity = configService.EditModule(request);
            return new ApiResponse(ResponseType.OK, "修改成功！", entity);
        }

        /// <summary>
        /// 绩效模板删除
        /// </summary>
        /// <returns></returns>
        [Route("deletemodule")]
        [HttpPost]
        public ApiResponse DelModule([FromBody] ModModuleRequest request)
        {
            if (request.ModuleId == null || request.ModuleId == 0)
                return new ApiResponse(ResponseType.ParameterError, "ModuleId 参数错误！");

            configService.DelModule(request.ModuleId.Value);
            return new ApiResponse(ResponseType.OK, "删除成功！");
        }

        /// <summary>
        /// 绩效收入模板配置项新增
        /// </summary>
        /// <returns></returns>
        [Route("additem")]
        [HttpPost]
        public ApiResponse AddItem([FromBody] ItemListRequest request)
        {
            if (request.ModuleId == null && request.ModuleId == 0)
                return new ApiResponse(ResponseType.ParameterError, "ModuleId 参数错误！");

            if (request.Items == null && !request.Items.Any())
                return new ApiResponse(ResponseType.ParameterError, "Items 未发现任添加何项！");

            var list = configService.AddItem(request);
            return new ApiResponse(ResponseType.OK, "添加成功！", list);
        }

        /// <summary>
        /// 绩效收入模板配置项列表
        /// </summary>
        /// <returns></returns>
        [Route("items")]
        [HttpPost]
        public ApiResponse Items([FromBody] ModItemRequest request)
        {
            bool isSingle = false;
            if (!configService.QueryHosConfigs(request.ModuleId.Value, ref isSingle, out int sheetType))
                return new ApiResponse(ResponseType.Fail, "当前医院未配置地址");

            if (sheetType == (int)SheetType.Income)
            {
                if (isSingle)
                {
                    configService.AddItems(request.ModuleId.Value);
                }
                else
                {
                    logger.LogInformation($"绩效收入模板配置项列表 : 请求地址 {options.HttpPost}modextract/items");

                    var http = new RestSharpHelper();
                    var url = http.SetUrl(options.HttpPost, "modextract/items");
                    var req = http.CreatePostRequest(JsonHelper.Serialize(request));
                    var res = http.GetResponse(url, req);
                    var ret = http.GetContent<ApiResponse>(res);

                    logger.LogInformation($"绩效收入模板配置项列表在{DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss完成请求")}");
                }
            }
            var list = configService.QueryItems(request.ModuleId.Value);
            return new ApiResponse(ResponseType.OK, list);
        }

        /// <summary>
        /// 绩效收入模板配置项修改
        /// </summary>
        /// <returns></returns>
        [Route("edititem")]
        [HttpPost]
        public ApiResponse EditItem([FromBody] ItemListRequest request)
        {
            if (request.Items == null || !request.Items.Any())
                return new ApiResponse(ResponseType.ParameterError, "请选择需要修改的数据！");

            var entity = configService.EditItem(request.Items[0]);
            return new ApiResponse(ResponseType.OK, "修改成功！", entity);
        }

        /// <summary>
        /// 绩效收入模板配置项删除
        /// </summary>
        /// <returns></returns>
        [Route("deleteitem")]
        [HttpPost]
        public ApiResponse DelItem([FromBody] ModItemRequest request)
        {
            if (request.ItemId == null && request.ItemId == 0)
                return new ApiResponse(ResponseType.ParameterError, "ItemId 参数错误！");

            configService.DelItem(request.ItemId.Value);
            return new ApiResponse(ResponseType.OK, "删除成功！");
        }

        #region 特殊科室模板

        /// <summary>
        /// 特殊科室模板配置项新增
        /// </summary>
        /// <returns></returns>
        [Route("addspecial")]
        [HttpPost]
        public ApiResponse AddSpecial([FromBody] SpecialListRequest request)
        {
            if (request.HospitalId == 0)
                return new ApiResponse(ResponseType.ParameterError, "HospitalId 参数错误！");

            if (request.Items == null && !request.Items.Any())
                return new ApiResponse(ResponseType.ParameterError, "Items 未发现任添加何项！");

            var list = configService.AddSpecial(request);
            return new ApiResponse(ResponseType.OK, "添加成功！", list);
        }

        /// <summary>
        /// 特殊科室模板配置项列表
        /// </summary>
        /// <returns></returns>
        [Route("specials")]
        [HttpPost]
        public ApiResponse Specials([FromBody] ModSpecialRequest request)
        {
            var list = configService.QuerySpecial(request.HospitalId.Value);
            return new ApiResponse(ResponseType.OK, list);
        }

        /// <summary>
        /// 特殊科室模板配置项修改
        /// </summary>
        /// <returns></returns>
        [Route("editspecial")]
        [HttpPost]
        public ApiResponse EditSpecial([FromBody] SpecialListRequest request)
        {
            if (request.Items == null || !request.Items.Any())
                return new ApiResponse(ResponseType.ParameterError, "请选择需要修改的数据！");

            var entity = configService.EditSpecial(request.Items[0]);
            return new ApiResponse(ResponseType.OK, "修改成功！", entity);
        }

        /// <summary>
        /// 特殊科室模板配置项删除
        /// </summary>
        /// <returns></returns>
        [Route("deletespecial")]
        [HttpPost]
        public ApiResponse DelSpecial([FromBody] ModSpecialRequest request)
        {
            if (request.SpecialId == null && request.SpecialId == 0)
                return new ApiResponse(ResponseType.ParameterError, "SpecialId 参数错误！");

            configService.DelSpecial(request.SpecialId.Value);
            return new ApiResponse(ResponseType.OK, "删除成功！");
        }

        /// <summary>
        /// 特殊科室人均
        /// </summary>
        /// <returns></returns>
        [Route("perfortype")]
        [HttpPost]
        public ApiResponse PerforType()
        {
            var list = configService.PerforType();
            return new ApiResponse(ResponseType.OK, list);
        }

        #endregion 特殊科室模板

        /// <summary>
        /// 数据配置项
        /// </summary>
        /// <returns></returns>
        [Route("config")]
        [HttpPost]
        public ApiResponse Config([FromBody] ModModuleRequest request)
        {
            if (request.HospitalId == null || request.HospitalId.Value == 0)
                return new ApiResponse(ResponseType.ParameterError, "HospitalId 不存在，请重新选择！");
            var configs = configService.GetHospitalconfigs(request.HospitalId.Value);
            return new ApiResponse(ResponseType.OK, "绩效抽取数据地址！", configs);
        }
    }
}
