using APT.BaseData.Domain.Entities.OP;
using APT.BaseData.Domain.Enums.OP;
using APT.Infrastructure.Core;
using APT.Utility;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Linq;

namespace APT.OP.WebApi.Controllers.Api
{
    [Route("api/OP/OPRechargeOrder")]
    public partial class RechargeOrderController : AuthorizeApiController<T_OP_RECHARGE_ORDER>
    {
        /// <summary>
        /// 排序分页查询数据
        /// </summary>
        /// <param name="pageFilter">分页过滤实体</param>
        /// <returns></returns>
        [HttpPost, Route("FullOrderPaged")]
        public PagedActionResult<T_OP_RECHARGE_ORDER> FullOrderPaged([FromBody] KeywordPageFilter pageFilter)
        {
            return SafeGetPagedData<T_OP_RECHARGE_ORDER>((result) =>
            {
                result = this.GetOrderPageEntities<T_OP_RECHARGE_ORDER>(null, pageFilter);
            });
        }

        /// <summary>
        /// 查询充值卡收支明细
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        [HttpPost, Route("OrderPageDetail")]
        public PagedActionResult<T_OP_RECHARGE_ORDER> OrderPageDetail([FromBody] KeywordPageFilter filter)
        {
            if (filter.FilterGroup.Rules.Count == 0)
                return WitOrderPaged(null, filter);
            var str = filter.FilterGroup.Rules.FirstOrDefault();
            filter.FilterGroup = new FilterGroup();
            if (str.Field == "Parameter1")
            {
                var cardId = Guid.Parse(str.Value.ToString());
                return WitOrderPaged(x => x.RECHARGE_CARD_ID == cardId, filter);
            }
            else if (str.Field == "Time")
            {
                var time = DateTime.Parse(str.Value.ToString());
                return WitOrderPaged(x => x.TIME.Year == time.Year && x.TIME.Month == time.Month && x.ORDER_STATUS == (int)OPRechargeOrderStatus.成功, filter);
            }
            else if (str.Field == "Code")
            {
                var code = str.Value.ToString();
                var member = GetEntity<T_OP_MEMBER>(x => x.CODE == code);
                if (member?.RECHARGE_CARD_ID != null)
                    return WitOrderPaged(x => x.RECHARGE_CARD_ID == member.RECHARGE_CARD_ID && x.ORDER_STATUS == (int)OPRechargeOrderStatus.成功, filter);
            }
            return null;
        }

        /// <summary>
        /// 充值订单对账功能
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        [HttpPost, Route("RechargeOrderReconciliation")]
        public JsonActionResult<dynamic> RechargeOrderReconciliation([FromBody] KeywordFilter filter)
        {
            return SafeExecute(() =>
            {
                dynamic result = new ExpandoObject();
                if (filter.Parameter1 == null)
                    return result;
                var timeStr = filter.Parameter1.Split(",");
                if (timeStr.Length != 2)
                    return result;
                var startTime = DateTime.Parse(timeStr[0]);
                var endTime = DateTime.Parse(timeStr[1]);
                var head = new List<TableHeadModel>
                {
                    new TableHeadModel{ Title = "时间", DataIndex = "Time"},
                    new TableHeadModel{ Title = "充值次数", DataIndex = "Recharge_Num"},
                    new TableHeadModel{ Title = "充值金额", DataIndex = "Recharge_Amount"},
                };
                var dicList = new List<Dictionary<string, object>>();
                filter.SelectField = new string[] { "AMOUNT", "ENERGY_USED", "TIME", "ORDER_STATUS" };
                var details = GetEntities<T_OP_RECHARGE_ORDER>(x => x.ORDER_STATUS == (int)OPRechargeOrderStatus.成功 && x.TIME >= startTime && x.TIME < endTime.AddMonths(1), filter);
                while (startTime <= endTime)
                {
                    var detail = details.Where(x => x.TIME.ToIMonth() == startTime.ToIMonth());
                    var dic = new Dictionary<string, object>
                    {
                        {"Time", startTime.ToString("yyyy-MM") },
                        {"Recharge_Num", detail.Count() },
                        {"Recharge_Amount", detail?.Select(x=>x.AMOUNT).Sum() },
                    };
                    dicList.Add(dic);
                    startTime = startTime.AddMonths(1);
                }
                result.head = head;
                result.dataSource = dicList;

                return result;
            });
        }

        /// <summary>
        /// 会员支付信息统计
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        [HttpPost, Route("MemberRecharge")]
        public JsonActionResult<dynamic> MemberRecharge([FromBody] KeywordFilter filter)
        {
            return SafeExecute(() =>
            {
                dynamic result = new ExpandoObject();
                var code = filter.Parameter1;
                var name = filter.Parameter2;
                var head = new List<TableHeadModel>
                {
                    new TableHeadModel{ Title = "会员编码", DataIndex = "Code"},
                    new TableHeadModel{ Title = "会员名称", DataIndex = "Name"},
                    new TableHeadModel{ Title = "充值次数", DataIndex = "Recharge_Num"},
                    new TableHeadModel{ Title = "充值金额", DataIndex = "Recharge_Amount"},
                    new TableHeadModel{ Title = "剩余金额", DataIndex = "Balance"},
                };
                var dicList = new List<Dictionary<string, object>>();
                filter.SelectField = new string[] { "CODE", "NAME", "RECHARGE_CARD_ID", "Nav_RechargeCard.BALANCE" };
                var member = GetEntities<T_OP_MEMBER>(x => x.RECHARGE_CARD_ID != null, filter);
                if (code != null)
                    member = member.Where(x => x.CODE.Contains(code));
                if (name != null)
                    member = member.Where(x => x.NAME.Contains(name));

                filter.SelectField = new string[] { "AMOUNT", "RECHARGE_CARD_ID", "METHOD" };
                var details = GetEntities<T_OP_RECHARGE_ORDER>(x => x.ORDER_STATUS == (int)OPRechargeOrderStatus.成功 && member.Select(y => y.RECHARGE_CARD_ID).Contains(x.RECHARGE_CARD_ID), filter);
                foreach (var item in member)
                {
                    var detail = details.Where(x => x.RECHARGE_CARD_ID == item.RECHARGE_CARD_ID);
                    var dic = new Dictionary<string, object>
                    {
                        {"Code", item.CODE },
                        {"Name", item.NAME },
                        {"Recharge_Num", detail?.Count() },
                        {"Recharge_Amount", detail?.Select(x=>x.AMOUNT).Sum() },
                        {"Balance", item.Nav_RechargeCard.BALANCE }
                    };
                    dicList.Add(dic);
                }
                result.head = head;
                result.dataSource = dicList;

                return result;
            });
        }

    }
}
