using MainShell.Filewritable;
using MainShell.AlgorithmCalib.Model;
using MainShell.AlgorithmCalib.Service;
using MaxwellFramework.Core.Interfaces;
using MwFramework.Controls.SystemCalib;
using MwFramework.ManagerService;
using SemiconductorVisionAlgorithm.SemiParams;
using Stylet;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using Point = SemiconductorVisionAlgorithm.SemiParams.Point;

namespace MainShell.AlgorithmCalib.ViewModel
{
    public class MotionCalibViewModel : Screen, IPage, IHandle<MotionCalibFinishEventArgs>
    {
        public string Name { get; set; } = "CameraMotionCalib";
        public string CalibName { get; private set; }
        public string CalibId { get; private set; }
        public string FileSaveName { get; private set; }

        private MotionSysDataItem _inputParam;
        public MotionSysDataItem InputParam
        {
            get => _inputParam;
            set => SetAndNotify(ref _inputParam, value);
        }

        private MotionSysDataItem _resultParam;
        public MotionSysDataItem ResultParam
        {
            get => _resultParam;
            set => SetAndNotify(ref _resultParam, value);
        }

        private MotionSysDataItem _motionSysDataItem;
        public MotionSysDataItem MotionSysDataItem
        {
            get => _motionSysDataItem;
            set => SetAndNotify(ref _motionSysDataItem, value);
        }

        private MotionSysCalibViewModel _service;
        public MotionSysCalibViewModel Service
        {
            get => _service;
            set => SetAndNotify(ref _service, value);
        }

        private List<Point> _calibAxisPoints;
        public List<Point> CalibAxisPoints
        {
            get => _calibAxisPoints;
            set => SetAndNotify(ref _calibAxisPoints, value);
        }

        private List<Point> _calibRealPoints;
        public List<Point> CalibRealPoints
        {
            get => _calibRealPoints;
            set => SetAndNotify(ref _calibRealPoints, value);
        }

        private string _fileSaveDir = Paths.CalibSettingPath;
        public string FileSaveDir
        {
            get => _fileSaveDir;
            set => SetAndNotify(ref _fileSaveDir, value);
        }

        private bool _isCalibFinished;
        public bool IsCalibFinished
        {
            get => _isCalibFinished;
            set => SetAndNotify(ref _isCalibFinished, value);
        }

        public MotionCalibViewModel() { }

        /// <summary>
        /// 普通创建：不订阅事件，不使用用户ID
        /// </summary>
        public static MotionCalibViewModel Create(
            string calibName, string fileSaveName, List<HardwareDevice> device)
        {
            var vm = new MotionCalibViewModel();
            vm.Initialize(calibName, fileSaveName, device,
                          subscribeEvents: false, calibId: "", isUseUserId: false);
            return vm;
        }

        /// <summary>
        /// 弹窗专用：传入标定参数，订阅事件，使用用户ID
        /// </summary>
        public static MotionCalibViewModel Create(
            string calibName, string fileSaveName, List<HardwareDevice> device,
            MotionSysDataItem param, string calibId = "")
        {
            var vm = new MotionCalibViewModel();
            vm.Initialize(calibName, fileSaveName, device,
                          subscribeEvents: true, calibId: calibId, isUseUserId: true);
            vm.InputParam = param;
            return vm;
        }

        private void Initialize(
            string calibName, string fileSaveName, List<HardwareDevice> device,
            bool subscribeEvents, string calibId = "", bool isUseUserId = false)
        {
            if (subscribeEvents)
            {
                IoC.Get<IEventAggregator>().Unsubscribe(this);
                IoC.Get<IEventAggregator>().Subscribe(this);
            }

            CalibName = calibName;
            CalibId = calibId;
            FileSaveName = fileSaveName;

            var paramList = IoC.Get<IParameterManager>() as IParamList;
            Service = isUseUserId
                ? new MotionSysCalibViewModel(device, paramList, true, true, calibId)
                : new MotionSysCalibViewModel(device, paramList, true);

            string pathSavePath = Path.Combine(FileSaveDir, FileSaveName + ".xml");
            Service.SetParaSavePath(pathSavePath);
            Service.IsShowSolidLine = true;
            Service.ShapeThickness = 1;
            Service.DrawInConcurrency = false;
            Service.IsAxisControlLDBVisible = Visibility.Visible;
        }

        public void FetchCalibResult()
        {
            if (Service == null || !Service.IsCalibTaskCompleted)
                return;

            var (axisPoints, realPoints) = Service.GetCalibResult();
            CalibAxisPoints = axisPoints;
            CalibRealPoints = realPoints;

            var filePath = Path.Combine(FileSaveDir, $"{FileSaveName}.csv");
            MotionCalibFileService.SaveCalibPointsFile(filePath, CalibRealPoints, CalibAxisPoints);
        }

        public void Handle(MotionCalibFinishEventArgs message)
        {
            FetchCalibResult();
        }

        // 修复：页面关闭时取消事件订阅，防止内存泄漏
        protected override void OnDeactivate()
        {
            IoC.Get<IEventAggregator>().Unsubscribe(this);
            base.OnDeactivate();
        }
    }

}
