using AutoMapper;
using Microsoft.EntityFrameworkCore.Internal;
using NPOI.SS.Formula.Functions;
using Performance.DtoModels;
using Performance.EntityModels;
using Performance.Repository;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Performance.Services
{
    public class BudgetService : IAutoInjection
    {
        private readonly PerforPerbudgetamountRepository perbudgetamountRepository;
        private readonly PerforPerbudgetratioRepository perbudgetratioRepository;
        private readonly PerforPerbudgetresultRepository perbudgetresultRepository;
        private readonly PerforPerallotRepository perallotRepository;

        public BudgetService(PerforPerbudgetamountRepository perbudgetamountRepository,
            PerforPerbudgetratioRepository perbudgetratioRepository,
            PerforPerbudgetresultRepository perbudgetresultRepository,
            PerforPerallotRepository perallotRepository)
        {
            this.perbudgetamountRepository = perbudgetamountRepository;
            this.perbudgetratioRepository = perbudgetratioRepository;
            this.perbudgetresultRepository = perbudgetresultRepository;
            this.perallotRepository = perallotRepository;
        }

        /// <summary>
        /// 预算管理查询（包含金额、占比）
        /// </summary>
        /// <param name="hospitalid"></param>
        /// <param name="year"></param>
        /// <returns></returns>
        public List<BudgetResponse> QueryBudgetByYear(int hospitalid, int year)
        {
            var nextYear = year + 1;
            var amounts = perbudgetamountRepository.GetEntities(t => t.HospitalId == hospitalid && new List<int> { year, nextYear }.Contains(t.Year));
            var ratios = perbudgetratioRepository.GetEntities(t => t.HospitalId == hospitalid && new List<int> { year, nextYear }.Contains(t.Year));
            var result = Mapper.Map<List<BudgetResponse>>(amounts);
            if (result == null)
                return Mapper.Map<List<BudgetResponse>>(ratios);
            else if (ratios != null && ratios.Any())
            {
                result.AddRange(Mapper.Map<List<BudgetResponse>>(ratios));
            }
            return result;
        }

        /// <summary>
        /// 保存预算管理数据
        /// </summary>
        /// <param name="request"></param>
        /// <param name="userId"></param>
        /// <returns></returns>
        public bool SaveBudgetData(List<BudgetResponse> request, int userId)
        {
            if (request == null || !request.Any(t => t.Type == 1) || !request.Any(t => t.Type == 2))
                throw new PerformanceException("提交数据中含无效数据");

            var amounts = Mapper.Map<List<per_budget_amount>>(request.Where(t => t.Type == 1));
            amounts.ForEach(t =>
            {
                t.CreateTime = DateTime.Now;
                t.CreateUser = userId;
            });
            if (amounts != null && perbudgetamountRepository.AddRange(amounts.ToArray()))
            {
                var ratios = Mapper.Map<List<per_budget_ratio>>(request.Where(t => t.Type == 2));
                ratios.ForEach(t =>
                {
                    t.CreateTime = DateTime.Now;
                    t.CreateUser = userId;
                });
                return perbudgetratioRepository.AddRange(ratios.ToArray());
            }

            return false;
        }

        /// <summary>
        /// 修改预算管理数据
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public bool ModifyBudgetData(List<BudgetResponse> request)
        {
            if (request == null || !request.Any(t => t.Type == 1) || !request.Any(t => t.Type == 2))
                throw new PerformanceException("提交数据中含无效数据");

            var amounts = perbudgetamountRepository.GetEntities(w => request.Where(t => t.Type == 1).Select(t => t.Id).Contains(w.Id));
            if (amounts != null && amounts.Any())
            {
                foreach (var item in amounts)
                {
                    var data = request.FirstOrDefault(t => t.Type == 1 && t.Id == item.Id);
                    if (data == null) continue;
                    item.HospitalRevenue = data.HospitalRevenue;
                    item.HospitalRevenue = data.HospitalRevenue;
                    item.TotalLaborCost = data.TotalLaborCost;
                    item.StaffSpendingFixed = data.StaffSpendingFixed;
                    item.StaffSpendingBonus = data.StaffSpendingBonus;
                    item.TotalMeritPay = data.TotalMeritPay;
                    item.AmountOfStaff = data.AmountOfStaff;
                    item.ThePerCapitaMerit = data.ThePerCapitaMerit;
                    item.TheIncrementCapita = data.TheIncrementCapita;
                    item.TheDrugIncome = data.TheDrugIncome;
                    item.MaterialIncome = data.MaterialIncome;
                    item.TheCostInTotal = data.TheCostInTotal;
                    item.DepreOfFixedAssets = data.DepreOfFixedAssets;
                    item.AmortOfIntangibleAssets = data.AmortOfIntangibleAssets;
                    item.MedicalRisk = data.MedicalRisk;
                    item.OtherExpenses = data.OtherExpenses;
                    item.BalanceOfPayments = data.BalanceOfPayments;
                    item.FiscalSubsidies = data.FiscalSubsidies;
                    item.TheTotalHospitalBalance = data.TheTotalHospitalBalance;
                }
                perbudgetamountRepository.UpdateRange(amounts.ToArray());
            }

            var ratios = perbudgetratioRepository.GetEntities(w => request.Where(t => t.Type == 2).Select(t => t.Id).Contains(w.Id));
            if (ratios != null && ratios.Any())
            {
                foreach (var item in ratios)
                {
                    var data = request.FirstOrDefault(t => t.Type == 2 && t.Id == item.Id);
                    if (data == null) continue;
                    item.HospitalRevenue = data.HospitalRevenue;
                    item.TotalLaborCost = data.TotalLaborCost;
                    item.StaffSpendingFixed = data.StaffSpendingFixed;
                    item.StaffSpendingBonus = data.StaffSpendingBonus;
                    item.MeritPayIncrement = data.MeritPayIncrement;
                    item.TotalMeritPay = data.TotalMeritPay;
                    item.Amplification = data.Amplification;
                    item.IncrementCapitaRatio = data.IncrementCapitaRatio;
                    item.TheDrugIncome = data.TheDrugIncome;
                    item.TheDrugIncomeBudget = data.TheDrugIncomeBudget;
                    item.MaterialIncome = data.MaterialIncome;
                    item.MaterialIncomeBudget = data.MaterialIncomeBudget;
                    item.TheCostInTotal = data.TheCostInTotal;
                    item.DepreOfFixedAssets = data.DepreOfFixedAssets;
                    item.AmortOfIntangibleAssets = data.AmortOfIntangibleAssets;
                    item.MedicalRisk = data.MedicalRisk;
                    item.OtherExpenses = data.OtherExpenses;
                    item.BalanceOfPayments = data.BalanceOfPayments;
                    item.TheTotalHospitalBalance = data.TheTotalHospitalBalance;
                }
                perbudgetratioRepository.UpdateRange(ratios.ToArray());
            }

            return true;
        }

        /// <summary>
        /// 预算合计数据查询
        /// </summary>
        /// <param name="hospitalid"></param>
        /// <param name="year"></param>
        /// <returns></returns>
        public List<per_budget_result> QueryResultByYear(int hospitalid, int year)
        {
            var results = perbudgetresultRepository.GetEntities(t => t.HospitalId == hospitalid && t.Year == year);
            return results;
        }

        /// <summary>
        /// 预算比例、历史比例查询
        /// </summary>
        /// <param name="hospitalid"></param>
        /// <param name="year"></param>
        /// <returns></returns>
        public List<BudgetRatioResponse> QueryBudgetRatio(int hospitalid, int year)
        {
            var nextYear = year + 1;
            var ratios = perbudgetratioRepository.GetEntities(t => t.HospitalId == hospitalid && new List<int> { year, nextYear }.Contains(t.Year));

            if (ratios != null && ratios.Any())
            {
                var result = ratios.Select(t => new BudgetRatioResponse
                {
                    HospitalId = t.HospitalId,
                    Year = t.Year,
                    PersonExpendRatio = t.TotalLaborCost,
                    NewPerformanceRatio = t.TheCostInTotal,
                    MedicinePropRatio = t.TheDrugIncome,
                    MaterialCostsRatio = t.MaterialIncome,
                    TotalMedicineRatio = t.TheDrugIncome + t.MaterialIncome,
                    DepreOfFixedAssetsRatio = t.DepreOfFixedAssets,
                    OtherExpensesRatio = t.OtherExpenses,
                    TheCostInTotalRatio = t.TheCostInTotal,
                    TheCostCombinedRatio = t.TheCostInTotal,
                });

                return result.OrderBy(t => t.Year).ToList();
            }
            return new List<BudgetRatioResponse>();
        }

        /// <summary>
        /// 保存预算合计数据
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public bool SaveBudgetRatio(List<per_budget_result> request, int userId)
        {
            if (request == null || !request.Any())
                throw new PerformanceException("提交数据为空");

            // 有效Id, 已经提交过的数据
            var effectIds = request.Where(t => t.Id != 0).Select(t => t.Id);
            if (effectIds != null && effectIds.Any())
            {
                var results = perbudgetresultRepository.GetEntities(t => effectIds.Contains(t.Id));
                if (results == null || !results.Any())
                    throw new PerformanceException("提交数据中需要修改的数据无效");
                foreach (var item in results)
                {
                    var data = request.FirstOrDefault(t => t.Id == item.Id);
                    if (data == null) continue;

                    item.Grant = data.Grant;
                    item.Adjust = data.Adjust;
                    item.MedicalIncome = data.MedicalIncome;
                    item.PersonnelExpenditure = data.PersonnelExpenditure;
                    item.TheNewPerformance = data.TheNewPerformance;
                    item.MedicineProportion = data.MedicineProportion;
                    item.MaterialCosts = data.MaterialCosts;
                    item.TotalMedicine = data.TotalMedicine;
                    item.DepreOfFixedAssets = data.DepreOfFixedAssets;
                    item.OtherExpenses = data.OtherExpenses;
                    item.TheCostInTotal = data.TheCostInTotal;
                    item.TheCostCombined = data.TheCostCombined;
                    item.PersonExpendRatio = data.PersonExpendRatio;
                    item.NewPerformanceRatio = data.NewPerformanceRatio;
                    item.MedicinePropRatio = data.MedicinePropRatio;
                    item.MaterialCostsRatio = data.MaterialCostsRatio;
                    item.TotalMedicineRatio = data.TotalMedicineRatio;
                    item.DepreOfFixedAssetsRatio = data.DepreOfFixedAssetsRatio;
                    item.OtherExpensesRatio = data.OtherExpensesRatio;
                    item.TheCostInTotalRatio = data.TheCostInTotalRatio;
                    item.TheCostCombinedRatio = data.TheCostCombinedRatio;
                }

                perbudgetresultRepository.UpdateRange(results.ToArray());
            }

            var addData = request.Where(t => t.Id == 0);
            if (addData != null && addData.Any())
            {
                addData.ToList().ForEach(t =>
                {
                    t.CreateDate = DateTime.Now;
                    t.CreateUser = userId;
                });
                perbudgetresultRepository.AddRange(addData.ToArray());
            }

            return true;
        }

        /// <summary>
        /// 修改发放系数、调节系数使用状态
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public bool UseResult(int id)
        {
            var result = perbudgetresultRepository.GetEntity(t => t.Id == id);
            if (result == null)
                throw new PerformanceException("所选数据不存在!");
            result.States = 2;
            return perbudgetresultRepository.Update(result);
        }

        public void GetAdjust(int allotId, ref decimal adjust)
        {
            var allot = perallotRepository.GetEntity(t => t.ID == allotId);
            if (allot == null) return;

            var result = perbudgetresultRepository.GetEntity(t => t.HospitalId == allot.HospitalId && t.Year == allot.Year && t.Month == allot.Month);
            if (result == null || result.States != 2) return;

            adjust = result.Adjust.Value;
        }

        public void GetGrant(int allotId, ref decimal grant)
        {
            var allot = perallotRepository.GetEntity(t => t.ID == allotId);
            if (allot == null) return;

            var result = perbudgetresultRepository.GetEntity(t => t.HospitalId == allot.HospitalId && t.Year == allot.Year && t.Month == allot.Month);
            if (result == null || result.States != 2) return;

            grant = result.Grant.Value;
        }
    }
}
