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

namespace StandardScene.Signal.Logic
{
    /// <summary>对齐反编译 DefaultPlugin.JGControl / JGJudge / RequestIn / Arrived。</summary>
    public static class JgControlHandler
    {
        public static void OnStopped(Car car, SignalStopSpec spec, Func<string, PlcStationRuntime> find, IDictionary<string, int> rateFlowLog)
        {
            var jgName = spec.Part(0).Trim();
            var action = spec.Part(1).Trim();
            var rateFlow = spec.Part(2).Trim();
            if (string.IsNullOrEmpty(jgName))
            {
                Diagnosis.Log($"AGV{car.id}停在地标{SignalCarAdapter.PositionId(car)}，读取配置机构名称为空", "JGControl", true);
                return;
            }

            if (!string.IsNullOrEmpty(rateFlow) && !RateFlowHandler.AllowPass(car, rateFlow, rateFlowLog))
            {
                Diagnosis.Log($"AGV{car.id}停在地标{SignalCarAdapter.PositionId(car)}，限流禁止通行", "JGControl", true);
                return;
            }

            if (string.Equals(action, "RequestIn", StringComparison.OrdinalIgnoreCase))
                RequestIn(jgName, car, find);
            else if (string.Equals(action, "Arrived", StringComparison.OrdinalIgnoreCase))
                Arrived(jgName, car, find);
        }

        public static void OnMoving(Car car, SignalStopSpec spec, Func<string, PlcStationRuntime> find)
        {
            var jgName = spec.Part(0).Trim();
            var action = spec.Part(1).Trim();
            if (string.IsNullOrEmpty(jgName))
                return;
            if (string.Equals(action, "RequestIn", StringComparison.OrdinalIgnoreCase))
                RequestInJudge(jgName, car, find);
        }

        private static void RequestIn(string jgName, Car car, Func<string, PlcStationRuntime> find)
        {
            var rt = find(jgName);
            if (rt == null)
            {
                Diagnosis.Log($"{jgName} 未能找到机构", "JGControl", true);
                return;
            }

            lock (rt.Sync)
            {
                if (rt.ReadSignal == SignalReadValue.允许进入 &&
                    rt.RequestInAgvNo == 0 &&
                    rt.ReadWriteSignal == SignalWriteValue.无状态)
                {
                    if (rt.Config.LineType is SignalLineType.单牵引下线机构 or SignalLineType.双牵引下线机构)
                    {
                        var inside = SignalCarAdapter.CarsAt(rt.Config.JgPointId);
                        if (inside.Count > 0)
                        {
                            Diagnosis.Log(
                                $"{jgName} 机构内有AGV【{string.Join(",", inside.Select(x => x.id))}】暂不放行AGV{car.id}",
                                "JGControl", true);
                            return;
                        }
                    }

                    Diagnosis.Log($"{jgName} 机构允许进入，通知AGV{car.id}启动，通知机构AGV进入中", "JGControl", true);
                    rt.WriteSignal = SignalWriteValue.进入中;
                    rt.RequestInAgvNo = car.id;
                    SignalCarAdapter.StopCharge(car);
                    SignalCarAdapter.Start(car);
                    return;
                }

                if (rt.ReadSignal != SignalReadValue.允许进入 &&
                    rt.RequestInAgvNo != car.id &&
                    SignalCarAdapter.IsMoving(car))
                {
                    SignalCarAdapter.Stop(car);
                    Diagnosis.Log($"{jgName} 机构不允许进入，监控到AGV启动，暂停AGV{car.id}", "JGControl", true);
                }
            }
        }

        private static void RequestInJudge(string jgName, Car car, Func<string, PlcStationRuntime> find)
        {
            var rt = find(jgName);
            if (rt == null)
            {
                Diagnosis.Log($"{jgName} 未能找到机构", "JGControl", true);
                return;
            }

            lock (rt.Sync)
            {
                if (rt.ReadSignal != SignalReadValue.允许进入 &&
                    rt.RequestInAgvNo != car.id &&
                    SignalCarAdapter.IsMoving(car))
                {
                    SignalCarAdapter.Stop(car);
                    Diagnosis.Log($"{jgName} 机构不允许进入，监控到AGV启动，暂停AGV{car.id}", "JGControl", true);
                }
            }
        }

        private static void Arrived(string jgName, Car car, Func<string, PlcStationRuntime> find)
        {
            var rt = find(jgName);
            if (rt == null)
            {
                Diagnosis.Log($"{jgName} 未能找到机构", "JGControl", true);
                return;
            }

            lock (rt.Sync)
            {
                if (rt.InAgvNo == car.id)
                    return;
                Diagnosis.Log($"AGV{car.id}已到达机构{jgName}", "JGControl", true);
                rt.WriteSignal = SignalWriteValue.到位;
                rt.InAgvNo = car.id;
                rt.RequestInAgvNo = 0;
            }
        }
    }
}
