using Mall.Common;
using Mall.Common.Plugin;
using Mall.Model.Entity.Finance;
using Mall.Model.Extend.Finance;
using Mall.Model.Extend.Product;
using Mall.Repository.Finance;
using Mall.Repository.Product;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Mall.WindowsService.Module
{
    public class FinanceModule
    {
        /// <summary>
        /// 财务单据规则
        /// </summary>
        private static RB_Finance_ConfigurineRepository financeConfigurineRepository = new RB_Finance_ConfigurineRepository();

        /// <summary>
        /// 财务生成记录
        /// </summary>
        private static RB_Finance_RecordRepository financeRecordRepository = new RB_Finance_RecordRepository();
        /// <summary>
        /// 财务生成记录详情
        /// </summary>
        private static RB_Finance_RecordDetailRepository financeRecordDetailRepository = new RB_Finance_RecordDetailRepository();

        /// <summary>
        /// 订单详情
        /// </summary>
        private static RB_Goods_OrderDetailRepository goodsOrderDetailRepository = new RB_Goods_OrderDetailRepository();
        #region 收入

        /// <summary>
        /// 订单收入单据
        /// </summary>
        /// <returns></returns>
        public static bool OrderIncomeFinanceModule()
        {
            var flag = false;

            try
            {
                //先查询规则
                var financeConfigurineList = financeConfigurineRepository.GetList(new Model.Extend.Finance.RB_Finance_Configurine_Extend { Type = 1 });

                //根据规则中的小程序，查询订单详情信息
                if (financeConfigurineList != null && financeConfigurineList.Any())
                {
                    foreach (var item in financeConfigurineList)
                    {
                        if (item.StartTime.HasValue && item.StartTime < System.DateTime.Now)//判断开始时间是否大于当前时间
                        {
                            //查询今天是否已经生成了财务单据
                            var addFinance = false;

                            DateTime startDate = System.DateTime.Now.AddDays(-1);
                            var recordModel = financeRecordRepository.GetList(new Model.Extend.Finance.RB_Finance_Record_Extend { TenantId = item.TenantId, MallBaseId = item.MallBaseId }).OrderByDescending(x => x.CreateDate).FirstOrDefault();
                            if (recordModel == null)//今天没生成单据
                            {
                                if (Convert.ToDateTime(item.StartTime.Value.AddDays(item.IntervalDay ?? 0).ToString("yyyy-MM-dd 00:00:00")) <= Convert.ToDateTime(System.DateTime.Now.ToString("yyyy-MM-dd 00:00:00")))//判断开始时间加上执行周期是否等于当前日期
                                {
                                    startDate = item.StartTime.Value;
                                    addFinance = true;
                                }
                            }
                            else
                            {
                                if (Convert.ToDateTime(recordModel.CreateDate.Value.AddDays(item.IntervalDay ?? 0).ToString("yyyy-MM-dd 00:00:00")) <= Convert.ToDateTime(System.DateTime.Now.ToString("yyyy-MM-dd 00:00:00")))//判断最近一次执行的时间加上执行周期是否等于当前日期
                                {
                                    startDate = recordModel.CreateDate.Value;
                                    addFinance = true;
                                }
                            }
                            DateTime endDate = startDate.AddDays(item.IntervalDay ?? 0);//结束时间
                            if (addFinance)//满足今天执行的条件查询间隔周期的订单
                            {
                                StringBuilder builder = new StringBuilder();
                                builder.AppendFormat($@" SELECT a.*,b.OrderNo from rb_goods_orderdetail as a LEFT JOIN rb_goods_order as b on a.OrderId=b.OrderId
where b.TenantId=1 and b.MallBaseId=1  and  DATE_FORMAT(b.CreateDate,'%y-%m-%d')<DATE_FORMAT('{startDate}','%y-%m-%d') 
and  DATE_FORMAT(b.CreateDate,'%y-%m-%d')<DATE_FORMAT('{endDate}','%y-%m-%d') and b.OrderStatus in(2,3,4,5,6)  ");
                                var goodsDetailList = goodsOrderDetailRepository.Get<RB_Goods_OrderDetail_Extend>(builder.ToString()).ToList();

                                var result = new List<RB_Goods_OrderDetail_Extend>();

                                RB_Finance_Record_Extend record = new RB_Finance_Record_Extend();
                                record.MallBaseId = item.MallBaseId;
                                record.TenantId = item.TenantId;
                                record.Type = 1;
                                record.CreateDate = System.DateTime.Now;
                                record.RecordDetailList = new List<RB_Finance_RecordDetail>();
                                foreach (var orderGoodsItem in goodsDetailList)
                                {

                                    if (orderGoodsItem.Final_Price > 0)
                                    {
                                        var newOrderGoods = new RB_Goods_OrderDetail_Extend();
                                        newOrderGoods = orderGoodsItem;
                                        newOrderGoods.FinanceType = 1;
                                        result.Add(newOrderGoods);

                                    }
                                    if (orderGoodsItem.FreightMoney.HasValue && orderGoodsItem.FreightMoney.Value > 0)
                                    {
                                        var newOrderGoods = new RB_Goods_OrderDetail_Extend();
                                        newOrderGoods = orderGoodsItem;
                                        newOrderGoods.FinanceType = 2;
                                        result.Add(newOrderGoods);
                                    }


                                    RB_Finance_RecordDetail financeRecordDetail = new RB_Finance_RecordDetail
                                    {

                                        ID = 0,
                                        RecordId = 0,
                                        Type = record.Type,
                                        TenantId = record.TenantId,
                                        MallBaseId = record.MallBaseId,
                                        FinanceId = 0,
                                        CreateDate = record.CreateDate,
                                        Name = orderGoodsItem.GoodsName,
                                        OrderId = orderGoodsItem.OrderId ?? 0,
                                        OrderDetailId = orderGoodsItem.Id,
                                        GoodsPrice = ((orderGoodsItem.Final_Price ?? 0) - (orderGoodsItem.FreightMoney ?? 0)),
                                        FreightMoney = orderGoodsItem.FreightMoney,
                                        Unit_Price = orderGoodsItem.Unit_Price,
                                        Number = orderGoodsItem.Number
                                    };
                                    record.RecordDetailList.Add(financeRecordDetail);
                                }

                                var detailList = result.Select(x => new
                                {
                                    CostTypeId = x.FinanceType == 1 ? item.IncomeCostTypeId : item.FreightCostTypeId,
                                    Number = x.FinanceType == 1 ? x.Number : 1,
                                    OriginalMoney = x.FinanceType == 1 ? x.Unit_Price : x.FreightMoney,
                                    UnitPrice = x.FinanceType == 1 ? (((x.Final_Price ?? 0) - (x.FreightMoney ?? 0)) / (x.Number ?? 0)) : x.FreightMoney,
                                    Remark = x.GoodsName + x.OrderNo
                                });
                                var financeObj = new
                                {
                                    CreateBy = Config.NetworkDirector,
                                    item.IsPublic,
                                    BType = item.AccountType,
                                    AccountId = item.AccountId,
                                    WBMoney = result.Sum(x => x.Final_Price ?? 0),
                                    RB_Branch_Id = Config.RB_Branch_Id,
                                    RemitterName = item.RemitterName,
                                    TradeDate = System.DateTime.Now.ToString("yyyy-MM-dd"),
                                    AccountNumber = System.DateTime.Now.ToString("yyyyMMdd"),
                                    TemplateId = item.WorkFlowId,
                                    OrderSource = 16,
                                    Remark = System.DateTime.Now.ToString("yyyy年MM月dd日") + "自动生成财务单据",
                                    detailList,

                                };
                                string sign = EncryptionHelper.AesEncrypt(JsonHelper.Serialize(financeObj), Config.FinanceKey);
                                var resultInfo = new
                                {
                                    msg = sign,
                                };

                                string apiResult = Mall.Common.Plugin.HttpHelper.HttpPost(Config.IncomeFinanceApi, JsonHelper.Serialize(resultInfo), "");
                                JObject parmsJob = JObject.Parse(apiResult);
                                string resultCode = parmsJob.GetStringValue("resultCode");
                                int frid = parmsJob.GetInt("data", 0);
                                if (resultCode == "1" && frid > 0)//新增记录
                                {
                                    record.FinanceId = frid;
                                    int recordId = financeRecordRepository.Insert(record);
                                    LogHelper.Write("财务单据ID：" + recordId + "订单数量：" + record.RecordDetailList.Count());
                                    record.RecordDetailList.ForEach(x => x.RecordId = recordId);
                                    record.RecordDetailList.ForEach(x => x.FinanceId = frid);
                                    flag = financeRecordDetailRepository.InsertBatch(record.RecordDetailList);
                                }

                                LogHelper.Write(apiResult);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {

                LogHelper.Write(ex);
            }

            return flag;
        }
        #endregion



        #region 成本

        #endregion

    }
}
