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.CustomerOrderFee
{
    /// <summary>
    /// 订单扣款（收入）
    /// </summary>
    public interface ICustomerDeductionService
    {
        /// <summary>
        /// 订单扣款（收入）
        /// </summary>
        /// <param name="list"></param>
        /// <returns></returns>
        Task<ApiJsonModel> Charges(List<ExpressFeechargesModel> list);

    }

    public class CustomerDeductionService : ICustomerDeductionService
    {
        private IUnitOfWork _unitOfWork;
        private ICustomerAccountService _customerAccountService;

        public CustomerDeductionService(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.Income(customerSupplements.Key, fees);
                    }
                    _unitOfWork.Transaction.Commit();
                    return ApiJsonModel.OK("成功");
                }
                catch (Exception ex)
                {
                    _unitOfWork.Transaction.Rollback();
                    return ApiJsonModel.Error(ex.Message);
                }
                finally
                {

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