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.Project;
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;

        public ProjectPriceService(IProjectRepository projectRepository, IProjectPriceRepository projectPriceRepository, IProjectConfigRepository projectConfigRepository)
        {
            _projectRepository = projectRepository;
            _projectPriceRepository = projectPriceRepository;
            _projectConfigRepository = projectConfigRepository;
        }
        #region 公司默认抽成比例
        /// <summary>
        /// 查询公司抽成比例
        /// </summary>        
        /// <returns></returns>
        [HttpGet]
        public async Task<CompanyDrawOutput> GetCompanyDrawAsync()
        {
            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 = current.DrawRatio;
                output.NextEffectDate = current.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.Where(m => 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
            });
        }
        #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 (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);
                await _projectPriceRepository.UpdateDiy.SetSource(new ProjectPriceEntity()
                {
                    DrawPriceWay = input.DrawPriceWay,
                    DrawRatio = input.DrawRatio,
                    DrawPrice = amount,
                    Id = price.Id
                }).UpdateColumns(a => new { a.DrawPriceWay, a.DrawRatio, a.DrawPrice, a.ModifiedTime }).ExecuteAffrowsAsync();
            }
            else if (input.DrawPriceWay == 2)
            {
                //抽成金额
                if (input.DrawPrice > price.Price || input.DrawPrice < 0)
                {
                    throw ResultOutput.Exception("设置有效的抽成金额");
                }
                await _projectPriceRepository.UpdateDiy.SetSource(new ProjectPriceEntity()
                {
                    DrawPriceWay = input.DrawPriceWay,
                    DrawRatio = 0,
                    DrawPrice = input.DrawPrice,
                    Id = price.Id
                }).UpdateColumns(a => new { a.DrawPriceWay, a.DrawRatio, a.DrawPrice, a.ModifiedTime }).ExecuteAffrowsAsync(); ;
            }
            else
            {
                throw ResultOutput.Exception("无效的设价方式！");
            }
            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("生效日期，最短为次日生效");
            }
        }
        #endregion
    }
}