using Microsoft.AspNetCore.Mvc;
using NPOI.SS.Formula.PTG;
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.Project;
using ZhonTai.Admin.Services.Project.Dto;
using ZhonTai.Admin.Services.Project;
using ZhonTai.Common.Extensions;
using ZhonTai.DynamicApi.Attributes;
using ZhonTai.DynamicApi;
using ZhonTai.Admin.Domain.ProjectAndTenant;
using ZhonTai.Admin.Domain.Org;
using ZhonTai.Admin.Services.ProjectAndTenant.Dto;
using NPOI.SS.Formula.Functions;

namespace ZhonTai.Admin.Services.ProjectAndTenant
{
    /// <summary>
    /// 平台项目价格设置服务
    /// </summary>
    [Order(10)]
    [DynamicApi(Area = AdminConsts.AreaName)]
    public partial class ProjectAndTenantService : BaseService, IProjectService, IDynamicApi
    {
        private readonly IProjectPriceRepository _projectPriceRepository;
        private readonly IProjectAndTenantRepository _projectAndTenantRepository;
        private readonly IOrgRepository _orgRepository;

        public ProjectAndTenantService(IProjectPriceRepository projectPriceRepository, IProjectAndTenantRepository projectAndTenantRepository, IOrgRepository orgRepository)
        {
            _projectPriceRepository = projectPriceRepository;
            _projectAndTenantRepository = projectAndTenantRepository;
            _orgRepository = orgRepository;
        }

        /// <summary>
        /// 查询分页
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<PageOutput<ProjectAndTenatntGetPageOutput>> GetPageAsync(PageInput<ProjectAndTenantGetPageInput> 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 ProjectAndTenatntGetPageOutput()
            {
                Id = a.TenantId.Value,
                Name = a.Name,
                prices = _projectAndTenantRepository.Select.DisableGlobalFilter(FilterNames.Tenant).Where(m => m.ProjectId == projectId && m.TenantId == a.TenantId).ToList<ProjectAndTenatntGetPageOutput_Price>()
            });

            foreach (var item in list)
            {
                List<ProjectAndTenatntGetPageOutput_Price> prices = new List<ProjectAndTenatntGetPageOutput_Price>();
                foreach (var it in projectprice)
                {
                    var tprice = item.prices.Where(m => m.ProjectPriceId == it.Id).FirstOrDefault();
                    if (tprice != null)
                    {
                        prices.Add(new ProjectAndTenatntGetPageOutput_Price()
                        {
                            Id = tprice.Id,
                            Name = it.Name,
                            Price = it.Price,
                            ProjectPriceId = tprice.ProjectPriceId,
                            DrawPriceWay = tprice.DrawPriceWay,
                            DrawRatio = tprice.DrawRatio,
                            DrawPrice = tprice.DrawPrice
                        });
                    }
                    else
                    {
                        prices.Add(new ProjectAndTenatntGetPageOutput_Price()
                        {
                            Id = 0,
                            Name = it.Name,
                            Price = it.Price,
                            ProjectPriceId = it.Id,
                            DrawPriceWay = 0
                        });
                    }
                }
                item.prices = prices;
            }

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

