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

namespace StandardScene.Signal.Logic
{
    /// <summary>
    /// 站点定时充电。对齐反编译 <c>DefaultPlugin.TimedCharging</c>。
    /// </summary>
    /// <remarks>
    /// <c>SignalParams</c>：<c>最长秒数;上限电量;下限电量</c>，某段填 0 表示该条件不启用。
    /// 正在充电：电量 ≥ 上限则停充；时长到且电量已过下限则停充；时长到但电量仍 ≤ 下限则继续充。
    /// 已停充且车仍停着：视为充电流程结束，启动放行。
    /// 充电秒数优先反射 <c>GetChargeTime</c>，没有则用 <paramref name="chargeStarted"/> 字典估算。
    /// </remarks>
    public static class TimedChargeHandler
    {
        /// <summary>停稳且本站是 TimedCharging 时由扫车线程调用。</summary>
        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);
            }
        }
    }
}
