using EVCB_OCPP.WEBAPI.Handlers;
using EVCB_OCPP.WEBAPI.Models.WebAPI;
using EVCB_OCPP.WEBAPI.Services;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using Newtonsoft.Json;
using System.Threading.Tasks;
using EVCB_OCPP.WEBAPI.Models.WebAPI.Dto;
using EVCB_OCPP.Packet.Messages.SubTypes;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Extensions;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using System.Diagnostics;
using EVCB_OCPP.Domain.Models.Database;
using Azure.Core;

namespace EVCB_OCPP.WEBAPI.Controllers.Version1
{
    //[ApiExplorerSettings(IgnoreApi = true)]
    [ServiceFilter(typeof(CPOAuthentication))]
    //[CPOAuthentication]
    [ApiController]
    [Route("api/v1/cpo")]
    public class CPOController : ControllerBase
    {
        public CPOController(IServiceProvider serviceProvider, IConfiguration configuration, ILogger<CPOController> logger)
        {
            this.serviceProvider = serviceProvider;
            this.logger = logger;
        }

        private readonly IServiceProvider serviceProvider;
        private readonly ILogger<CPOController> logger;

        [Route("station")]
        [HttpGet]
        public async Task<IActionResult> Station()
        {
            var result = new CPOOuterResponse();
            //HttpStatusCode statusCode = HttpStatusCode.InternalServerError;
            int statusCode = StatusCodes.Status500InternalServerError;

            try
            {
                if (!IsCustomerIdAvaliable())
                {
                    return StatusCode(statusCode, result);
                }

                var _customerId = GetCustomerId();

                ChargingStationService _service = serviceProvider.GetRequiredService<ChargingStationService>();

                var _innerResponse = new { Stations = await _service.GetStationsbyCustomerIdAsync(_customerId) };

                result.Data = JsonConvert.SerializeObject(_innerResponse, EVCBConfiguration.JSONSERIALIZER_FORMAT);
                result.StatusCode = (int)CPO_StatusCode.Success;
                result.StatusMessage = CPO_StatusMessage.Success;
                //statusCode = HttpStatusCode.OK;
                statusCode = StatusCodes.Status200OK;
                //return Request.CreateResponse(statusCode, result);
                return StatusCode(statusCode, result);
            }
            catch (Exception ex)
            {
                result.ErrorDetail = ex.ToString();
                result.StatusMessage = CPO_StatusMessage.ERROR_MSG_UNEXPECTEDERROR;
                result.StatusCode = (int)CPO_StatusCode.UnexpectedError;
                //return Request.CreateResponse(statusCode, result);
                return StatusCode(statusCode, result);
            }
        }

        [Route("information")]
        [Produces(typeof(CPOOuterResponse))]
        [HttpGet]
        public IActionResult BasicInformationofEVSEs(int? Limit = -1, int StationId = -1, string ChargeBoxId = "", DateTime? DateFrom = null, DateTime? DateTo = null, int? Offset = 0)
        {

            var result = new CPOOuterResponse();
            //HttpStatusCode statusCode = HttpStatusCode.InternalServerError;
            int statusCode = StatusCodes.Status500InternalServerError;
            try
            {
                ChargePointService _CPService = serviceProvider.GetRequiredService<ChargePointService>();// new ChargePointService();
                var tt = _CPService.GetLastUpdatedTimebyMachineId("0da4f4a6-a952-46f0-b2f3-696385a9a56a");
                if (!IsCustomerIdAvaliable())
                {
                    //return Request.CreateResponse(statusCode, result);
                    return StatusCode(statusCode, result);
                }

                var _customerId = GetCustomerId();

                var _innerResponse = new { EVSEs = new List<EVSE>() };
                ChargingStationService _stationService = serviceProvider.GetRequiredService<ChargingStationService>();// new ChargingStationService();

                if (StationId > -1)
                {
                    if (_stationService.ContainsStation(_customerId, StationId))
                    {
                        if (DateTo.HasValue)
                        {
                            if (!DateFrom.HasValue)
                            {

                                result.StatusMessage = CPO_StatusMessage.ERROR_MSG_PARAMETER_OUTOFRANGE_INCORRECT;
                                result.StatusCode = (int)CPO_StatusCode.PARAMETER_OUTOFRANGE_INCORRECT;
                                //statusCode = HttpStatusCode.BadRequest;
                                statusCode = StatusCodes.Status400BadRequest;
                                //return Request.CreateResponse(statusCode, result);
                                return StatusCode(statusCode, result);
                            }
                        }
                        _innerResponse = new { EVSEs = _stationService.GetEVSEsbyStationId(StationId, DateFrom, DateTo, Offset.Value, Limit == -1 ? 1000 : Limit.Value) };


                    }
                }
                else
                {
                    _innerResponse = new { EVSEs = new List<EVSE>() };
                    _innerResponse.EVSEs.Add(_CPService.GetEVSEsbyChargeBoxId(ChargeBoxId, DateFrom, DateTo));


                }

                result.Data = JsonConvert.SerializeObject(_innerResponse, EVCBConfiguration.JSONSERIALIZER_FORMAT);
                result.StatusCode = (int)CPO_StatusCode.Success;
                result.StatusMessage = CPO_StatusMessage.Success;
                //statusCode = HttpStatusCode.OK;
                statusCode = StatusCodes.Status200OK;
                //return Request.CreateResponse(statusCode, result);
                return StatusCode(statusCode, result);
            }
            catch (Exception ex)
            {
                result.ErrorDetail = ex.ToString();
                result.StatusMessage = CPO_StatusMessage.ERROR_MSG_UNEXPECTEDERROR;
                result.StatusCode = (int)CPO_StatusCode.UnexpectedError;
                //return Request.CreateResponse(statusCode, result);
                return StatusCode(statusCode, result);
            }
        }

        [Route("commands/start_session")]
        [Produces(typeof(CPOOuterResponse))]
        [HttpPost]
        async public Task<IActionResult> StartSession([FromBody] StartSessionRequest request)
        {

            var result = new CPOOuterResponse();
            //HttpStatusCode statusCode = HttpStatusCode.InternalServerError;
            int statusCode = StatusCodes.Status500InternalServerError;
            var _innerData = new { Result = CommandResponseType.Rejected.ToString(), Timeout = 60 };
            try
            {
                string _CustomerId = GetCustomerId();
                logger.LogTrace($"StartSession {request.ChargeBoxId} {_CustomerId}");

                if (!await ContainsChargePointAsync(request.ChargeBoxId, _CustomerId))
                {
                    // 沒槍~ 沒得充...                   
                    result.StatusMessage = CPO_StatusMessage.ERROR_MSG_CHARGEBOXID_DOESNT_EXIST;
                    result.StatusCode = (int)CPO_StatusCode.CHARGEBOXID_ISNT_EXIST_OR_OFFLINE;
                    result.Data = JsonConvert.SerializeObject(_innerData, EVCBConfiguration.JSONSERIALIZER_FORMAT);
                    //statusCode = HttpStatusCode.BadRequest;
                    statusCode = StatusCodes.Status400BadRequest;
                    //return Request.CreateResponse(statusCode, result);

                    return StatusCode(statusCode, result);
                }

                ChargePointService _CPService = serviceProvider.GetRequiredService<ChargePointService>();

                if (string.IsNullOrEmpty(request.ChargeBoxId) ||
                    request.ChargeBoxId.Length > 25 ||
                    request.ConnectorId.HasValue &&
                        (!(await _CPService.GetNumberofConnectorsAsync(request.ChargeBoxId) >= request.ConnectorId) || !(request.ConnectorId > 0)) ||
                    string.IsNullOrEmpty(request.Token) ||
                    request.Token.Length > 20)
                {
                    // 參數不符合定義
                    result.StatusMessage = CPO_StatusMessage.ERROR_MSG_PARAMETER_OUTOFRANGE_INCORRECT;
                    result.StatusCode = (int)CPO_StatusCode.PARAMETER_OUTOFRANGE_INCORRECT;
                    result.Data = JsonConvert.SerializeObject(_innerData, EVCBConfiguration.JSONSERIALIZER_FORMAT);
                    //statusCode = HttpStatusCode.BadRequest;
                    statusCode = StatusCodes.Status400BadRequest;

                    return StatusCode(statusCode, result);
                }

                InternalHttpClient _client = serviceProvider.GetRequiredService<InternalHttpClient>();
                ICustomerService _customer = serviceProvider.GetRequiredService<ICustomerService>();

                //trigger to charge
                var _request = new Models.WebAPI.StartTransactionRequest()
                {
                    ConnectorId = request.ConnectorId,
                    IdTag = request.Token
                };

                string urlformat = "{0}://{1}";

                var _innerResult = await _client.Post(
                    string.Format(urlformat, Request.Scheme, Request.Host.ToUriComponent())
                    , $"/api/v1/ocpp16/transaction?ChargeBoxId={request.ChargeBoxId}"
                    , new Dictionary<string, string>()
                    {
                        { "PartnerId",_CustomerId}
                    }, _request, _customer.GetAPIKey(new Guid(_CustomerId)));

                _innerData = new { Result = string.IsNullOrEmpty(_innerResult.SerialNo) ? CommandResponseType.Rejected.ToString() : CommandResponseType.Accepted.ToString(), Timeout = 60 };
                result = GetErrorDescription(_innerResult);
                result.Data = JsonConvert.SerializeObject(_innerData, EVCBConfiguration.JSONSERIALIZER_FORMAT);

                if (_innerResult.Status == HttpStatusCode.InternalServerError)
                {

                    result.StatusCode = _innerResult.ErrorCode;
                    result.StatusMessage = CPO_StatusMessage.ERROR_MSG_INNERSERVICE_ERROR;
                    //statusCode = HttpStatusCode.InternalServerError;
                    statusCode = StatusCodes.Status500InternalServerError;
                }
                else
                {
                    result.SerialNo = _innerResult.SerialNo;
                    result.StatusCode = _innerResult.ErrorCode;
                    result.StatusMessage = _innerResult.Message;
                    //statusCode = HttpStatusCode.OK;
                    statusCode = StatusCodes.Status200OK;
                }

                //return Request.CreateResponse(statusCode, result);
                return StatusCode(statusCode, result);
            }
            catch (Exception ex)
            {
                result.ErrorDetail = ex.ToString();
                result.StatusMessage = CPO_StatusMessage.ERROR_MSG_UNEXPECTEDERROR;
                result.StatusCode = (int)CPO_StatusCode.UnexpectedError;
                //return Request.CreateResponse(statusCode, result);
                return StatusCode(statusCode, result);
            }


        }


