using Microsoft.AspNetCore.Mvc;
using NPOI.SS.Formula.Functions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ZhonTai.Admin.Core.Consts;
using ZhonTai.Admin.Core.Dto;
using ZhonTai.Admin.Domain.Org;
using ZhonTai.Admin.Domain.Project;
using ZhonTai.Admin.Domain.Tenant;
using ZhonTai.Admin.Services.Project.Dto;
using ZhonTai.Common.Extensions;
using ZhonTai.DynamicApi;
using ZhonTai.DynamicApi.Attributes;

namespace ZhonTai.Admin.Services.Project
{
    /// <summary>
    /// 项目价格设置服务
    /// </summary>
    [Order(10)]
    [DynamicApi(Area = AdminConsts.AreaName)]
    public partial class ProjectPriceService : BaseService, IProjectService, IDynamicApi
    {
        private readonly IProjectRepository _projectRepository;
        private readonly IProjectPriceRepository _projectPriceRepository;
        private readonly IProjectConfigRepository _projectConfigRepository;
        private readonly IOrgRepository _orgRepository;
        private readonly ITenantRepository _tenantRepository;

        public ProjectPriceService(IProjectRepository projectRepository, IProjectPriceRepository projectPriceRepository, IProjectConfigRepository projectConfigRepository, IOrgRepository orgRepository, ITenantRepository tenantRepository)
        {
            _projectRepository = projectRepository;
            _projectPriceRepository = projectPriceRepository;
            _projectConfigRepository = projectConfigRepository;
            _orgRepository = orgRepository;
            _tenantRepository = tenantRepository;
        }
        #region 公司默认抽成比例
        /// <summary>
        /// 查询公司抽成比例
        /// </summary>        
        /// <returns></returns>
        [HttpGet]
        public async Task<CompanyDrawOutput> GetCompanyDrawAsync()
        {
            await ProjectPriceInitAsync();

            var list = await _projectConfigRepository.Select.Where(m => m.ProjectId == 0 && m.ProjectPriceId == 0 && m.Status == 1)
            .ToListAsync(a => new
            {
                a.Id,
                a.DrawRatio,
                a.EffectDate
            });
            CompanyDrawOutput output = new CompanyDrawOutput();
            if (list.Count > 1)
            {
                DateTime dtnow = DateTime.Today;
                var current = list.FirstOrDefault(m => m.EffectDate <= dtnow);
                var next = list.FirstOrDefault(m => m.EffectDate > dtnow);
                output.CurrentRatio = current.DrawRatio;
                output.NextRatio = next.DrawRatio;
                output.NextEffectDate = next.EffectDate;
            }
            else
            {
                output.CurrentRatio = list[0].DrawRatio;
                output.NextRatio = 0;
            }
            return output;
        }
        /// <summary>
        /// 修改公司抽成比例
        /// </summary>        
        /// <returns></returns>
        [HttpPost]
        public async Task EditCompanyDrawAsync(CompanyDrawInput input)
        {
            CheckDrawRatio(input.DrawRatio);

            CheckDrawRatioEffect(input.EffectDate);

            //删除旧的未生效记录
            var listDeleteId = await _projectConfigRepository.Select.DisableGlobalFilter(FilterNames.Tenant).Where(m => m.DrawType == 1 && m.ProjectId == 0 && m.ProjectPriceId == 0 && m.Status == 1 && m.EffectDate > DateTime.Today)
            .ToListAsync(m => m.Id);
            if (listDeleteId.Count > 0)
            {
                await _projectConfigRepository.SoftDeleteAsync(m => listDeleteId.Contains(m.Id));
            }
            //添加新的比例
            await _projectConfigRepository.InsertAsync(new ProjectConfigEntity()
            {
                ProjectId = 0,
                ProjectPriceId = 0,
                DrawRatio = input.DrawRatio,
                EffectDate = input.EffectDate,
                Status = 1,
                DrawType = 1,
                DrawWay = 1,
                TenantId = 0
            });
        }
        #endregion

