using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using XYY.Common.Standard;
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.CustomerOrderFee;
using XYY.Service.Standard.Finance.Charging.Dto;
using XYY.Service.Standard.Finance.Charging.EUExchange;
using XYY.Service.Standard.Finance.Charging.Express;
using XYY.Service.Standard.Finance.Charging.FeeFormula;
using XYY.Service.Standard.Finance.Charging.UserRate;
using static XYY.Common.Standard.EsClientManager;

namespace XYY.Api.Finance.Charges.Controllers
{

    [Route("api/[controller]/[action]")]
    [ApiController]
    public class ExpressFeeController : ApiControllerBase
    {
        ICustomerOrderFeeService _customerOrderFeeService;
        ICustomerOrderRecalculationService _customerOrderRecalculationService;
        ICustomerOrderFeeOffsetService _customerOrderFeeOffsetService;
        ICustomerAccountService _accountService;
        IAttachedService _attachedService;
        private IChargeLogService _chargeLogService;

        public ExpressFeeController(ICustomerOrderFeeService customerOrderFeeService,
            ICustomerOrderRecalculationService customerOrderRecalculationService,
            ICustomerOrderFeeOffsetService customerOrderFeeOffsetService,
            ICustomerAccountService accountService,
            IChargeLogService chargeLogService,
             IAttachedService attachedService)
        {
            _customerOrderFeeService = customerOrderFeeService;
            _customerOrderRecalculationService = customerOrderRecalculationService;
            _customerOrderFeeOffsetService = customerOrderFeeOffsetService;
            _accountService = accountService;
            _chargeLogService = chargeLogService;
            _attachedService = attachedService;
        }


        [HttpPost]
        [AllowAnonymous]
        /// <summary>
        /// 计费
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public async Task<IActionResult> Charges(ExpressFeechargesModel model)
        {
            ChargesLog chargesLog = new ChargesLog();
            System.Diagnostics.Stopwatch stopwatch = new System.Diagnostics.Stopwatch();
            stopwatch.Start();
            ApiJsonModel jsonModel = await this._customerOrderFeeService.ChargeCustomerAndBranchCompany(model);
            chargesLog.Number = model.TrackingNumber;
            chargesLog.Time = DateTime.Now.ToString_yyyyMMddHHmmss();
            chargesLog.TimeLong = DateTime.Now.ToFileTimeUtc();
            chargesLog.TimeList = model.timeList;
            stopwatch.Stop();
            chargesLog.Millise = stopwatch.ElapsedMilliseconds; 
            if (!EsClientManager.WeightLogClient.IndexExists("chargeslog").Exists)
            {
                EsClientManager.WeightLogClient.CreateIndex("chargeslog");
            }
            EsClientManager.WeightLogClient.IndexDocument(chargesLog);
            return Ok(jsonModel.error ?? jsonModel.message);
        }

        [AllowAnonymous]
        public async Task<IActionResult> NotSend(string periceVersion, string channelId, string customerId)
        {
            await this._customerOrderFeeService.AddNotSend(periceVersion, channelId, customerId);
            return Ok("关闭成功");
        }


        [HttpGet]
        [AllowAnonymous]
        public async Task<IActionResult> Test(string zipcode)
        {
            ApiJsonModel jsonModel = await _attachedService.Test(zipcode);
            return Ok(jsonModel.error ?? jsonModel.message);
        }

        /// <summary>
        /// 单独为MQ扣分公司建的扣费API，单独调用一次Charges
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public async Task<IActionResult> ChargesForBranchCompany(ExpressFeechargesModel model)
        {
            try
            {
                if (!model.IsChargeBranchCompany)
                {
                    throw new Exception("扣费对象必须为分公司");
                }

                ApiJsonModel jsonModel = await this._customerOrderFeeService.Charges(model);
                bool success = jsonModel.success;
                string msg = success ? null : jsonModel.error ?? jsonModel.message ?? "未知错误";
                await _chargeLogService.SaveChargeLog(model, success, msg);
            }
            catch (Exception ex)
            {
                await _chargeLogService.SaveChargeLog(model, false, ex.Message);
            }
            return Ok();
        }

        /// <summary>
        /// 撤消计费 
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public async Task<IActionResult> FeeOffset(ExpressFeechargesModel model)
        {
            ApiJsonModel jsonModel = await _customerOrderFeeOffsetService.ChargeCustomerAndBranchCompany(model);
            return Ok(jsonModel.error ?? jsonModel.message);
        }

        /// <summary>
        /// 重新计费
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public async Task<IActionResult> Recalculation(ExpressFeechargesModel model)
        {
            ApiJsonModel jsonModel = await _customerOrderRecalculationService.ChargeCustomerAndBranchCompany(model);
            return Ok(jsonModel.error ?? jsonModel.message);
        }

        /// <summary>
        /// 是否欠费
        /// </summary>
        /// <param name="customerId"></param>
        /// <returns></returns>
        public async Task<IActionResult> IsArrears(int customerId)
        {
            return Ok(await _accountService.IsArrears(customerId));
        }


        public async Task FixBranchCompanyCharge()
        {
            var lines = System.IO.File.ReadAllLines("d:\\fee5.txt").ToList();
            //            lines = new List<string> {
            //"6A20943106874",
            //"XYYEX0021695350YQ"
            //            };
            int pageSize = 100;
            int pageCount = (int)Math.Ceiling(lines.Count / (decimal)pageSize);
            for (int p = 0; p < pageCount; p++)
            {
                var pageLines = lines.Skip(p * pageSize).Take(pageSize).ToList();
                await _customerOrderFeeService.FixBranchCompanyCharge(pageLines);
                System.Threading.Thread.Sleep(5000);
            }

        }


        public async Task ReChargeByTime(ReChargeByTimeParam param)
        {
            await this._customerOrderFeeService.ReChargeByTime(param);
        }
    }
}