        [Route("commands/stop_session")]
        [Produces(typeof(CPOOuterResponse))]
        [HttpPost]
        async public Task<IActionResult> StopSession(string ChargeBoxId, int SessionId)
        {
            var result = new CPOOuterResponse();
            //HttpStatusCode statusCode = HttpStatusCode.InternalServerError;
            int statusCode = StatusCodes.Status500InternalServerError;
            var _innerData = new { Result = CommandResponseType.Rejected.ToString(), Timeout = 60 };
            try
            {
                string _CustomerId = GetCustomerId();
                logger.LogTrace($"{nameof(StopSession)} {ChargeBoxId} {_CustomerId}");

                if (!await ContainsChargePointAsync(ChargeBoxId, _CustomerId))
                {
                    // 沒槍~ 沒得充...                   
                    result.StatusMessage = CPO_StatusMessage.ERROR_MSG_CHARGEBOXID_DOESNT_EXIST;
                    result.StatusCode = (int)CPO_StatusCode.CHARGEBOXID_ISNT_EXIST_OR_OFFLINE;
                    result.Data = JsonConvert.SerializeObject(_innerData, EVCBConfiguration.JSONSERIALIZER_FORMAT);
                    //statusCode = HttpStatusCode.BadRequest;
                    statusCode = StatusCodes.Status400BadRequest;
                    //return Request.CreateResponse(statusCode, result);
                    return StatusCode(statusCode, result);
                }


                InternalHttpClient _client = serviceProvider.GetRequiredService<InternalHttpClient>();
                ICustomerService _customer = serviceProvider.GetRequiredService<ICustomerService>();

                string urlformat = "{0}://{1}";

                var _innerResult = await _client.Put(
                    string.Format(urlformat, Request.Scheme, Request.Host.ToUriComponent() ), 
                    $"/api/v1/ocpp16/transaction?ChargeBoxId={ChargeBoxId}&TransactionId={SessionId}",
                    new Dictionary<string, string>()
                    {
                        { "PartnerId",_CustomerId}

                    }, 
                    null, 
                    _customer.GetAPIKey(new Guid(_CustomerId)));


                _innerData = new { Result = string.IsNullOrEmpty(_innerResult.SerialNo) ? CommandResponseType.Rejected.ToString() : CommandResponseType.Accepted.ToString(), Timeout = 60 };
                result = GetErrorDescription(_innerResult);
                result.Data = JsonConvert.SerializeObject(_innerData, EVCBConfiguration.JSONSERIALIZER_FORMAT);
                if (_innerResult.Success)
                {
                    result.SerialNo = _innerResult.SerialNo;
                    result.StatusCode = (int)CPO_StatusCode.Success;
                    result.StatusMessage = CPO_StatusMessage.Success;
                    //statusCode = HttpStatusCode.OK;
                    statusCode = StatusCodes.Status200OK;
                }
                else
                {
                    if (_innerResult.ErrorCode == (int)CPO_StatusCode.UnexpectedError)
                    {
                        result.StatusCode = _innerResult.ErrorCode;
                        result.StatusMessage = CPO_StatusMessage.ERROR_MSG_INNERSERVICE_ERROR;
                        //statusCode = HttpStatusCode.BadRequest;
                        statusCode = StatusCodes.Status400BadRequest;
                    }
                    else
                    {
                        result.StatusCode = _innerResult.ErrorCode;
                        result.StatusMessage = _innerResult.Message;
                        //statusCode = HttpStatusCode.BadRequest;
                        statusCode = StatusCodes.Status400BadRequest;
                    }


                }


            }
            catch (Exception ex)
            {
                result.ErrorDetail = ex.ToString();
                result.StatusMessage = CPO_StatusMessage.ERROR_MSG_UNEXPECTEDERROR;
                result.StatusCode = (int)CPO_StatusCode.UnexpectedError;
                //return Request.CreateResponse(statusCode, result);
                return StatusCode(statusCode, result);
            }

            //return Request.CreateResponse(statusCode, result);
            return StatusCode(statusCode, result);
        }

        [Route("commands/reserve_now")]
        [Produces(typeof(CPOOuterResponse))]
        [HttpPost]
        async public Task<IActionResult> ReserveNow([FromBody] ReserveNowRequest request)
        {
            var result = new CPOOuterResponse();
            //HttpStatusCode statusCode = HttpStatusCode.InternalServerError;
            int statusCode = StatusCodes.Status500InternalServerError;
            var _innerData = new { Result = CommandResponseType.Rejected.ToString(), Timeout = 60 };
            try
            {
                string _CustomerId = string.Empty;

                if (!ContainsChargePoint(request.ChargeBoxId, out _CustomerId))
                {
                    // 沒槍~ 沒得充...                   
                    result.StatusMessage = CPO_StatusMessage.ERROR_MSG_CHARGEBOXID_DOESNT_EXIST;
                    result.StatusCode = (int)CPO_StatusCode.CHARGEBOXID_ISNT_EXIST_OR_OFFLINE;
                    result.Data = JsonConvert.SerializeObject(_innerData, EVCBConfiguration.JSONSERIALIZER_FORMAT);
                    //statusCode = HttpStatusCode.BadRequest;
                    statusCode = StatusCodes.Status400BadRequest;
                    //return Request.CreateResponse(statusCode, result);
                    return StatusCode(statusCode, result);
                }


                InternalHttpClient _client = serviceProvider.GetRequiredService<InternalHttpClient>();
                ICustomerService _customer = serviceProvider.GetRequiredService<ICustomerService>();

                string urlformat = "{0}://{1}";

                var _innerRequest = new ReserveRequest()
                {
                    ConnectorId = request.ConnectorId,
                    IdTag = request.Token,
                    ReservationId = request.ReservationId,
                    ExpiryDate = request.ExpiryDate.ToString(EVCBConfiguration.UTC_DATETIMEFORMAT)
                };

                var _innerResult = await _client.Post(
                    string.Format(urlformat, Request.Scheme, Request.Host.ToUriComponent()),
                    $"/api/v1/ocpp16/reservation?ChargeBoxId={request.ChargeBoxId}",
                    new Dictionary<string, string>()
                        {
                            { "PartnerId",_CustomerId}

                        },
                    _innerRequest,
                    _customer.GetAPIKey(new Guid(_CustomerId)));


                _innerData = new { Result = string.IsNullOrEmpty(_innerResult.SerialNo) ? CommandResponseType.Rejected.ToString() : CommandResponseType.Accepted.ToString(), Timeout = 60 };
                result = GetErrorDescription(_innerResult);
                result.Data = JsonConvert.SerializeObject(_innerData, EVCBConfiguration.JSONSERIALIZER_FORMAT);
                if (_innerResult.Success)
                {
                    result.SerialNo = _innerResult.SerialNo;
                    result.StatusCode = (int)CPO_StatusCode.Success;
                    result.StatusMessage = CPO_StatusMessage.Success;
                    //statusCode = HttpStatusCode.OK;
                    statusCode = StatusCodes.Status200OK;
                }
                else
                {

                    if (_innerResult.ErrorCode == (int)CPO_StatusCode.UnexpectedError)
                    {
                        result.StatusCode = _innerResult.ErrorCode;
                        result.StatusMessage = CPO_StatusMessage.ERROR_MSG_INNERSERVICE_ERROR;
                        //statusCode = HttpStatusCode.BadRequest;
                        statusCode = StatusCodes.Status400BadRequest;
                    }
                    else
                    {
                        result.StatusCode = _innerResult.ErrorCode;
                        result.StatusMessage = _innerResult.Message;
                        //statusCode = HttpStatusCode.BadRequest;
                        statusCode = StatusCodes.Status400BadRequest;
                    }
                }
            }
            catch (Exception ex)
            {
                result.ErrorDetail = ex.ToString();
                result.StatusMessage = CPO_StatusMessage.ERROR_MSG_UNEXPECTEDERROR;
                result.StatusCode = (int)CPO_StatusCode.UnexpectedError;
                //return Request.CreateResponse(statusCode, result);
                return StatusCode(statusCode, result);
            }

            //return Request.CreateResponse(statusCode, result);
            return StatusCode(statusCode, result);
        }


