using Dapper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using XYY.Core.Standard.Data.Infrastructure;
using XYY.Core.Standard.Mvc;
using XYY.Service.Standard.Finance.Charging.Base;
using XYY.Service.Standard.Finance.Charging.CustomerAccount;
using XYY.Service.Standard.Finance.Charging.Express;

namespace XYY.Service.Standard.Finance.Charging.CustomerSupplement
{
    /// <summary>
    /// 订单补款（支出），不考虑欠费
    /// </summary>
    public interface ICustomerSupplementService
    {
        Task<ApiJsonModel> Charges(List<ExpressFeechargesModel> list);
    }

    /// <summary>
    /// 订单补款，不考虑欠费
    /// </summary>
    public class CustomerSupplementService : ICustomerSupplementService
    {
        private IUnitOfWork _unitOfWork;
        private ICustomerAccountService _customerAccountService;

        public CustomerSupplementService(IUnitOfWork unitOfWork, ICustomerAccountService customerAccountService)
        {
            _unitOfWork = unitOfWork;
            _customerAccountService = customerAccountService;
        }

        public async Task<ApiJsonModel> Charges(List<ExpressFeechargesModel> list)
        {
            list.ForEach(x =>
            {
                x.CreateTime = DateTime.Now;
                x.TransactionNo = "OF" + DateTime.Now.ToString("yyyyMMddHHmmssfff");
                x.AccountingNo = "ANO" + DateTime.Now.ToString("yyyyMMddHHmmssfff");
                x.IncomeOrESxpense = "支出";
            });

            if (_unitOfWork.Connection.State == System.Data.ConnectionState.Closed)
            {
                _unitOfWork.Connection.Open();
            }
            using (_unitOfWork.Transaction = _unitOfWork.Connection.BeginTransaction())
            {
                try
                {
                    list.ForEach(x => x.SettlementCompleted = true);
                    await _unitOfWork.BulkToDBAsync(list.CopyList<Finance_ChargesDetail>().ToList());
                    foreach (var customerSupplements in list.GroupBy(x => x.CustomerId))
                    {
                        decimal fees = customerSupplements.Sum(x => x.SettlementAmount);
                        await _customerAccountService.Deduction(customerSupplements.Key, fees, false);
                        await _unitOfWork.Connection.ExecuteAsync($"update Finance_Customer_Account set Arrears=1 where customerId={customerSupplements.Key}" +
                            $" and Balance+Quota<0", null, _unitOfWork.Transaction);

                    }

                    _unitOfWork.Transaction.Commit();
                    return ApiJsonModel.OK("成功");
                }
                catch (Exception ex)
                {
                    _unitOfWork.Transaction.Rollback();
                    return ApiJsonModel.Error(ex.Message);
                }
                finally
                {

                    _unitOfWork.Connection.Close();
                    _unitOfWork.Dispose();
                }
            }
        }
    }
}