            return data;
        }
        /// <summary>
        /// 平台项目设置价格
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<long> SetPriceAsync(ProjectAndTenantSetInput input)
        {
            ProjectAndTenantEntity tprice = new ProjectAndTenantEntity();
            if (input.Id > 0)
            {
                tprice = await _projectAndTenantRepository.Select.DisableGlobalFilter(FilterNames.Tenant).Where(m => m.Id == input.Id).ToOneAsync();
                if (tprice == null)
                {
                    throw ResultOutput.Exception("信息不存在,请刷新后重试！");
                }
            }
            else {
                tprice = await _projectAndTenantRepository.Select.DisableGlobalFilter(FilterNames.Tenant).Where(m => m.TenantId == input.TenatntId && m.ProjectPriceId == input.ProjectPriceId).FirstAsync();                
            }
            //验证项目价格信息是否存在
            var price = await _projectPriceRepository.GetAsync(input.ProjectPriceId);
            if (!(price?.Id > 0))
            {
                throw ResultOutput.Exception("项目信息不存在,请刷新后重试！");
            }

            if (input.DrawPriceWay == 1)
            {
                //抽成比例
                if (input.DrawRatio < 0 || input.DrawRatio > 100)
                {
                    throw ResultOutput.Exception("抽成比例有效范围在0-100");
                }
                var amount = UtilConvertExtension.ToDecimalCutWithN(price.Price * input.DrawRatio * 0.01m, 0, 1);
                if (tprice != null)
                {
                    await _projectAndTenantRepository.UpdateDiy.DisableGlobalFilter(FilterNames.Tenant).SetSource(new ProjectAndTenantEntity()
                    {
                        DrawPriceWay = input.DrawPriceWay,
                        DrawRatio = input.DrawRatio,
                        DrawPrice = amount,
                        Id = tprice.Id                       
                    }).UpdateColumns(a => new { a.DrawPriceWay, a.DrawRatio, a.DrawPrice, a.ModifiedTime }).ExecuteAffrowsAsync();
                }
                else
                {
                    await _projectAndTenantRepository.InsertAsync(new ProjectAndTenantEntity()
                    {
                        DrawPriceWay = input.DrawPriceWay,
                        DrawRatio = input.DrawRatio,
                        DrawPrice = amount,
                        TenantId = input.TenatntId,
                        ProjectId = price.ProjectId,
                        ProjectPriceId = price.Id
                    });
                }

            }
            else if (input.DrawPriceWay == 2)
            {
                if (tprice != null)
                {
                    //抽成金额
                    if (input.DrawPrice > price.Price || input.DrawPrice < 0)
                    {
                        throw ResultOutput.Exception("设置有效的抽成金额");
                    }
                    await _projectAndTenantRepository.UpdateDiy.DisableGlobalFilter(FilterNames.Tenant).SetSource(new ProjectAndTenantEntity()
                    {
                        DrawPriceWay = input.DrawPriceWay,
                        DrawRatio = 0,
                        DrawPrice = input.DrawPrice,
                        Id = tprice.Id                        
                    }).UpdateColumns(a => new { a.DrawPriceWay, a.DrawRatio, a.DrawPrice, a.ModifiedTime }).ExecuteAffrowsAsync();
                }
                else
                {
                    await _projectAndTenantRepository.InsertAsync(new ProjectAndTenantEntity()
                    {
                        DrawPriceWay = input.DrawPriceWay,
                        DrawRatio = 0,
                        DrawPrice = input.DrawPrice,
                        TenantId = input.TenatntId,
                        ProjectId = price.ProjectId,
                        ProjectPriceId = price.Id
                    });
                }
            }
            else
            {
                throw ResultOutput.Exception("无效的设价方式！");
            }
            return 1;
        }
        /// <summary>
        /// 初始化抽成信息
        /// </summary>        
        /// <returns></returns>
        public async Task<long> SetPriceInitAsync()
        {
            ProjectAndTenantEntity tprice = new ProjectAndTenantEntity();
            var count= await _projectAndTenantRepository.Select.Where(m => m.SetType == 1).CountAsync();
            if (count<=0)
            {
                await _projectAndTenantRepository.InsertAsync(new ProjectAndTenantEntity()
                {
                    ProjectId = 0,
                    ProjectPriceId = 0,
                    SetType = 1,
                    EffectDate = DateTime.Now,
                    TenantId = 0,
                });
            }           
            return 1;
        }
        /// <summary>
        /// 整体抽成更新
        /// </summary>        
        /// <returns></returns>
        public async Task<long> SetPriceUpdateToGlobalAsync()
        {
            ProjectAndTenantEntity tprice = new ProjectAndTenantEntity();
            var project = await _projectAndTenantRepository.Select.Where(m => m.SetType == 1).ToOneAsync();
            //if (count > 0)
            //{
            //    await _projectAndTenantRepository.UpdateAsync(new ProjectAndTenantEntity()
            //    {
            //        ProjectId = 0,
            //        ProjectPriceId = 0,
            //        SetType = 1,
            //        EffectDate = DateTime.Now,
            //        TenantId = -1,
            //    });
            //}
         
            return 1;
        }
    }
}