        [Route("commands/cancel_reservation")]
        [Produces(typeof(CPOOuterResponse))]
        [HttpPost]
        async public Task<IActionResult> CancelReservation(string ChargeBoxId, int ReservationId)
        {
            var result = new CPOOuterResponse();
            //HttpStatusCode statusCode = HttpStatusCode.InternalServerError;
            int statusCode = StatusCodes.Status500InternalServerError;
            var _innerData = new { Result = CommandResponseType.Rejected.ToString(), Timeout = 60 };
            try
            {
                string _CustomerId = string.Empty;

                if (!ContainsChargePoint(ChargeBoxId, out _CustomerId))
                {
                    // 沒槍~ 沒得充...                   
                    result.StatusMessage = CPO_StatusMessage.ERROR_MSG_CHARGEBOXID_DOESNT_EXIST;
                    result.StatusCode = (int)CPO_StatusCode.CHARGEBOXID_ISNT_EXIST_OR_OFFLINE;
                    result.Data = JsonConvert.SerializeObject(_innerData, EVCBConfiguration.JSONSERIALIZER_FORMAT);
                    //statusCode = HttpStatusCode.BadRequest;
                    statusCode = StatusCodes.Status400BadRequest;
                    //return Request.CreateResponse(statusCode, result);
                    return StatusCode(statusCode, result);
                }


                InternalHttpClient _client = serviceProvider.GetRequiredService<InternalHttpClient>();
                ICustomerService _customer = serviceProvider.GetRequiredService<ICustomerService>();

                string urlformat = "{0}://{1}";

                var _innerResult = await _client.Delete(
                    string.Format(urlformat, Request.Scheme, Request.Host.ToUriComponent()), 
                    $"/api/v1/ocpp16/reservation?ChargeBoxId={ChargeBoxId}&ReservationId={ReservationId}",
                    new Dictionary<string, string>()
                    {
                        { "PartnerId",_CustomerId}

                    }, _customer.GetAPIKey(new Guid(_CustomerId)));


                _innerData = new { Result = string.IsNullOrEmpty(_innerResult.SerialNo) ? CommandResponseType.Rejected.ToString() : CommandResponseType.Accepted.ToString(), Timeout = 60 };
                result = GetErrorDescription(_innerResult);
                result.Data = JsonConvert.SerializeObject(_innerData, EVCBConfiguration.JSONSERIALIZER_FORMAT);
                if (_innerResult.Success)
                {
                    result.SerialNo = _innerResult.SerialNo;
                    result.StatusCode = (int)CPO_StatusCode.Success;
                    result.StatusMessage = CPO_StatusMessage.Success;
                    //statusCode = HttpStatusCode.OK;
                    statusCode = StatusCodes.Status200OK;
                }
                else
                {
                    if (_innerResult.ErrorCode == (int)CPO_StatusCode.UnexpectedError)
                    {
                        result.StatusCode = _innerResult.ErrorCode;
                        result.StatusMessage = CPO_StatusMessage.ERROR_MSG_INNERSERVICE_ERROR;
                        //statusCode = HttpStatusCode.BadRequest;
                        statusCode = StatusCodes.Status400BadRequest;
                    }
                    else
                    {
                        result.StatusCode = _innerResult.ErrorCode;
                        result.StatusMessage = _innerResult.Message;
                        //statusCode = HttpStatusCode.BadRequest;
                        statusCode = StatusCodes.Status400BadRequest;
                    }
                }
            }
            catch (Exception ex)
            {
                result.ErrorDetail = ex.ToString();
                result.StatusMessage = CPO_StatusMessage.ERROR_MSG_UNEXPECTEDERROR;
                result.StatusCode = (int)CPO_StatusCode.UnexpectedError;
                //return Request.CreateResponse(statusCode, result);
                return StatusCode(statusCode, result);
            }

            //return Request.CreateResponse(statusCode, result);
            return StatusCode(statusCode, result);
        }


        [Route("commands/chargingprofiles")]
        [Produces(typeof(CPOOuterResponse))]
        [HttpGet]
        async public Task<IActionResult> GetActiveChargingProfile(string ChargeBoxId, int ConnectorId, int Duration, int ChargingRateUnit = -1)
        {
            var result = new CPOOuterResponse();
            //HttpStatusCode statusCode = HttpStatusCode.InternalServerError;
            int statusCode = StatusCodes.Status500InternalServerError;
            var _innerData = new { Result = CommandResponseType.Rejected.ToString(), Timeout = 60 };
            try
            {
                string _CustomerId = string.Empty;

                if (!ContainsChargePoint(ChargeBoxId, out _CustomerId))
                {
                    // 沒槍~ 沒得充...                   
                    result.StatusMessage = CPO_StatusMessage.ERROR_MSG_CHARGEBOXID_ISNT_EXIST_OR_OFFLINE;
                    result.StatusCode = (int)CPO_StatusCode.CHARGEBOXID_ISNT_EXIST_OR_OFFLINE;
                    result.Data = JsonConvert.SerializeObject(_innerData, EVCBConfiguration.JSONSERIALIZER_FORMAT);
                    //statusCode = HttpStatusCode.BadRequest;
                    statusCode = StatusCodes.Status400BadRequest;
                    //return Request.CreateResponse(statusCode, result);
                    return StatusCode(statusCode, result);
                }


                InternalHttpClient _client = serviceProvider.GetRequiredService<InternalHttpClient>();
                ICustomerService _customer = serviceProvider.GetRequiredService<ICustomerService>();

                string urlformat = "{0}://{1}";

                var _innerResult = await _client.Get(
                    string.Format(urlformat, Request.Scheme, Request.Host.ToUriComponent()),
                    $"/api/v1/ocpp16/compositeschedule?ChargeBoxId={ChargeBoxId}&ConnectorId={ConnectorId}&Duration={Duration}&ChargingRateUnit={ChargingRateUnit}",
                    new Dictionary<string, string>()
                    {
                        { "PartnerId",_CustomerId}

                    }, _customer.GetAPIKey(new Guid(_CustomerId)));


                _innerData = new { Result = string.IsNullOrEmpty(_innerResult.SerialNo) ? CommandResponseType.Rejected.ToString() : CommandResponseType.Accepted.ToString(), Timeout = 60 };
                result = GetErrorDescription(_innerResult);
                result.Data = JsonConvert.SerializeObject(_innerData, EVCBConfiguration.JSONSERIALIZER_FORMAT);
                if (_innerResult.Success)
                {
                    result.SerialNo = _innerResult.SerialNo;
                    result.StatusCode = (int)CPO_StatusCode.Success;
                    result.StatusMessage = CPO_StatusMessage.Success;
                    //statusCode = HttpStatusCode.OK;
                    statusCode = StatusCodes.Status200OK;
                }
                else
                {
                    if (_innerResult.ErrorCode == (int)CPO_StatusCode.UnexpectedError)
                    {
                        result.StatusCode = _innerResult.ErrorCode;
                        result.StatusMessage = CPO_StatusMessage.ERROR_MSG_INNERSERVICE_ERROR;
                        //statusCode = HttpStatusCode.BadRequest;
                        statusCode = StatusCodes.Status400BadRequest;
                    }
                    else
                    {
                        result.StatusCode = _innerResult.ErrorCode;
                        result.StatusMessage = _innerResult.Message;
                        //statusCode = HttpStatusCode.BadRequest;
                        statusCode = StatusCodes.Status400BadRequest;
                    }

                }
            }
            catch (Exception ex)
            {
                result.ErrorDetail = ex.ToString();
                result.StatusMessage = CPO_StatusMessage.ERROR_MSG_UNEXPECTEDERROR;
                result.StatusCode = (int)CPO_StatusCode.UnexpectedError;
                //return Request.CreateResponse(statusCode, result);
                return StatusCode(statusCode, result);
            }

            //return Request.CreateResponse(statusCode, result);
            return StatusCode(statusCode, result);
        }

        [Route("commands/chargingprofiles")]
        [Produces(typeof(CPOOuterResponse))]
        [HttpPut]
        async public Task<IActionResult> SetChargingProfile(string ChargeBoxId, [FromBody] ChargingProfileRequest request)
        {
            var result = new CPOOuterResponse();
            //HttpStatusCode statusCode = HttpStatusCode.InternalServerError;
            int statusCode = StatusCodes.Status500InternalServerError;
            var _innerData = new { Result = CommandResponseType.Rejected.ToString(), Timeout = 60 };
            try
            {
                string _CustomerId = string.Empty;

                if (!ContainsChargePoint(ChargeBoxId, out _CustomerId))
                {
                    // 沒槍~ 沒得充...                   
                    result.StatusMessage = CPO_StatusMessage.ERROR_MSG_CHARGEBOXID_DOESNT_EXIST;
                    result.StatusCode = (int)CPO_StatusCode.CHARGEBOXID_ISNT_EXIST_OR_OFFLINE;
                    result.Data = JsonConvert.SerializeObject(_innerData, EVCBConfiguration.JSONSERIALIZER_FORMAT);
                    //statusCode = HttpStatusCode.BadRequest;
                    statusCode = StatusCodes.Status400BadRequest;
                    //return Request.CreateResponse(statusCode, result);
                    return StatusCode(statusCode, result);
                }



                InternalHttpClient _client = serviceProvider.GetRequiredService<InternalHttpClient>();
                ICustomerService _customer = serviceProvider.GetRequiredService<ICustomerService>();

                string urlformat = "{0}://{1}";

                var _innerResult = await _client.Post(
                    string.Format(urlformat, Request.Scheme, Request.Host.ToUriComponent()), 
                    $"/api/v1/ocpp16/chargingprofile?ChargeBoxId={ChargeBoxId}",
                    new Dictionary<string, string>()
                    {
                        { "PartnerId", _CustomerId}
                    }, 
                    request,
                    _customer.GetAPIKey(new Guid(_CustomerId)));

                _innerData = new { Result = string.IsNullOrEmpty(_innerResult.SerialNo) ? CommandResponseType.Rejected.ToString() : CommandResponseType.Accepted.ToString(), Timeout = 60 };
                result = GetErrorDescription(_innerResult);
                result.Data = JsonConvert.SerializeObject(_innerData, EVCBConfiguration.JSONSERIALIZER_FORMAT);
                if (_innerResult.Success)
                {
                    result.SerialNo = _innerResult.SerialNo;
                    result.StatusCode = (int)CPO_StatusCode.Success;
                    result.StatusMessage = CPO_StatusMessage.Success;
                    //statusCode = HttpStatusCode.OK;
                    statusCode = StatusCodes.Status200OK;
                }
                else
                {

                    if (_innerResult.ErrorCode == (int)CPO_StatusCode.UnexpectedError)
                    {
                        result.StatusCode = _innerResult.ErrorCode;
                        result.StatusMessage = CPO_StatusMessage.ERROR_MSG_INNERSERVICE_ERROR;
                        //statusCode = HttpStatusCode.BadRequest;
                        statusCode = StatusCodes.Status400BadRequest;
                    }
                    else
                    {
                        result.StatusCode = _innerResult.ErrorCode;
                        result.StatusMessage = _innerResult.Message;
                        //statusCode = HttpStatusCode.BadRequest;
                        statusCode = StatusCodes.Status400BadRequest;
                    }
                }
                ChargePointService chargePointService = serviceProvider.GetRequiredService<ChargePointService>();

                if (!chargePointService.IsOnline(ChargeBoxId))
                {
                    //return Request.CreateResponse(HttpStatusCode.BadRequest, new ErrorResponse() { Code = 2101, Message = EVCBConfiguration.ERROR_MSG_CHARGEBOXID_ISNT_EXIST_OR_OFFLINE });
                    return StatusCode(
                        StatusCodes.Status400BadRequest,
                        new ErrorResponse()
                        {
                            Code = 2101,
                            Message = EVCBConfiguration.ERROR_MSG_CHARGEBOXID_ISNT_EXIST_OR_OFFLINE
                        });
                }


            }
            catch (Exception ex)
            {
                result.ErrorDetail = ex.ToString();
                result.StatusMessage = CPO_StatusMessage.ERROR_MSG_UNEXPECTEDERROR;
                result.StatusCode = (int)CPO_StatusCode.UnexpectedError;
                //return Request.CreateResponse(statusCode, result);
                return StatusCode(statusCode, result);
            }

            //return Request.CreateResponse(statusCode, result);
            return StatusCode(statusCode, result);
        }

