using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Transactions;
using AutoMapper;
using GxPress.Common.AppOptions;
using GxPress.Common.Exceptions;
using GxPress.Common.Page;
using GxPress.Common.Tools;
using GxPress.Entity;
using GxPress.Repository.Interface;
using GxPress.Request.Sell;
using GxPress.Request.Storehouse;
using GxPress.Result.HumanAffairs;
using GxPress.Result.Storehouse;
using Microsoft.Extensions.Options;
using Datory;

namespace GxPress.Repository.Implement
{
    public class StorehouseRepository : IStorehouseRepository
    {
        private readonly Repository<Storehouse> _repository;

        public StorehouseRepository(IOptionsMonitor<DatabaseOptions> dbOptionsAccessor, IMapper mapper)
        {
            var databaseType = StringUtils.ToEnum<DatabaseType>(dbOptionsAccessor.CurrentValue.DatabaseType, DatabaseType.MySql);
            var database = new Database(databaseType, dbOptionsAccessor.CurrentValue.ConnectionString);
            _repository = new Repository<Storehouse>(database);
        }

        public IDatabase Database => _repository.Database;
        public string TableName => _repository.TableName;
        public List<TableColumn> TableColumns => _repository.TableColumns;

        /// <summary>
        /// 添加库存记录
        /// </summary>
        /// <param name="storehouses"></param>
        /// <returns></returns>
        public async Task<bool> InsertAsync(IEnumerable<Storehouse> storehouses)
        {
            try
            {
                using (TransactionScope transactionScope = new TransactionScope())
                {
                    foreach (var storehouse in storehouses)
                    {
                        await _repository.InsertAsync(storehouse);
                    }

                    transactionScope.Complete();
                }
            }
            catch (Exception e)
            {
                throw new BusinessException(e.Message);
            }

            return true;
        }

        public async Task<PagedList<Storehouse>> GetPageListAsync(PageParameter request)
        {
            var result = new PagedList<Storehouse>
            {
                Items = await _repository.GetAllAsync(Q.ForPage(request.Page, request.PerPage)),
                Total = await _repository.CountAsync()
            };
            return result;
        }
        /// <summary>
        /// 库存图像
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public async Task<StorehouseResult> GetStorehouseChartAsync(StorehouseRequest request)
        {
            var result = new StorehouseResult();
            //获取当前时间
            DateTime dt = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd"));
            //当前星期几
            int weekNow = Convert.ToInt32(DateTime.Now.DayOfWeek);
            result.HumanAffairsChartDataResult = new List<HumanAffairsChartData>();
            //收入
            //上月
            var a = await _repository.GetAllAsync(Q
                .WhereDate(nameof(Storehouse.EnteringDateTime), "<=", dt.AddDays(-dt.Day))
                .WhereDate(nameof(Storehouse.EnteringDateTime), ">=",
                    dt.AddDays(-dt.Day).AddMonths(1)));
            //本月
            var b = await _repository.GetAllAsync(Q
                .WhereDate(nameof(Storehouse.EnteringDateTime), "<=", dt)
                .WhereDate(nameof(Storehouse.EnteringDateTime), ">=",
                    dt.AddDays(-dt.Day)));
            //今天
            var c = await _repository.GetAllAsync(Q.WhereDate(nameof(Storehouse.EnteringDateTime), "<=", dt)
                .WhereDate(nameof(Storehouse.EnteringDateTime), ">=", dt.AddHours(-dt.Hour)));
            //同比增长
            result.ComparedMonthCount = b.Sum(n => n.StorehouseCount) - a.Sum(n => n.StorehouseCount);
            //当月多少库存
            result.Monthcount = c.Sum(n => n.StorehouseCount);
            var storehouseList = await _repository.GetAllAsync();
            result.StorehouseAllCount = storehouseList.Sum(n => n.StorehouseCount);
            //计算周
            if (request.DateType == 2)
            {
                var beginDat = dt;
                for (int i = 1; i <= 7; i++)
                {
                    var week = (i - 1) * 7;
                    var endDay = beginDat.AddDays(-weekNow + week + 1);
                    var query = Q.NewQuery();
                    var humanAffairsWeekList = await _repository.GetAllAsync(query
                        .WhereDate(nameof(Storehouse.EnteringDateTime), "<=", beginDat)
                        .WhereDate(nameof(Storehouse.EnteringDateTime), ">=", endDay));
                    var humanAffairsChartData = new HumanAffairsChartData
                    {
                        NavigationNumber = i,
                        ResultParameter = humanAffairsWeekList.Sum(n => n.StorehouseCount)
                    };
                    result.HumanAffairsChartDataResult.Add(humanAffairsChartData);
                    beginDat = endDay;
                }
            }

            //天数
            if (request.DateType == 1)
            {
                var beginDat = dt;
                for (int i = 1; i <= 7; i++)
                {

                    var endDay = beginDat.AddDays(-1);
                    var query = Q.NewQuery();
                    var humanAffairsDayList = await _repository.GetAllAsync(query
                        .WhereDate(nameof(Storehouse.EnteringDateTime), "<=", beginDat)
                        .WhereDate(nameof(Storehouse.EnteringDateTime), ">=", endDay));
                    var humanAffairsChartData = new HumanAffairsChartData
                    {
                        NavigationNumber = i,
                        ResultParameter = humanAffairsDayList.Sum(n => n.StorehouseCount)
                    };
                    result.HumanAffairsChartDataResult.Add(humanAffairsChartData);
                    beginDat = endDay;
                }
            }

            //月
            if (request.DateType == 3)
            {
                var beginDat = dt;
                for (int i = 1; i <= 7; i++)
                {
                    var days = beginDat.Day;
                    var endDay = dt.AddDays(-days).AddMonths(-1);
                    var query = Q.NewQuery();
                    var humanAffairsMonthList = await _repository.GetAllAsync(query
                        .WhereDate(nameof(Storehouse.EnteringDateTime), "<=", beginDat)
                        .WhereDate(nameof(Storehouse.EnteringDateTime), ">=", endDay));
                    var humanAffairsChartData = new HumanAffairsChartData
                    {
                        NavigationNumber = i,
                        ResultParameter = humanAffairsMonthList.Sum(n => n.StorehouseCount)
                    };
                    result.HumanAffairsChartDataResult.Add(humanAffairsChartData);
                    beginDat = endDay;
                }
            }

            //年
            if (request.DateType == 4)
            {
                var beginDat = dt;
                for (int i = 1; i <= 7; i++)
                {
                    var days = beginDat.DayOfYear;
                    var endDay = dt.AddDays(-days).AddYears(-1);
                    var query = Q.NewQuery();
                    var humanAffairsYearList = await _repository.GetAllAsync(query
                        .WhereDate(nameof(Storehouse.EnteringDateTime), "<=", beginDat)
                        .WhereDate(nameof(Storehouse.EnteringDateTime), ">=", endDay));
                    var humanAffairsChartData = new HumanAffairsChartData
                    {
                        NavigationNumber = i,
                        ResultParameter = humanAffairsYearList.Sum(n => n.StorehouseCount)
                    };
                    result.HumanAffairsChartDataResult.Add(humanAffairsChartData);
                    beginDat = endDay;
                }
            }

            //支出

            return result;

        }
    }
}