        #region 公司设置项目抽成比例
        /// <summary>
        /// 查询项目分页
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<PageOutput<GetProjectPricePageOutput>> GetProjectPageAsync(PageInput<GetProjectPricePageInput> input)
        {
            var list = await _projectRepository.Select
            .Count(out var total)
            .OrderByDescending(true, a => a.Id)
            .Page(input.CurrentPage, input.PageSize)
            .ToListAsync(a => new GetProjectPricePageOutput()
            {
                Id = a.Id,
                Name = a.Name,
                Logo = a.Logo,
                Prices = _projectPriceRepository.Select.Where(m => m.ProjectId == a.Id).ToList<PriceGetPageOutput_Price>()
            });

            var data = new PageOutput<GetProjectPricePageOutput>()
            {
                List = Mapper.Map<List<GetProjectPricePageOutput>>(list),
                Total = total
            };

            return data;
        }
        /// <summary>
        /// 项目价格设价
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<long> SetProjectPriceAsync(ProjectPriceSetInput input)
        {
            //验证项目价格信息是否存在
            var price = await _projectPriceRepository.GetAsync(input.Id);
            if (!(price?.Id > 0))
            {
                throw ResultOutput.Exception("信息不存在,请刷新后重试！");
            }
            if (!new int[] { 1, 2 }.Contains(input.DrawPriceWay))
            {
                throw ResultOutput.Exception("无效的设价方式！");
            }
            decimal amount = input.DrawPrice;
            if (input.DrawPriceWay == 1)
            {
                CheckDrawRatio(input.DrawRatio);

                amount = GetDrawAmount(price.Price, input.DrawRatio);
            }
            else if (input.DrawPriceWay == 2)
            {
                //抽成金额
                if (input.DrawPrice > price.Price || input.DrawPrice < 0)
                {
                    throw ResultOutput.Exception("设置有效的抽成金额");
                }
            }
            //覆盖已经存在未生效的
            var listDeleteId = await _projectConfigRepository.Select.DisableGlobalFilter(FilterNames.Tenant).Where(m => m.ProjectId == price.ProjectId && m.ProjectPriceId == price.Id && m.Status == 1 && m.EffectDate > DateTime.Today && m.DrawType == 2)
           .ToListAsync(m => m.Id);
            if (listDeleteId.Count > 0)
            {
                await _projectConfigRepository.SoftDeleteAsync(m => listDeleteId.Contains(m.Id));
            }

            //新增
            var effectDate = input.EffectDate.HasValue ? input.EffectDate : DateTime.Today.AddDays(1);
            await _projectConfigRepository.InsertAsync(new ProjectConfigEntity()
            {
                ProjectId = price.ProjectId,
                ProjectPriceId = price.Id,
                Status = 1,
                DrawWay = input.DrawPriceWay,
                DrawRatio = input.DrawRatio,
                DrawAmount = amount,
                EffectDate = effectDate,
                DrawType = 2,
                TenantId = 0
            });
            return 1;
        }
        #endregion