        [Route("commands/chargingprofiles")]
        [Produces(typeof(CPOOuterResponse))]
        [HttpDelete]
        async public Task<IActionResult> ClearChargingPorfile(string ChargeBoxId, int ChargeProfileId = -1)
        {
            var result = new CPOOuterResponse();
            //HttpStatusCode statusCode = HttpStatusCode.InternalServerError;
            int statusCode = StatusCodes.Status500InternalServerError;
            var _innerData = new { Result = CommandResponseType.Rejected.ToString(), Timeout = 60 };
            try
            {
                string _CustomerId = string.Empty;

                if (!ContainsChargePoint(ChargeBoxId, out _CustomerId))
                {
                    // 沒槍~ 沒得充...                   
                    result.StatusMessage = CPO_StatusMessage.ERROR_MSG_CHARGEBOXID_DOESNT_EXIST;
                    result.StatusCode = (int)CPO_StatusCode.CHARGEBOXID_ISNT_EXIST_OR_OFFLINE;
                    result.Data = JsonConvert.SerializeObject(_innerData, EVCBConfiguration.JSONSERIALIZER_FORMAT);
                    // statusCode = HttpStatusCode.BadRequest;
                    statusCode = StatusCodes.Status400BadRequest;
                    //return Request.CreateResponse(statusCode, result);
                    return StatusCode(statusCode, result);
                }


                InternalHttpClient _client = serviceProvider.GetRequiredService<InternalHttpClient>();
                ICustomerService _customer = serviceProvider.GetRequiredService<ICustomerService>();

                string urlformat = "{0}://{1}";

                var _innerResult = await _client.Delete(
                    string.Format(urlformat, Request.Scheme, Request.Host.ToUriComponent()),
                    string.Format("/api/v1/ocpp16/chargingprofile?ChargeBoxId={2}{3}", ChargeBoxId, ChargeProfileId == -1 ? "" : "&Id=" + ChargeProfileId),
                    new Dictionary<string, string>()
                    {
                        { "PartnerId",_CustomerId}

                    }, _customer.GetAPIKey(new Guid(_CustomerId)));


                _innerData = new { Result = string.IsNullOrEmpty(_innerResult.SerialNo) ? CommandResponseType.Rejected.ToString() : CommandResponseType.Accepted.ToString(), Timeout = 60 };
                result = GetErrorDescription(_innerResult);
                result.Data = JsonConvert.SerializeObject(_innerData, EVCBConfiguration.JSONSERIALIZER_FORMAT);
                if (_innerResult.Success)
                {
                    result.SerialNo = _innerResult.SerialNo;
                    result.StatusCode = (int)CPO_StatusCode.Success;
                    result.StatusMessage = CPO_StatusMessage.Success;
                    //statusCode = HttpStatusCode.OK;
                    statusCode = StatusCodes.Status200OK;
                }
                else
                {

                    if (_innerResult.ErrorCode == (int)CPO_StatusCode.UnexpectedError)
                    {
                        result.StatusCode = _innerResult.ErrorCode;
                        result.StatusMessage = CPO_StatusMessage.ERROR_MSG_INNERSERVICE_ERROR;
                        //statusCode = HttpStatusCode.BadRequest;
                        statusCode = StatusCodes.Status400BadRequest;
                    }
                    else
                    {
                        result.StatusCode = _innerResult.ErrorCode;
                        result.StatusMessage = _innerResult.Message;
                        //statusCode = HttpStatusCode.BadRequest;
                        statusCode = StatusCodes.Status400BadRequest;
                    }
                }
            }
            catch (Exception ex)
            {
                result.ErrorDetail = ex.ToString();
                result.StatusMessage = CPO_StatusMessage.ERROR_MSG_UNEXPECTEDERROR;
                result.StatusCode = (int)CPO_StatusCode.UnexpectedError;
                //return Request.CreateResponse(statusCode, result);
                return StatusCode(statusCode, result);
            }

            //return Request.CreateResponse(statusCode, result);
            return StatusCode(statusCode, result);
        }

        [Route("commands/set_locallist")]
        [Produces(typeof(CPOOuterResponse))]
        [HttpPost]
        async public Task<IActionResult> SendLocalList(string ChargeBoxId, [FromBody] LocalListRequest request)
        {
            var result = new CPOOuterResponse();
            //HttpStatusCode statusCode = HttpStatusCode.InternalServerError;
            int statusCode = StatusCodes.Status500InternalServerError;
            var _innerData = new { Result = CommandResponseType.Rejected.ToString(), Timeout = 60 };
            try
            {
                string _CustomerId = string.Empty;

                if (!ContainsChargePoint(ChargeBoxId, out _CustomerId))
                {
                    // 沒槍~ 沒得充...                   
                    result.StatusMessage = CPO_StatusMessage.ERROR_MSG_CHARGEBOXID_DOESNT_EXIST;
                    result.StatusCode = (int)CPO_StatusCode.CHARGEBOXID_ISNT_EXIST_OR_OFFLINE;
                    result.Data = JsonConvert.SerializeObject(_innerData, EVCBConfiguration.JSONSERIALIZER_FORMAT);
                    //statusCode = HttpStatusCode.BadRequest;
                    statusCode = StatusCodes.Status400BadRequest;
                    //return Request.CreateResponse(statusCode, result);
                    return StatusCode(statusCode, result);
                }


                InternalHttpClient _client = serviceProvider.GetRequiredService<InternalHttpClient>();
                ICustomerService _customer = serviceProvider.GetRequiredService<ICustomerService>();

                string urlformat = "{0}://{1}";

                var _innerResult = await _client.Post(
                    string.Format(urlformat, Request.Scheme, Request.Host.ToUriComponent()), 
                    $"/api/v1/ocpp16/locallist?ChargeBoxId={ChargeBoxId}",
                    new Dictionary<string, string>()
                        {
                            { "PartnerId",_CustomerId}

                        }, request, _customer.GetAPIKey(new Guid(_CustomerId)));

                _innerData = new { Result = string.IsNullOrEmpty(_innerResult.SerialNo) ? CommandResponseType.Rejected.ToString() : CommandResponseType.Accepted.ToString(), Timeout = 60 };
                result = GetErrorDescription(_innerResult);
                result.Data = JsonConvert.SerializeObject(_innerData, EVCBConfiguration.JSONSERIALIZER_FORMAT);
                if (_innerResult.Success)
                {
                    result.SerialNo = _innerResult.SerialNo;
                    result.StatusCode = (int)CPO_StatusCode.Success;
                    result.StatusMessage = CPO_StatusMessage.Success;
                    //statusCode = HttpStatusCode.OK;
                    statusCode = StatusCodes.Status200OK;
                }
                else
                {

                    if (_innerResult.ErrorCode == (int)CPO_StatusCode.UnexpectedError)
                    {
                        result.StatusCode = _innerResult.ErrorCode;
                        result.StatusMessage = CPO_StatusMessage.ERROR_MSG_INNERSERVICE_ERROR;
                        //statusCode = HttpStatusCode.BadRequest;
                        statusCode = StatusCodes.Status400BadRequest;

                    }
                    else
                    {
                        result.StatusCode = _innerResult.ErrorCode;
                        result.StatusMessage = _innerResult.Message;
                        //statusCode = HttpStatusCode.BadRequest;
                        statusCode = StatusCodes.Status400BadRequest;

                    }
                }
            }
            catch (Exception ex)
            {
                result.ErrorDetail = ex.ToString();
                result.StatusMessage = CPO_StatusMessage.ERROR_MSG_UNEXPECTEDERROR;
                result.StatusCode = (int)CPO_StatusCode.UnexpectedError;
                //return Request.CreateResponse(statusCode, result);
                return StatusCode(statusCode, result);
            }

            //return Request.CreateResponse(statusCode, result);
            return StatusCode(statusCode, result);
        }


