using EVCB_OCPP.WEBAPI.Handlers;
using EVCB_OCPP.WEBAPI.Models.WebAPI;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using Newtonsoft.Json;
using System.Threading.Tasks;
using EVCB_OCPP.WEBAPI.Models.WebAPI.Dto;
using System.Net.Http.Headers;
using EVCB_OCPP.Packet.Messages.SubTypes;
using System.Security.Cryptography.X509Certificates;
using OCPPPackage.Profiles;
using EVCB_OCPP.Packet.Messages.Core;
using EVCB_OCPP.Packet.Messages;
using EVCB_OCPP.WEBAPI.Services.Integration;
using EVCB_OCPP.WEBAPI.Services;
using ChargingStationService = EVCB_OCPP.WEBAPI.Services.Integration.ChargingStationService;
using ServerTriggerService = EVCB_OCPP.WEBAPI.Services.Integration.ServerTriggerService;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Extensions;
using Microsoft.Extensions.Configuration;
using System.Security.Policy;
using Microsoft.Extensions.DependencyInjection;

namespace EVCB_OCPP.WEBAPI.Controllers.Version2.ocpp16
{
    [ServiceFilter(typeof(CPOAuthentication))]
    [ApiExplorerSettings(IgnoreApi = false)]
    [Route("api/v2/cpo16")]
    //[CPOAuthentication]
    public class OCPP16_CPOController : ControllerBase
    {
        private HttpClientService service = new HttpClientService();
        private readonly IServiceProvider serviceProvider;

        public OCPP16_CPOController(IServiceProvider serviceProvider)
        {
            this.serviceProvider = serviceProvider;
        }

        private bool ContainsChargePoint(string chargeBoxId, out string customerId)
        {

            customerId = string.Empty;

            if (!Request.Headers.ContainsKey(EVCBConfiguration.Header_PartnerId)) return false;

            customerId = Request.Headers[EVCBConfiguration.Header_PartnerId].First();

            ChargePoint16Service _service = serviceProvider.GetRequiredService<ChargePoint16Service>();
            return _service.ContainsChargePoint(chargeBoxId, customerId);

        }



        [Route("station")]
        [Produces(typeof(CPOOuterResponse))]
        [HttpGet]
        public IActionResult Station([FromServices]IServiceProvider serviceProvider)
        {
            var result = new CPOOuterResponse();
            //HttpStatusCodeHttpStatusCode statusCode = HttpStatusCode.InternalServerError;
            int statusCode = StatusCodes.Status500InternalServerError;
            try
            {
                if (Request.Headers.ContainsKey(EVCBConfiguration.Header_PartnerId))
                {
                    var _customerId = Request.Headers[EVCBConfiguration.Header_PartnerId].First();
                    ChargingStationService _service = serviceProvider.GetRequiredService<ChargingStationService>();//new ChargingStationService();
                    var _innerResponse = new { Stations = _service.GetStationsbyCustomerId(_customerId) };
                    result.Data = JsonConvert.SerializeObject(_innerResponse, EVCBConfiguration.JSONSERIALIZER_FORMAT);
                    result.StatusCode = (int)CPO_StatusCode.Success;
                    result.StatusMessage = CPO_StatusMessage.Success;
                    //statusCode = StatusCodes.Status200OK;
                    statusCode = StatusCodes.Status200OK;
                }
                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 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
            {
                ChargePoint16Service _CPService = serviceProvider.GetRequiredService<ChargePoint16Service>();
                var tt = _CPService.GetLastUpdatedTimebyMachineId("0da4f4a6-a952-46f0-b2f3-696385a9a56a");
                if (Request.Headers.ContainsKey(EVCBConfiguration.Header_PartnerId))
                {
                    var _customerId = Request.Headers[EVCBConfiguration.Header_PartnerId].First();

                    var _innerResponse = new { EVSEs = new List<EVSE>() };
                    ChargingStationService _stationService = serviceProvider.GetRequiredService<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 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 = StatusCodes.Status200OK;
                    statusCode = StatusCodes.Status200OK;

                }
                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 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 = 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 StatusCode(statusCode, result);
                }

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

                if (!string.IsNullOrEmpty(request.ChargeBoxId) && request.ChargeBoxId.Length <= 25
                   && _CPService.GetNumberofConnectors(request.ChargeBoxId) >= request.ConnectorId && request.ConnectorId > 0
                    && !string.IsNullOrEmpty(request.Token) && request.Token.Length <= 20)
                {

                    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 = StatusCodes.Status200OK;
                        statusCode = StatusCodes.Status200OK;

                    }



                }
                else
                {
                    // 參數不符合定義
                    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);
            }
            catch (Exception ex)
            {
                result.ErrorDetail = ex.ToString();
                result.StatusMessage = CPO_StatusMessage.ERROR_MSG_UNEXPECTEDERROR;
                result.StatusCode = (int)CPO_StatusCode.UnexpectedError;
                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 = 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 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.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 = StatusCodes.Status200OK;
                    statusCode = StatusCodes.Status200OK;

                }


            }
            catch (Exception ex)
            {
                result.ErrorDetail = ex.ToString();
                result.StatusMessage = CPO_StatusMessage.ERROR_MSG_UNEXPECTEDERROR;
                result.StatusCode = (int)CPO_StatusCode.UnexpectedError;
                return StatusCode(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 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.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 = StatusCodes.Status200OK;
                    statusCode = StatusCodes.Status200OK;
                }
            }
            catch (Exception ex)
            {
                result.ErrorDetail = ex.ToString();
                result.StatusMessage = CPO_StatusMessage.ERROR_MSG_UNEXPECTEDERROR;
                result.StatusCode = (int)CPO_StatusCode.UnexpectedError;
                return StatusCode(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 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 = StatusCodes.Status200OK;
                }
                else
                {

                    result.StatusCode = _innerResult.ErrorCode;
                    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 StatusCode(statusCode, result);
            }

            return StatusCode(statusCode, result);
        }