        #region 公司设置平台抽成比例
        /// <summary>
        /// 查询平台单独设价分页
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<PageOutput<TenantPriceGetPageOutput>> GetTenantDrawPageAsync(PageInput<TenantPriceGetPageInput> input)
        {
            var projectId = input?.Filter?.ProjectId;
            if (!projectId.HasValue)
            {
                projectId = 0;
            }
            //项目价格信息
            var projectprice = _projectPriceRepository.Select.DisableGlobalFilter(FilterNames.Tenant).Where(m => m.ProjectId == projectId).ToList(m => new
            {
                m.Id,
                m.Name,
                m.Price
            });
            //平台信息
            var list = await _orgRepository.Select.DisableGlobalFilter(FilterNames.Tenant)
            .Count(out var total)
            .OrderByDescending(true, a => a.Id)
            .Page(input.CurrentPage, input.PageSize)
            .ToListAsync(a => new TenantPriceGetPageOutput()
            {
                Id = a.TenantId.Value,
                Name = a.Name,
                prices = _projectConfigRepository.Select.DisableGlobalFilter(FilterNames.Tenant).Where(m => m.ProjectId == projectId && m.TenantId == a.TenantId && m.Status == 1 & m.DrawType == 3).ToList<TenantPriceGetPageOutput_Price>()
            });
            //项目信息同平台信息合并
            foreach (var item in list)
            {
                List<TenantPriceGetPageOutput_Price> prices = new List<TenantPriceGetPageOutput_Price>();
                foreach (var it in projectprice)
                {
                    var tprice = item.prices.Where(m => m.ProjectPriceId == it.Id).FirstOrDefault();
                    if (tprice != null)
                    {
                        prices.Add(new TenantPriceGetPageOutput_Price()
                        {
                            ProjectId = tprice.ProjectId,
                            ProjectPriceId = tprice.ProjectPriceId,
                            Name = it.Name,
                            Price = it.Price,
                            DrawPriceWay = tprice.DrawPriceWay,
                            DrawRatio = tprice.DrawRatio,
                            DrawPrice = tprice.DrawPrice
                        });
                    }
                    else
                    {
                        prices.Add(new TenantPriceGetPageOutput_Price()
                        {
                            ProjectId = projectId.Value,
                            ProjectPriceId = it.Id,
                            Name = it.Name,
                            Price = it.Price,
                            DrawPriceWay = 0
                        });
                    }
                }
                item.prices = prices;
            }

            var data = new PageOutput<TenantPriceGetPageOutput>()
            {
                List = Mapper.Map<List<TenantPriceGetPageOutput>>(list),
                Total = total
            };

            return data;
        }
        /// <summary>
        /// 平台项目设置价格
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<long> SetTenantDrawAsync(TenantDrawSetInput input)
        {
            if (!new[] { 1, 2 }.Contains(input.DrawPriceWay))
            {
                throw ResultOutput.Exception("无效的设价方式！");
            }
            //验证平台是否存在
            var tenant = await _tenantRepository.GetAsync(input.TenatntId);
            if (!(tenant?.Id > 0))
            {
                throw ResultOutput.Exception("平台不存在,请刷新后重试！");
            }

            //验证项目价格信息是否存在
            var price = await _projectPriceRepository.GetAsync(input.ProjectPriceId);
            if (!(price?.Id > 0))
            {
                throw ResultOutput.Exception("项目信息不存在,请刷新后重试！");
            }
           
            var amount = input.DrawPrice;
            if (input.DrawPriceWay == 1)
            {
                //抽成比例
                CheckDrawRatio(input.DrawRatio);

                amount = GetDrawAmount(price.Price, input.DrawRatio);

            }
            else if (input.DrawPriceWay == 2)
            {
                //抽成金额
                if (input.DrawPrice > price.Price || input.DrawPrice < 0)
                {
                    throw ResultOutput.Exception("设置有效的抽成金额");
                }               

            }

            //覆盖已经存在未生效的
            var listDeleteId = await _projectConfigRepository.Select.DisableGlobalFilter(FilterNames.Tenant).Where(m => m.ProjectId == price.ProjectId && m.ProjectPriceId == price.Id && m.Status == 1 && m.EffectDate > DateTime.Today && m.DrawType == 3)
           .ToListAsync(m => m.Id);
            if (listDeleteId.Count > 0)
            {
                await _projectConfigRepository.SoftDeleteAsync(m => listDeleteId.Contains(m.Id));
            }

            //新增
            var effectDate = input.EffectDate.HasValue ? input.EffectDate : DateTime.Today.AddDays(1);
            await _projectConfigRepository.InsertAsync(new ProjectConfigEntity()
            {
                ProjectId = price.ProjectId,
                ProjectPriceId = price.Id,
                Status = 1,
                DrawWay = input.DrawPriceWay,
                DrawRatio = input.DrawRatio,
                DrawAmount = amount,
                EffectDate = effectDate,
                DrawType = 3,
                TenantId = input.TenatntId
            });


            return 1;
        }
        #endregion


        #region 校验
        /// <summary>
        /// 校验抽成比例
        /// </summary>
        /// <param name="drawRatio"></param>
        private void CheckDrawRatio(decimal drawRatio)
        {
            //抽成比例
            if (drawRatio < 0 || drawRatio > 100)
            {
                throw ResultOutput.Exception("抽成比例有效范围在0-100");
            }
        }
        /// <summary>
        /// 校验抽成比例生效时间
        /// </summary>
        /// <param name="effectDate"></param>
        private void CheckDrawRatioEffect(DateTime effectDate)
        {
            //生效时间
            if (effectDate <= DateTime.Today)
            {
                throw ResultOutput.Exception("生效日期，最短为次日生效");
            }
        }
        /// <summary>
        /// 抽成金额
        /// </summary>

        private decimal GetDrawAmount(decimal price, decimal ratio)
        {
            var amount = UtilConvertExtension.ToDecimalCutWithN(price * ratio * 0.01m, 0, 1);
            return amount;
        }
        /// <summary>
        /// 初始化公司抽成信息
        /// </summary>        
        /// <returns></returns>
        private async Task ProjectPriceInitAsync()
        {
            var count = await _projectConfigRepository.Select.Where(m => m.ProjectId == 0 && m.ProjectPriceId == 0).CountAsync();
            if (count <= 0)
            {
                await _projectConfigRepository.InsertAsync(new ProjectConfigEntity()
                {
                    ProjectId = 0,
                    ProjectPriceId = 0,
                    DrawRatio = 5,
                    EffectDate = DateTime.Today,
                    Status = 1
                });
            }
        }
        #endregion
    }
}