        [Route("commands/locallistversion")]
        [Produces(typeof(CPOOuterResponse))]
        [HttpGet]
        async public Task<IActionResult> GetLocalListVersion(string ChargeBoxId)
        {
            var result = new CPOOuterResponse();
            //HttpStatusCode statusCode = HttpStatusCode.InternalServerError;
            int statusCode = StatusCodes.Status500InternalServerError;
            var _innerData = new { Result = CommandResponseType.Rejected.ToString(), Timeout = 60 };
            try
            {
                string _CustomerId = string.Empty;

                if (!ContainsChargePoint(ChargeBoxId, out _CustomerId))
                {
                    // 沒槍~ 沒得充...                   
                    result.StatusMessage = CPO_StatusMessage.ERROR_MSG_CHARGEBOXID_DOESNT_EXIST;
                    result.StatusCode = (int)CPO_StatusCode.CHARGEBOXID_ISNT_EXIST_OR_OFFLINE;
                    result.Data = JsonConvert.SerializeObject(_innerData, EVCBConfiguration.JSONSERIALIZER_FORMAT);
                    //statusCode = HttpStatusCode.BadRequest;
                    statusCode = StatusCodes.Status400BadRequest;
                    //return Request.CreateResponse(statusCode, result);
                    return StatusCode(statusCode, result);
                }


                InternalHttpClient _client = serviceProvider.GetRequiredService<InternalHttpClient>();
                ICustomerService _customer = serviceProvider.GetRequiredService<ICustomerService>();

                string urlformat = "{0}://{1}";

                var _innerResult = await _client.Get(
                    string.Format(urlformat, Request.Scheme, Request.Host.ToUriComponent() ), 
                    $"/api/v1/ocpp16/locallistversion?ChargeBoxId={ChargeBoxId}",
                    new Dictionary<string, string>()
                        {
                            { "PartnerId",_CustomerId}

                        }, _customer.GetAPIKey(new Guid(_CustomerId)));


                _innerData = new { Result = string.IsNullOrEmpty(_innerResult.SerialNo) ? CommandResponseType.Rejected.ToString() : CommandResponseType.Accepted.ToString(), Timeout = 60 };
                result = GetErrorDescription(_innerResult);
                result.Data = JsonConvert.SerializeObject(_innerData, EVCBConfiguration.JSONSERIALIZER_FORMAT);
                if (_innerResult.Success)
                {
                    result.SerialNo = _innerResult.SerialNo;
                    result.StatusCode = (int)CPO_StatusCode.Success;
                    result.StatusMessage = CPO_StatusMessage.Success;
                    //statusCode = HttpStatusCode.OK;
                    statusCode = StatusCodes.Status200OK;
                }
                else
                {

                    if (_innerResult.ErrorCode == (int)CPO_StatusCode.UnexpectedError)
                    {
                        result.StatusCode = _innerResult.ErrorCode;
                        result.StatusMessage = CPO_StatusMessage.ERROR_MSG_INNERSERVICE_ERROR;
                        //statusCode = HttpStatusCode.BadRequest;
                        statusCode = StatusCodes.Status400BadRequest;
                    }
                    else
                    {
                        result.StatusCode = _innerResult.ErrorCode;
                        result.StatusMessage = _innerResult.Message;
                        //statusCode = HttpStatusCode.BadRequest;
                        statusCode = StatusCodes.Status400BadRequest;
                    }
                }

                //statusCode = HttpStatusCode.OK;
                statusCode = StatusCodes.Status200OK;
            }
            catch (Exception ex)
            {
                result.ErrorDetail = ex.ToString();
                result.StatusMessage = CPO_StatusMessage.ERROR_MSG_UNEXPECTEDERROR;
                result.StatusCode = (int)CPO_StatusCode.UnexpectedError;
                //return Request.CreateResponse(statusCode, result);
                return StatusCode(statusCode, result);
            }

            //return Request.CreateResponse(statusCode, result);
            return StatusCode(statusCode, result);
        }


        [Route("commands/results")]
        [Produces(typeof(CPOOuterResponse))]
        [HttpGet]
        async public Task<IActionResult> ExecutionofCmdSearch(string ChargeBoxId, CommandType? commandType, string SerialNo)
        {
            var result = new CPOOuterResponse();
            //HttpStatusCode statusCode = HttpStatusCode.InternalServerError;
            int statusCode = StatusCodes.Status500InternalServerError;

            try
            {
                string _CustomerId = string.Empty;

                if (!ContainsChargePoint(ChargeBoxId, out _CustomerId))
                {
                    // 沒槍~ 沒得充...                   
                    result.StatusMessage = CPO_StatusMessage.ERROR_MSG_CHARGEBOXID_DOESNT_EXIST;
                    result.StatusCode = (int)CPO_StatusCode.CHARGEBOXID_ISNT_EXIST_OR_OFFLINE;
                    //statusCode = HttpStatusCode.BadRequest;
                    statusCode = StatusCodes.Status400BadRequest;
                    //return Request.CreateResponse(statusCode, result);
                    return StatusCode(statusCode, result);
                }


                InternalHttpClient _client = serviceProvider.GetRequiredService<InternalHttpClient>();
                ICustomerService _customer = serviceProvider.GetRequiredService<ICustomerService>();

                int? orderNo = (int?)null;

                switch (commandType.Value)
                {
                    case CommandType.CancelReservation:
                        {
                            orderNo = 4;
                        }
                        break;
                    case CommandType.ClearChargingProfile:
                        {
                            orderNo = 6;
                        }
                        break;
                    case CommandType.GetAcitveChargingProfile:
                        {
                            orderNo = 7;
                        }
                        break;
                    case CommandType.GetLocalListVersion:
                        {
                            orderNo = 9;
                        }
                        break;
                    case CommandType.Start_Session:
                        {
                            orderNo = 10;
                        }
                        break;
                    case CommandType.Stop_Session:
                        {
                            orderNo = 11;
                        }
                        break;
                    case CommandType.Reserve_Now:
                        {
                            orderNo = 12;
                        }
                        break;
                    case CommandType.SetLocalList:
                        {
                            orderNo = 14;
                        }
                        break;
                    case CommandType.SetChargingProfile:
                        {
                            orderNo = 15;
                        }
                        break;
                    default:
                        {
                            orderNo = 18;
                        }
                        break;


                }

                string urlformat = "{0}://{1}";

                var _innerResult = await _client.Get(
                    string.Format(urlformat, Request.Scheme, Request.Host.ToUriComponent()),
                    string.Format("/api/v1/ocpp16/command?ChargeBoxId={0}{1}&SerialNo={2}", ChargeBoxId, orderNo.HasValue ? "&OrderNo=" + orderNo.Value : "", SerialNo),
                    new Dictionary<string, string>()
                    {
                        { "PartnerId",_CustomerId}

                    }, _customer.GetAPIKey(new Guid(_CustomerId)));


                result = GetErrorDescription(_innerResult);

                if (_innerResult.Success)
                {
                    ComandExecution _execution = JsonConvert.DeserializeObject<ComandExecution>(_innerResult.Message);

                    CommandResultType? _cmdResult = (CommandResultType?)null;

                    switch (_execution.Code)
                    {
                        case 1:
                            {
                                _cmdResult = CommandResultType.Accepted;
                            }
                            break;
                        case 9:
                            {
                                _cmdResult = CommandResultType.Notsupported;
                            }
                            break;
                        case 10:
                            {
                                _cmdResult = CommandResultType.Unknown;
                            }
                            break;
                        case 26:
                            {
                                _cmdResult = CommandResultType.Occupied;
                            }
                            break;
                        case 31:
                            {
                                _cmdResult = CommandResultType.Rejected;
                            }
                            break;
                        case 32:
                            {
                                _cmdResult = CommandResultType.Failed;
                            }
                            break;
                        case 254:
                            {
                                _cmdResult = CommandResultType.EVSE_ERROR;
                            }
                            break;
                        default:
                            {
                                if (_execution.Detail == "Timeout") _cmdResult = CommandResultType.Timeout;
                                if (_execution.Detail == "Waited") _cmdResult = CommandResultType.Waited;

                            }
                            break;


                    }


                    if (!_cmdResult.HasValue)
                    {
                        result.StatusCode = (int)CPO_StatusCode.CANT_FOUND_DATA;
                        result.StatusMessage = CPO_StatusMessage.ERROR_MSG_CANT_FIND_RESULT;
                        //statusCode = HttpStatusCode.NotFound;
                        statusCode = StatusCodes.Status404NotFound;
                    }
                    else
                    {
                        var _innerData = new { Result = _cmdResult.Value.ToString(), Message = _execution.Detail };
                        result.Data = JsonConvert.SerializeObject(_innerData, EVCBConfiguration.JSONSERIALIZER_FORMAT);
                        result.SerialNo = _innerResult.SerialNo;
                        result.StatusCode = (int)CPO_StatusCode.Success;
                        result.StatusMessage = CPO_StatusMessage.Success;
                        //statusCode = HttpStatusCode.OK;
                        statusCode = StatusCodes.Status200OK;
                    }

                }


            }
            catch (Exception ex)
            {
                result.ErrorDetail = ex.ToString();
                result.StatusMessage = CPO_StatusMessage.ERROR_MSG_UNEXPECTEDERROR;
                result.StatusCode = (int)CPO_StatusCode.UnexpectedError;
                //return Request.CreateResponse(statusCode, result);
                return StatusCode(statusCode, result);
            }

            //return Request.CreateResponse(statusCode, result);
            return StatusCode(statusCode, result);
        }


        [Route("version")]
        [Produces(typeof(CPOOuterResponse))]
        [HttpGet]
        public IActionResult Version(string ChargeBoxId)
        {
            var result = new CPOOuterResponse();
            //HttpStatusCode statusCode = HttpStatusCode.InternalServerError;
            int statusCode = StatusCodes.Status500InternalServerError;

            try
            {
                ChargePointService _service = serviceProvider.GetRequiredService<ChargePointService>();
                string version = _service.GetVersionbyChargeBoxId(ChargeBoxId);

                result.Data = version;
                result.StatusCode = (int)CPO_StatusCode.Success;
                result.StatusMessage = CPO_StatusMessage.Success;
                //statusCode = HttpStatusCode.OK;
                statusCode = StatusCodes.Status200OK;
            }
            catch (Exception ex)
            {
                result.ErrorDetail = ex.ToString();
                result.StatusMessage = CPO_StatusMessage.ERROR_MSG_UNEXPECTEDERROR;
                result.StatusCode = (int)CPO_StatusCode.UnexpectedError;
                //return Request.CreateResponse(statusCode, result);
                return StatusCode(statusCode, result);
            }

            //return Request.CreateResponse(statusCode, result);
            return StatusCode(statusCode, result);

        }