        [Route("commands/chargingprofiles")]
        [Produces(typeof(CPOOuterResponse))]
        [HttpGet]
        async public Task<IActionResult> GetActiveChargingPorfile(string ChargeBoxId, int ConnectorId, int Duration)
        {
            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 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}", 
                    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 = StatusCodes.Status200OK;
                    statusCode = StatusCodes.Status200OK;
                }
                else
                {

                    result.StatusCode = _innerResult.ErrorCode;
                    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 StatusCode(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 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 = StatusCodes.Status200OK;
                    statusCode = StatusCodes.Status200OK;
                }
                else
                {

                    result.StatusCode = _innerResult.ErrorCode;
                    result.StatusMessage = CPO_StatusMessage.ERROR_MSG_INNERSERVICE_ERROR;
                    //statusCode = HttpStatusCode.BadRequest;
                    statusCode = StatusCodes.Status400BadRequest;
                }
                ChargePoint16Service chargePointService = serviceProvider.GetRequiredService<ChargePoint16Service>();

                if (!chargePointService.IsOnline(ChargeBoxId))
                {
                    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 StatusCode(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 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={0}{1}", 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 = StatusCodes.Status200OK;
                    statusCode = StatusCodes.Status200OK;
                }
                else
                {

                    result.StatusCode = _innerResult.ErrorCode;
                    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 StatusCode(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 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 = StatusCodes.Status200OK;
                    statusCode = StatusCodes.Status200OK;
                }
                else
                {

                    result.StatusCode = _innerResult.ErrorCode;
                    result.StatusMessage = CPO_StatusMessage.ERROR_MSG_INNERSERVICE_ERROR;
                    //statusCode = HttpStatusCode.BadRequest;
                    statusCode = StatusCodes.Status200OK;
                }
            }
            catch (Exception ex)
            {
                result.ErrorDetail = ex.ToString();
                result.StatusMessage = CPO_StatusMessage.ERROR_MSG_UNEXPECTEDERROR;
                result.StatusCode = (int)CPO_StatusCode.UnexpectedError;
                return StatusCode(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 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 = StatusCodes.Status200OK;
                    statusCode = StatusCodes.Status200OK;
                }
                else
                {

                    result.StatusCode = _innerResult.ErrorCode;
                    result.StatusMessage = CPO_StatusMessage.ERROR_MSG_INNERSERVICE_ERROR;
                    //statusCode = HttpStatusCode.BadRequest;
                    statusCode = StatusCodes.Status400BadRequest;
                }

                //statusCode = StatusCodes.Status200OK;
                statusCode = StatusCodes.Status200OK;
            }
            catch (Exception ex)
            {
                result.ErrorDetail = ex.ToString();
                result.StatusMessage = CPO_StatusMessage.ERROR_MSG_UNEXPECTEDERROR;
                result.StatusCode = (int)CPO_StatusCode.UnexpectedError;
                return StatusCode(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 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 = StatusCodes.Status200OK;
                        statusCode = StatusCodes.Status200OK;
                    }

                }


            }
            catch (Exception ex)
            {
                result.ErrorDetail = ex.ToString();
                result.StatusMessage = CPO_StatusMessage.ERROR_MSG_UNEXPECTEDERROR;
                result.StatusCode = (int)CPO_StatusCode.UnexpectedError;
                return StatusCode(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
            {
                ChargePoint16Service _service = serviceProvider.GetRequiredService<ChargePoint16Service>();
                string version = _service.GetVersionbyChargeBoxId(ChargeBoxId);

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

            return StatusCode(statusCode, result);

        }


        [Route("activesession")]
        [Produces(typeof(CPOOuterResponse))]
        [HttpGet]
        public IActionResult ActiveSession(string ChargeBoxId, string SessionId = "", string IdTag = "")
        {
            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 StatusCode(statusCode, result);
                }

                // query meter value
                ChargePoint16Service _service = serviceProvider.GetRequiredService<ChargePoint16Service>();
                var transactionDatas = _service.GetActiveSessionInfo(ChargeBoxId, new List<Packet.Messages.SubTypes.Measurand>()
                {   Packet.Messages.SubTypes.Measurand.Voltage,
                    Packet.Messages.SubTypes.Measurand.Current_Import,
                    Packet.Messages.SubTypes.Measurand.SoC,
                    Packet.Messages.SubTypes.Measurand.Power_Active_Import,
                    Packet.Messages.SubTypes.Measurand.TotalEnergy
                }, SessionId, IdTag);

                if (transactionDatas == null)
                {
                    result.StatusCode = (int)CPO_StatusCode.CANT_FOUND_DATA;
                    result.StatusMessage = CPO_StatusMessage.ERROR_MSG_CANT_FIND_RESULT;
                    //statusCode = HttpStatusCode.NotFound;
                    statusCode = StatusCodes.Status404NotFound;
                }
                else
                {
                    List<ActiveSession> _innerData = new List<ActiveSession>();

                    foreach (var transactionData in transactionDatas)
                    {


                        _innerData.Add(new ActiveSession()
                        {
                            ChargeBoxId = ChargeBoxId,
                            SessionId = transactionData.Id,
                            ElaspedTime = (int)DateTime.UtcNow.Subtract(transactionData.StartTime).TotalMinutes,
                            ConnectorId = transactionData.ConnectorId,
                            IdTag = transactionData.StartIdTag,
                            Power = transactionData.MeterValues == null ? "0" : transactionData.MeterValues.Where(x => x.Measurand == Packet.Messages.SubTypes.Measurand.Power_Active_Import).Select(x => x.Value).FirstOrDefault(),
                            Power_Format = transactionData.MeterValues == null ? UnitOfMeasure.W.ToString() : transactionData.MeterValues.Where(x => x.Measurand == Packet.Messages.SubTypes.Measurand.Power_Active_Import).Select(x => x.Unit.ToString()).FirstOrDefault(),
                            Current = transactionData.MeterValues == null ? "0" : transactionData.MeterValues.Where(x => x.Measurand == Packet.Messages.SubTypes.Measurand.Current_Import).Select(x => x.Value).FirstOrDefault(),
                            Current_Format = transactionData.MeterValues == null ? UnitOfMeasure.A.ToString() : transactionData.MeterValues.Where(x => x.Measurand == Packet.Messages.SubTypes.Measurand.Current_Import).Select(x => x.Unit.ToString()).FirstOrDefault(),
                            Energy = transactionData.MeterValues == null ? "0" : transactionData.MeterValues.Where(x => x.Measurand == Packet.Messages.SubTypes.Measurand.TotalEnergy).Select(x => x.Value).FirstOrDefault(),
                            Energy_Format = transactionData.MeterValues == null ? UnitOfMeasure.Wh.ToString() : transactionData.MeterValues.Where(x => x.Measurand == Packet.Messages.SubTypes.Measurand.TotalEnergy).Select(x => x.Unit.ToString()).FirstOrDefault(),
                            Voltage = transactionData.MeterValues == null ? "0" : transactionData.MeterValues.Where(x => x.Measurand == Packet.Messages.SubTypes.Measurand.Voltage).Select(x => x.Value).FirstOrDefault(),
                            Voltage_Format = transactionData.MeterValues == null ? UnitOfMeasure.V.ToString() : transactionData.MeterValues.Where(x => x.Measurand == Packet.Messages.SubTypes.Measurand.Voltage).Select(x => x.Unit.ToString()).FirstOrDefault(),
                            SOC = transactionData.MeterValues == null ? "0" : transactionData.MeterValues.Where(x => x.Measurand == Packet.Messages.SubTypes.Measurand.SoC).Select(x => x.Unit.ToString()).FirstOrDefault() == null ? null : transactionData.MeterValues.Where(x => x.Measurand == Packet.Messages.SubTypes.Measurand.SoC).Select(x => x.Value).FirstOrDefault(),
                            SOC_Format = transactionData.MeterValues == null ? UnitOfMeasure.Percent.ToString() : transactionData.MeterValues.Where(x => x.Measurand == Packet.Messages.SubTypes.Measurand.SoC).Select(x => x.Unit.ToString()).FirstOrDefault(),
                        });

                    }
                    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 = StatusCodes.Status200OK;
                    statusCode = StatusCodes.Status200OK;

                }

                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 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 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
                ChargePoint16Service _service = serviceProvider.GetRequiredService<ChargePoint16Service>();
                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 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 = StatusCodes.Status200OK;
                statusCode = StatusCodes.Status200OK;
                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 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 = StatusCodes.Status200OK;
                    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 StatusCode(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 = StatusCodes.Status200OK;
                    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 StatusCode(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 = StatusCodes.Status200OK;
                    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 StatusCode(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 = StatusCodes.Status200OK;
                    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 StatusCode(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 = StatusCodes.Status200OK;
                    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 StatusCode(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 = StatusCodes.Status200OK;
                    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 StatusCode(statusCode, result);
            }

            return StatusCode(statusCode, result);
        }

        #region CDFA
        [Route("commands/defaulprice")]
        [Produces(typeof(CPOOuterResponse))]
        [HttpPost]
        async public Task<IActionResult> ChargePointDefaultPrice(string ChargeBoxId, [FromBody] ChargePointDefaultPriceRequest 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 StatusCode(statusCode, result);
                }


                ChargePoint16Service chargePointService = serviceProvider.GetRequiredService<ChargePoint16Service>();

                if (!chargePointService.IsOnline(ChargeBoxId))
                {

                    return StatusCode(StatusCodes.Status400BadRequest, new ErrorResponse() { Code = 2101, Message = EVCBConfiguration.ERROR_MSG_CHARGEBOXID_ISNT_EXIST_OR_OFFLINE });
                }
                //create reqest
                var _request = new DataTransferRequest()
                {
                    messageId = "DefaultPrice",
                    vendorId = "Phihong Technology",
                    data = request.DefaultPrice
                };

                string uuid = Guid.NewGuid().ToString();
                if (!AddCommandtoServer(ChargeBoxId, uuid, _request))
                {
                    throw new Exception("Write Command Fail!!");
                }

                result.SerialNo = uuid;
                result.Data = JsonConvert.SerializeObject(new { Result = CommandResponseType.Accepted.ToString(), Timeout = 60 });
                await Task.Delay(10);

            }
            catch (Exception ex)
            {
                result.Data = JsonConvert.SerializeObject(_innerData);
                result.ErrorDetail = ex.ToString();
                result.StatusMessage = CPO_StatusMessage.ERROR_MSG_UNEXPECTEDERROR;
                result.StatusCode = (int)CPO_StatusCode.UnexpectedError;
                return StatusCode(statusCode, result);
            }

            return StatusCode(statusCode, result);
        }


        [Route("commands/userprice")]
        [Produces(typeof(CPOOuterResponse))]
        [HttpPost]
        async public Task<IActionResult> UserPrice(string ChargeBoxId, [FromBody] UserPriceRequest 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 StatusCode(statusCode, result);
                }


                ChargePoint16Service chargePointService = serviceProvider.GetRequiredService<ChargePoint16Service>();

                if (!chargePointService.IsOnline(ChargeBoxId))
                {

                    return StatusCode(StatusCodes.Status400BadRequest, new ErrorResponse() { Code = 2101, Message = EVCBConfiguration.ERROR_MSG_CHARGEBOXID_ISNT_EXIST_OR_OFFLINE });
                }
                //create reqest
                var _request = new DataTransferRequest()
                {
                    messageId = "SetUserPrice",
                    vendorId = "Phihong Technology",
                    data = JsonConvert.SerializeObject(request)
                };

                string uuid = Guid.NewGuid().ToString();
                if (!AddCommandtoServer(ChargeBoxId, uuid, _request))
                {
                    throw new Exception("Write Command Fail!!");
                }

                result.SerialNo = uuid;
                result.Data = JsonConvert.SerializeObject(new { Result = CommandResponseType.Accepted.ToString(), Timeout = 60 });
                await Task.Delay(10);

            }
            catch (Exception ex)
            {
                result.Data = JsonConvert.SerializeObject(_innerData);
                result.ErrorDetail = ex.ToString();
                result.StatusMessage = CPO_StatusMessage.ERROR_MSG_UNEXPECTEDERROR;
                result.StatusCode = (int)CPO_StatusCode.UnexpectedError;
                return StatusCode(statusCode, result);
            }

            return StatusCode(statusCode, result);
        }

        [Route("commands/finalcost")]
        [Produces(typeof(CPOOuterResponse))]
        [HttpPost]
        async public Task<IActionResult> FinalCost(string ChargeBoxId, [FromBody] FinalCostRequest 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 StatusCode(statusCode, result);
                }


                ChargePoint16Service chargePointService = serviceProvider.GetRequiredService<ChargePoint16Service>();

                if (!chargePointService.IsOnline(ChargeBoxId))
                {

                    return StatusCode(StatusCodes.Status400BadRequest, new ErrorResponse() { Code = 2101, Message = EVCBConfiguration.ERROR_MSG_CHARGEBOXID_ISNT_EXIST_OR_OFFLINE });
                }

                string text = JsonConvert.SerializeObject(request).Replace("SessionId", "txId");
                //create reqest
                var _request = new DataTransferRequest()
                {
                    messageId = "DefaultPrice",
                    vendorId = "Phihong Technology",
                    data = text
                };

                string uuid = Guid.NewGuid().ToString();
                if (!AddCommandtoServer(ChargeBoxId, uuid, _request))
                {
                    throw new Exception("Write Command Fail!!");
                }

                result.SerialNo = uuid;
                result.Data = JsonConvert.SerializeObject(new { Result = CommandResponseType.Accepted.ToString(), Timeout = 60 });
                await Task.Delay(10);

            }
            catch (Exception ex)
            {
                result.Data = JsonConvert.SerializeObject(_innerData);
                result.ErrorDetail = ex.ToString();
                result.StatusMessage = CPO_StatusMessage.ERROR_MSG_UNEXPECTEDERROR;
                result.StatusCode = (int)CPO_StatusCode.UnexpectedError;
                return StatusCode(statusCode, result);
            }

            return StatusCode(statusCode, result);
        }
        #endregion


        private bool AddCommandtoServer(string chargeBoxId, string uuid, IRequest request)
        {
            bool result = false;
            try
            {
                ServerTriggerService service = serviceProvider.GetRequiredService<ServerTriggerService>();
                service.AddMessage(chargeBoxId, uuid, request);
                result = true;
            }
            catch (Exception ex)
            {
                ;
            }

            return 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;


        }




    }
}
