using System;
using System.Collections.Generic;
using SimpleCore.Library;
using SimpleLite.RCS.CarTypes;
using StandardScene.Signal.Plc;

namespace StandardScene.Signal.Logic
{
    /// <summary>对齐反编译 DefaultPlugin.TimedCharging：时长 / 上限电量 / 下限电量。</summary>
    public static class TimedChargeHandler
    {
        public static void OnStopped(Car car, SignalStopSpec spec, IDictionary<int, DateTime> chargeStarted)
        {
            int.TryParse(spec.Part(0), out var maxSeconds);
            int.TryParse(spec.Part(1), out var maxSoc);
            int.TryParse(spec.Part(2), out var minSoc);

            var charged = SignalCarAdapter.ChargeSeconds(car, chargeStarted);
            var soc = SignalCarAdapter.Soc(car);
            var pos = SignalCarAdapter.PositionId(car);

            if (SignalCarAdapter.IsCharging(car))
            {
                Diagnosis.Log(
                    $"AGV{car.id}实时电量{soc}停在地标{pos}上已充电{charged}秒，信号停止类型为定时充电，参数为：{maxSeconds}，{maxSoc}，{minSoc}",
                    "Charge", true);

                if (maxSoc != 0 && soc >= maxSoc)
                {
                    Diagnosis.Log($"AGV{car.id}电量大于配置的最高充电电量，故停止充电", "Charge", true);
                    SignalCarAdapter.StopCharge(car);
                    return;
                }

                if (maxSeconds != 0 && charged >= maxSeconds)
                {
                    if (minSoc != 0 && soc <= minSoc)
                    {
                        Diagnosis.Log($"AGV{car.id}充电时长已到达{maxSeconds}秒，但仍未充电至{minSoc}继续充电", "Charge", true);
                        return;
                    }

                    Diagnosis.Log($"AGV{car.id}充电时长已到达{maxSeconds}秒，故停止充电", "Charge", true);
                    SignalCarAdapter.StopCharge(car);
                }

                return;
            }

            if (SignalCarAdapter.IsStopped(car))
            {
                Diagnosis.Log($"AGV{car.id}已经停止充电，故放行AGV", "Charge", true);
                SignalCarAdapter.Start(car);
            }
        }
    }
}