        [Route("activesession")]
        [Produces(typeof(CPOOuterResponse))]
        [HttpGet]
        public async Task<IActionResult> ActiveSession(string ChargeBoxId, int? SessionId = null, string IdTag = null)
        {
            var result = new CPOOuterResponse();
            //HttpStatusCode statusCode = HttpStatusCode.InternalServerError;
            int statusCode = StatusCodes.Status500InternalServerError;

            try
            {
                string _CustomerId = GetCustomerId();

                if (!await ContainsChargePointAsync(ChargeBoxId, _CustomerId))
                {
                    // 沒槍~ 沒得充...                   
                    result.StatusMessage = CPO_StatusMessage.ERROR_MSG_CHARGEBOXID_DOESNT_EXIST;
                    result.StatusCode = (int)CPO_StatusCode.CHARGEBOXID_ISNT_EXIST_OR_OFFLINE;
                    //statusCode = HttpStatusCode.BadRequest;
                    statusCode = StatusCodes.Status400BadRequest;
                    //return Request.CreateResponse(statusCode, result);
                    return StatusCode(statusCode, result);
                }

                // query meter value
                ChargePointService _service = serviceProvider.GetRequiredService<ChargePointService>();
                var transactionDatas = await _service.GetActiveSessionInfoAsync(ChargeBoxId, new List<Measurand>()
                {  Measurand.Voltage,
                   Measurand.Current_Import,
                   Measurand.SoC,
                   Measurand.Power_Active_Import,
                   Measurand.TotalEnergy,
                   Measurand.ChargingCost
                }, _CustomerId, SessionId, IdTag);

                if (transactionDatas is null)
                {
                    result.StatusCode = (int)CPO_StatusCode.CANT_FOUND_DATA;
                    result.StatusMessage = CPO_StatusMessage.ERROR_MSG_CANT_FIND_RESULT;
                    //statusCode = HttpStatusCode.NotFound;
                    statusCode = StatusCodes.Status404NotFound;

                    return StatusCode(statusCode, result);
                }

                List<ActiveSession> _innerData = new();

                foreach (TransasctionData transactionData in transactionDatas)
                {
                    string currencyText = string.IsNullOrEmpty(transactionData.Fee) ? "TWD" : transactionData.Fee.Remove(0, transactionData.Fee.Length - 3);

                    _innerData.Add(ToActiveSession(ChargeBoxId, transactionData));
                }
                var _innerResponse = new { Sessions = _innerData };
                result.Data = JsonConvert.SerializeObject(_innerResponse, EVCBConfiguration.JSONSERIALIZER_FORMAT);

                result.StatusCode = (int)CPO_StatusCode.Success;
                result.StatusMessage = CPO_StatusMessage.Success;
                //statusCode = HttpStatusCode.OK;
                statusCode = StatusCodes.Status200OK;

                //return Request.CreateResponse(statusCode, result);
                return StatusCode(statusCode, result);
            }
            catch (Exception ex)
            {
                result.ErrorDetail = ex.ToString();
                result.StatusMessage = CPO_StatusMessage.ERROR_MSG_UNEXPECTEDERROR;
                result.StatusCode = (int)CPO_StatusCode.UnexpectedError;
                //return Request.CreateResponse(statusCode, result);
                return StatusCode(statusCode, result);
            }

        }


        [Route("completedsession")]
        [Produces(typeof(CPOOuterResponse))]
        [HttpGet]
        public IActionResult CompletedSession(string ChargeBoxId, int SessionId = -1, string IdTag = "", string StartTime = "", string StopTime = "")
        {
            var result = new CPOOuterResponse();
            //HttpStatusCode statusCode = HttpStatusCode.InternalServerError;
            int statusCode = StatusCodes.Status500InternalServerError;

            try
            {
                string _CustomerId = string.Empty;

                if (!ContainsChargePoint(ChargeBoxId, out _CustomerId))
                {
                    // 沒槍~ 沒得充...                   
                    result.StatusMessage = CPO_StatusMessage.ERROR_MSG_CHARGEBOXID_DOESNT_EXIST;
                    result.StatusCode = (int)CPO_StatusCode.CHARGEBOXID_ISNT_EXIST_OR_OFFLINE;
                    //statusCode = HttpStatusCode.BadRequest;
                    statusCode = StatusCodes.Status400BadRequest;
                    //return Request.CreateResponse(statusCode, result);
                    return StatusCode(statusCode, result);
                }

                DateTime startDt = string.IsNullOrEmpty(StartTime) ? new DateTime(1991, 1, 1) : DateTime.Parse(StartTime);
                DateTime stopDt = string.IsNullOrEmpty(StopTime) ? new DateTime(1991, 1, 1) : DateTime.Parse(StopTime);
                // query meter value
                ChargePointService _service = serviceProvider.GetRequiredService<ChargePointService>();
                var _innerData = _service.GetSessionDetail(ChargeBoxId, SessionId, IdTag, startDt, stopDt);

                if (_innerData == null)
                {
                    result.StatusCode = (int)CPO_StatusCode.CANT_FOUND_DATA;
                    result.StatusMessage = CPO_StatusMessage.ERROR_MSG_CANT_FIND_SESSIONDETAIL;
                    //statusCode = HttpStatusCode.NotFound;
                    statusCode = StatusCodes.Status404NotFound;
                    //return Request.CreateResponse(statusCode, result);
                    return StatusCode(statusCode, result);
                }
                var _innerResponse = new { SessionDetails = _innerData };
                result.Data = JsonConvert.SerializeObject(_innerResponse, EVCBConfiguration.JSONSERIALIZER_FORMAT);

                result.StatusCode = (int)CPO_StatusCode.Success;
                result.StatusMessage = CPO_StatusMessage.Success;
                //statusCode = HttpStatusCode.OK;
                statusCode = StatusCodes.Status200OK;
                //return Request.CreateResponse(statusCode, result);
                return StatusCode(statusCode, result);
            }
            catch (Exception ex)
            {
                result.ErrorDetail = ex.ToString();
                result.StatusMessage = CPO_StatusMessage.ERROR_MSG_UNEXPECTEDERROR;
                result.StatusCode = (int)CPO_StatusCode.UnexpectedError;
                //return Request.CreateResponse(statusCode, result);
                return StatusCode(statusCode, result);
            }

        }


        [Route("statistics/charging_sessions")]
        [Produces(typeof(CPOOuterResponse))]
        [HttpPost]
        async public Task<IActionResult> ChargingSessionsStatistics([FromBody] StatisticsRequest request, [FromServices] IConfiguration configuration)
        {
            var result = new CPOOuterResponse();
            //HttpStatusCode statusCode = HttpStatusCode.InternalServerError;
            int statusCode = StatusCodes.Status500InternalServerError;
            //var _innerData = new { Result = CommandResponseType.Rejected.ToString(), Timeout = 60 };
            try
            {

                InternalHttpClient _client = serviceProvider.GetRequiredService<InternalHttpClient>();
                ICustomerService _customer = serviceProvider.GetRequiredService<ICustomerService>();

                string url = configuration["StatisticsAPI"] + 1;
                string chargeBoxIds = GetStatisticChargeBoxIds(request.ChargeBoxIds);

                HttpClientService service = new HttpClientService();

                Dictionary<string, string> postData = new Dictionary<string, string>()
                {
                  { "ChargeBoxId", chargeBoxIds },
                  { "Type", request.Type.ToString() },
                  { "StartDate",request.DateFrom.ToString(EVCBConfiguration.DATETIMEFORMAT)},
                  { "EndDate",request.DateTo.ToString(EVCBConfiguration.DATETIMEFORMAT)}

                };
                var _innerresult = await service.PostFormDataAsync(url, postData, null);


                if (_innerresult.StatusCode == HttpStatusCode.OK)
                {
                    _innerresult.Response = _innerresult.Response.Replace("item", "Title");
                    _innerresult.Response = _innerresult.Response.Replace("Data", "Count");
                    result.Data = _innerresult.Response;
                    result.StatusCode = (int)CPO_StatusCode.Success;
                    result.StatusMessage = CPO_StatusMessage.Success;
                    //statusCode = HttpStatusCode.OK;
                    statusCode = StatusCodes.Status200OK;
                }
                else
                {
                    logger.LogWarning(_innerresult.Exception, _innerresult.Response);

                    result.StatusCode = (int)CPO_StatusCode.CANT_FOUND_DATA;
                    result.StatusMessage = CPO_StatusMessage.ERROR_MSG_INNERSERVICE_ERROR;
                    //statusCode = HttpStatusCode.BadRequest;
                    statusCode = StatusCodes.Status400BadRequest;
                }
            }
            catch (Exception ex)
            {
                result.ErrorDetail = ex.ToString();
                result.StatusMessage = CPO_StatusMessage.ERROR_MSG_UNEXPECTEDERROR;
                result.StatusCode = (int)CPO_StatusCode.UnexpectedError;
                //return Request.CreateResponse(statusCode, result);
                return StatusCode(statusCode, result);
            }

            //return Request.CreateResponse(statusCode, result);
            return StatusCode(statusCode, result);
        }

        [Route("statistics/energy_delivered")]
        [Produces(typeof(CPOOuterResponse))]
        [HttpPost]
        async public Task<IActionResult> Energy_Delivered([FromBody] StatisticsRequest request, [FromServices] IConfiguration configuration)
        {
            var result = new CPOOuterResponse();
            //HttpStatusCode statusCode = HttpStatusCode.InternalServerError;
            int statusCode = StatusCodes.Status500InternalServerError;
            var _innerData = new { Result = CommandResponseType.Rejected.ToString(), Timeout = 60 };
            try
            {

                InternalHttpClient _client = serviceProvider.GetRequiredService<InternalHttpClient>();
                ICustomerService _customer = serviceProvider.GetRequiredService<ICustomerService>();

                string url = configuration["StatisticsAPI"] + 2;
                string chargeBoxIds = GetStatisticChargeBoxIds(request.ChargeBoxIds);

                HttpClientService service = new HttpClientService();

                Dictionary<string, string> postData = new Dictionary<string, string>()
                {
                  { "ChargeBoxId",chargeBoxIds },
                  { "Type", request.Type.ToString() },
                  { "StartDate",request.DateFrom.ToString(EVCBConfiguration.DATETIMEFORMAT)},
                  { "EndDate",request.DateTo.ToString(EVCBConfiguration.DATETIMEFORMAT)}

                };
                var _innerresult = await service.PostFormDataAsync(url, postData, null);


                if (_innerresult.StatusCode == HttpStatusCode.OK)
                {
                    _innerresult.Response = _innerresult.Response.Replace("item", "Title");
                    _innerresult.Response = _innerresult.Response.Replace("Data", "DeliveredEnergy");
                    result.Data = _innerresult.Response;
                    result.StatusCode = (int)CPO_StatusCode.Success;
                    result.StatusMessage = CPO_StatusMessage.Success;
                    //statusCode = HttpStatusCode.OK;
                    statusCode = StatusCodes.Status200OK;
                }
                else
                {
                    result.StatusCode = (int)CPO_StatusCode.CANT_FOUND_DATA;
                    result.StatusMessage = CPO_StatusMessage.ERROR_MSG_INNERSERVICE_ERROR;
                    //statusCode = HttpStatusCode.BadRequest;
                    statusCode = StatusCodes.Status400BadRequest;
                }
            }
            catch (Exception ex)
            {
                result.ErrorDetail = ex.ToString();
                result.StatusMessage = CPO_StatusMessage.ERROR_MSG_UNEXPECTEDERROR;
                result.StatusCode = (int)CPO_StatusCode.UnexpectedError;
                //return Request.CreateResponse(statusCode, result);
                return StatusCode(statusCode, result);
            }

            //return Request.CreateResponse(statusCode, result);
            return StatusCode(statusCode, result);
        }

        [Route("statistics/time_of_use")]
        [Produces(typeof(CPOOuterResponse))]
        [HttpPost]
        async public Task<IActionResult> Time_of_Use([FromBody] StatisticsRequest request, [FromServices] IConfiguration configuration)
        {
            var result = new CPOOuterResponse();
            //HttpStatusCode statusCode = HttpStatusCode.InternalServerError;
            int statusCode = StatusCodes.Status500InternalServerError;
            var _innerData = new { Result = CommandResponseType.Rejected.ToString(), Timeout = 60 };
            try
            {

                InternalHttpClient _client = serviceProvider.GetRequiredService<InternalHttpClient>();
                ICustomerService _customer = serviceProvider.GetRequiredService<ICustomerService>();

                string url = configuration["StatisticsAPI"] + 3;
                string chargeBoxIds = GetStatisticChargeBoxIds(request.ChargeBoxIds);

                HttpClientService service = new HttpClientService();

                Dictionary<string, string> postData = new Dictionary<string, string>()
                {
                  { "ChargeBoxId",chargeBoxIds },
                  { "StartDate",request.DateFrom.ToString(EVCBConfiguration.DATETIMEFORMAT)},
                  { "EndDate",request.DateTo.ToString(EVCBConfiguration.DATETIMEFORMAT)}

                };
                var _innerresult = await service.PostFormDataAsync(url, postData, null);


                if (_innerresult.StatusCode == HttpStatusCode.OK)
                {
                    _innerresult.Response = _innerresult.Response.Replace("item", "Title");
                    _innerresult.Response = _innerresult.Response.Replace("data", "Count");
                    _innerresult.Response = _innerresult.Response.Replace("data2", "DeliveredEnergy");
                    result.Data = _innerresult.Response;
                    result.StatusCode = (int)CPO_StatusCode.Success;
                    result.StatusMessage = CPO_StatusMessage.Success;
                    //statusCode = HttpStatusCode.OK;
                    statusCode = StatusCodes.Status200OK;
                }
                else
                {
                    result.StatusCode = (int)CPO_StatusCode.CANT_FOUND_DATA;
                    result.StatusMessage = CPO_StatusMessage.ERROR_MSG_INNERSERVICE_ERROR;
                    //statusCode = HttpStatusCode.BadRequest;
                    statusCode = StatusCodes.Status400BadRequest;
                }
            }
            catch (Exception ex)
            {
                result.ErrorDetail = ex.ToString();
                result.StatusMessage = CPO_StatusMessage.ERROR_MSG_UNEXPECTEDERROR;
                result.StatusCode = (int)CPO_StatusCode.UnexpectedError;
                //return Request.CreateResponse(statusCode, result);
                return StatusCode(statusCode, result);
            }

            //return Request.CreateResponse(statusCode, result);
            return StatusCode(statusCode, result);
        }

        [Route("statistics/peak_load")]
        [Produces(typeof(CPOOuterResponse))]
        [HttpPost]
        async public Task<IActionResult> Peak_Load([FromBody] StatisticsRequest request, [FromServices] IConfiguration configuration)
        {
            var result = new CPOOuterResponse();
            //HttpStatusCode statusCode = HttpStatusCode.InternalServerError;
            int statusCode = StatusCodes.Status500InternalServerError;
            var _innerData = new { Result = CommandResponseType.Rejected.ToString(), Timeout = 60 };
            try
            {

                InternalHttpClient _client = serviceProvider.GetRequiredService<InternalHttpClient>();
                ICustomerService _customer = serviceProvider.GetRequiredService<ICustomerService>();

                string url = configuration["StatisticsAPI"] + 4;
                string chargeBoxIds = GetStatisticChargeBoxIds(request.ChargeBoxIds);

                HttpClientService service = new HttpClientService();

                Dictionary<string, string> postData = new Dictionary<string, string>()
                {
                  { "ChargeBoxId", chargeBoxIds },
                  { "StartDate",request.DateFrom.ToString(EVCBConfiguration.DATETIMEFORMAT)},
                  { "EndDate",request.DateTo.ToString(EVCBConfiguration.DATETIMEFORMAT)}

                };
                var _innerresult = await service.PostFormDataAsync(url, postData, null);


                if (_innerresult.StatusCode == HttpStatusCode.OK)
                {
                    _innerresult.Response = _innerresult.Response.Replace("item", "Title");
                    _innerresult.Response = _innerresult.Response.Replace("data", "DeliveredEnergy");
                    result.Data = _innerresult.Response;
                    result.StatusCode = (int)CPO_StatusCode.Success;
                    result.StatusMessage = CPO_StatusMessage.Success;
                    //statusCode = HttpStatusCode.OK;
                    statusCode = StatusCodes.Status200OK;
                }
                else
                {
                    result.StatusCode = (int)CPO_StatusCode.CANT_FOUND_DATA;
                    result.StatusMessage = CPO_StatusMessage.ERROR_MSG_INNERSERVICE_ERROR;
                    //statusCode = HttpStatusCode.BadRequest;
                    statusCode = StatusCodes.Status400BadRequest;
                }
            }
            catch (Exception ex)
            {
                result.ErrorDetail = ex.ToString();
                result.StatusMessage = CPO_StatusMessage.ERROR_MSG_UNEXPECTEDERROR;
                result.StatusCode = (int)CPO_StatusCode.UnexpectedError;
                //return Request.CreateResponse(statusCode, result);
                return StatusCode(statusCode, result);
            }

            //return Request.CreateResponse(statusCode, result);
            return StatusCode(statusCode, result);
        }

        [Route("statistics/sessions")]
        [Produces(typeof(CPOOuterResponse))]
        [HttpPost]
        async public Task<IActionResult> Sessions([FromBody] StatisticsRequest request, [FromServices] IConfiguration configuration)
        {
            var result = new CPOOuterResponse();
            //HttpStatusCode statusCode = HttpStatusCode.InternalServerError;
            int statusCode = StatusCodes.Status500InternalServerError;
            var _innerData = new { Result = CommandResponseType.Rejected.ToString(), Timeout = 60 };
            try
            {

                InternalHttpClient _client = serviceProvider.GetRequiredService<InternalHttpClient>();
                ICustomerService _customer = serviceProvider.GetRequiredService<ICustomerService>();

                string url = configuration["StatisticsAPI"] + 6;
                string chargeBoxIds = GetStatisticChargeBoxIds(request.ChargeBoxIds);

                HttpClientService service = new HttpClientService();

                Dictionary<string, string> postData = new Dictionary<string, string>()
                {
                  { "ChargeBoxId", chargeBoxIds },
                  { "StartDate",request.DateFrom.ToString(EVCBConfiguration.DATETIMEFORMAT)},
                  { "EndDate",request.DateTo.ToString(EVCBConfiguration.DATETIMEFORMAT)}

                };
                var _innerresult = await service.PostFormDataAsync(url, postData, null);


                if (_innerresult.StatusCode == HttpStatusCode.OK)
                {
                    string titles = "\"Title\":[\"ChargeBox Id\",\"Connector Id\",\"Session Id\",\"DateFrom\",\"DateTo\",\"Duration(sec)\",\"Energy(kWh)\",\"Stop Reason\"],";

                    _innerresult.Response = _innerresult.Response.Replace("data", "Session");
                    _innerresult.Response = _innerresult.Response.Insert(1, titles);
                    result.Data = _innerresult.Response;
                    result.StatusCode = (int)CPO_StatusCode.Success;
                    result.StatusMessage = CPO_StatusMessage.Success;
                    //statusCode = HttpStatusCode.OK;
                    statusCode = StatusCodes.Status200OK;
                }
                else
                {
                    result.StatusCode = (int)CPO_StatusCode.CANT_FOUND_DATA;
                    result.StatusMessage = CPO_StatusMessage.ERROR_MSG_INNERSERVICE_ERROR;
                    //statusCode = HttpStatusCode.BadRequest;
                    statusCode = StatusCodes.Status400BadRequest;
                }
            }
            catch (Exception ex)
            {
                result.ErrorDetail = ex.ToString();
                result.StatusMessage = CPO_StatusMessage.ERROR_MSG_UNEXPECTEDERROR;
                result.StatusCode = (int)CPO_StatusCode.UnexpectedError;
                //return Request.CreateResponse(statusCode, result);
                return StatusCode(statusCode, result);
            }

            //return Request.CreateResponse(statusCode, result);
            return StatusCode(statusCode, result);
        }

        [Route("statistics/fault")]
        [Produces(typeof(CPOOuterResponse))]
        [HttpPost]
        async public Task<IActionResult> Fault([FromBody] StatisticsRequest request, [FromServices] IConfiguration configuration)
        {
            var result = new CPOOuterResponse();
            //HttpStatusCode statusCode = HttpStatusCode.InternalServerError;
            int statusCode = StatusCodes.Status500InternalServerError;
            var _innerData = new { Result = CommandResponseType.Rejected.ToString(), Timeout = 60 };
            try
            {

                InternalHttpClient _client = serviceProvider.GetRequiredService<InternalHttpClient>();
                ICustomerService _customer = serviceProvider.GetRequiredService<ICustomerService>();

                string url = configuration["StatisticsAPI"] + 5;
                string chargeBoxIds = GetStatisticChargeBoxIds(request.ChargeBoxIds);

                HttpClientService service = new HttpClientService();

                Dictionary<string, string> postData = new Dictionary<string, string>()
                {
                  { "ChargeBoxId", chargeBoxIds},
                  { "StartDate",request.DateFrom.ToString(EVCBConfiguration.DATETIMEFORMAT)},
                  { "EndDate",request.DateTo.ToString(EVCBConfiguration.DATETIMEFORMAT)}

                };
                var _innerresult = await service.PostFormDataAsync(url, postData, null);


                if (_innerresult.StatusCode == HttpStatusCode.OK)
                {
                    _innerresult.Response = _innerresult.Response.Replace("item", "Title");
                    _innerresult.Response = _innerresult.Response.Replace("data", "Count");
                    _innerresult.Response = _innerresult.Response.Replace("data2", "CumulativePercentage");
                    result.Data = _innerresult.Response;
                    result.StatusCode = (int)CPO_StatusCode.Success;
                    result.StatusMessage = CPO_StatusMessage.Success;
                    //statusCode = HttpStatusCode.OK;
                    statusCode = StatusCodes.Status200OK;
                }
                else
                {
                    result.StatusCode = (int)CPO_StatusCode.CANT_FOUND_DATA;
                    result.StatusMessage = CPO_StatusMessage.ERROR_MSG_INNERSERVICE_ERROR;
                    //statusCode = HttpStatusCode.BadRequest;
                    statusCode = StatusCodes.Status400BadRequest;
                }
            }
            catch (Exception ex)
            {
                result.ErrorDetail = ex.ToString();
                result.StatusMessage = CPO_StatusMessage.ERROR_MSG_UNEXPECTEDERROR;
                result.StatusCode = (int)CPO_StatusCode.UnexpectedError;
                //return Request.CreateResponse(statusCode, result);
                return StatusCode(statusCode, result);
            }

            //return Request.CreateResponse(statusCode, result);
            return StatusCode(statusCode, result);
        }

        private string GetStatisticChargeBoxIds(List<string> chargeBoxIds)
        {
            string result = JsonConvert.SerializeObject(chargeBoxIds, Formatting.None).Replace("\"", "'");
            result = result.Replace("[", "");
            result = result.Replace("]", "");

            return result;
        }


        private CPOOuterResponse GetErrorDescription(InternalHttpResult innerResponse)
        {
            CPOOuterResponse result = new CPOOuterResponse();

            result.ErrorDetail = innerResponse.Exception == null ? null : innerResponse.Exception.ToString();

            if (innerResponse.Status != HttpStatusCode.Accepted)
            {
                switch (innerResponse.ErrorCode)
                {
                    #region Authorization
                    case 2000:
                        {
                            result.StatusCode = innerResponse.ErrorCode;
                            result.StatusMessage = string.Format("{0}-{1}", "InnerService", "Authorize Unexpected Error");
                            result.ErrorDetail = result.StatusMessage;
                        }
                        break;
                    case 2001:
                    case 2002:
                    case 2003:
                        {
                            result.StatusCode = innerResponse.ErrorCode;
                            result.StatusMessage = string.Format("{0}-{1}", "InnerService", innerResponse.Message);
                        }
                        break;

                    #endregion
                    case 2100:
                    case 2101:
                    case 2102:
                    case 2103:
                    case 2104:
                    case 2105:
                    case 2106:
                        {
                            result.StatusCode = innerResponse.ErrorCode;
                            result.StatusMessage = innerResponse.Message;
                        }
                        break;
                    case 2999:
                        {
                            result.StatusCode = innerResponse.ErrorCode;
                            result.StatusMessage = string.Format("{0}-{1}", "InnerService", "Unexpected Error");
                            result.ErrorDetail = result.StatusMessage;
                        }
                        break;
                    default:
                        {
                            result.StatusCode = 2998;
                            result.StatusMessage = CPO_StatusMessage.ERROR_MSG_CANT_FIND_ERRORCODE;
                        }
                        break;
                }
            }

            return result;


        }

        private bool ContainsChargePoint(string chargeBoxId, out string customerId)
        {
            customerId = string.Empty;
            if (!IsCustomerIdAvaliable()) 
                return false;
            customerId = GetCustomerId();

            return ContainsChargePointAsync(chargeBoxId, customerId).Result;
        }

        private ValueTask<bool> ContainsChargePointAsync(string chargeBoxId, string customerId)
        {
            ChargePointService _service = serviceProvider.GetRequiredService<ChargePointService>();//;new ChargePointService();
            return _service.ContainsChargePointAsync(chargeBoxId, customerId);
        }

        private string GetCustomerId()
        {
            if (!IsCustomerIdAvaliable())
                return string.Empty;
            return Request.Headers[EVCBConfiguration.Header_PartnerId].First();
        }

        private bool IsCustomerIdAvaliable()
        {
            return Request.Headers.ContainsKey(EVCBConfiguration.Header_PartnerId);
        }

        private ActiveSession ToActiveSession(string ChargeBoxId, TransasctionData trans)
        {
            string currencyText = string.IsNullOrEmpty(trans.Fee) ? "TWD" : trans.Fee.Remove(0, trans.Fee.Length - 3);

            var toRerurn = new ActiveSession()
            {
                ChargeBoxId = ChargeBoxId,
                SessionId = trans.Id,
                ElaspedTime = (int)DateTime.UtcNow.Subtract(trans.StartTime).TotalMinutes,
                ConnectorId = trans.ConnectorId,
                IdTag = trans.StartIdTag,
                Currency = currencyText
            };

            toRerurn.Power = "0";
            toRerurn.Power_Format = UnitOfMeasure.W.ToString();
            toRerurn.Current = "0";
            toRerurn.Current_Format = UnitOfMeasure.A.ToString();
            toRerurn.Energy = "0";
            toRerurn.Energy_Format = UnitOfMeasure.Wh.ToString();
            toRerurn.Voltage = "0";
            toRerurn.Voltage_Format = UnitOfMeasure.V.ToString();
            toRerurn.SOC = "0";
            toRerurn.SOC_Format = UnitOfMeasure.Percent.ToString();
            toRerurn.CurrentCost = "0";

            Models.ConnectorMeterValue power = trans.MeterValues.FirstOrDefault(x => x.Measurand == Measurand.Power_Active_Import);
            if (power is not null)
            {
                toRerurn.Power = power.Value;
                toRerurn.Power_Format = power.Unit.ToString();
            }
            Models.ConnectorMeterValue current = trans.MeterValues.FirstOrDefault(x => x.Measurand == Measurand.Current_Import);
            if (current is not null)
            {
                toRerurn.Current = current.Value;
                toRerurn.Current_Format = current.Unit.ToString();
            }
            Models.ConnectorMeterValue _energy = trans.MeterValues.FirstOrDefault(x => x.Measurand == Measurand.TotalEnergy);
            if (_energy is not null)
            {
                toRerurn.Energy = _energy.Value;
                toRerurn.Energy_Format = _energy.Unit.ToString();
            }
            Models.ConnectorMeterValue voltage = trans.MeterValues.FirstOrDefault(x => x.Measurand == Measurand.Voltage);
            if (voltage is not null)
            {
                toRerurn.Voltage = voltage.Value;
                toRerurn.Voltage_Format = voltage.Unit.ToString();
            }
            Models.ConnectorMeterValue soc = trans.MeterValues.FirstOrDefault(x => x.Measurand == Measurand.SoC);
            if (soc is not null)
            {
                toRerurn.SOC = soc.Value;
                toRerurn.SOC_Format = soc.Unit.ToString();
            }
            Models.ConnectorMeterValue cost = trans.MeterValues.FirstOrDefault(x => x.Measurand == Measurand.ChargingCost);
            if (cost is not null)
            {
                toRerurn.CurrentCost = cost.Value;
            }

            if (toRerurn.Energy_Format == UnitOfMeasure.Wh.ToString())
            {
                decimal energy = decimal.Parse(toRerurn.Energy);
                energy = Decimal.Divide(energy, 1000);
                toRerurn.Energy = energy.ToString("0.000");
                toRerurn.Energy_Format = UnitOfMeasure.kWh.ToString();
            }

            return toRerurn;
        }
    }
}
