using System;
using System.Collections.Generic;
using CncService.Interface;
using CncModels.Dto;
using CncModels.Dto.Production;
using CncModels.Entity;
using CncModels.Constants;
using CncRepository.Interface;

namespace CncService.Impl
{
    /// <summary>
    /// 产量管理实现
    /// </summary>
    public class ProductionService : IProductionService
    {
        private readonly IDailyProductionRepository _dailyProductionRepository;
        private readonly IProductionSegmentRepository _productionSegmentRepository;
        private readonly IProductionAdjustmentRepository _productionAdjustmentRepository;

        public ProductionService(
            IDailyProductionRepository dailyProductionRepository,
            IProductionSegmentRepository productionSegmentRepository,
            IProductionAdjustmentRepository productionAdjustmentRepository)
        {
            _dailyProductionRepository = dailyProductionRepository ?? throw new ArgumentNullException(nameof(dailyProductionRepository));
            _productionSegmentRepository = productionSegmentRepository ?? throw new ArgumentNullException(nameof(productionSegmentRepository));
            _productionAdjustmentRepository = productionAdjustmentRepository ?? throw new ArgumentNullException(nameof(productionAdjustmentRepository));
        }

        /// <inheritdoc/>
        public PagedResult<DailyProductionListItem> GetList(ProductionQuery query)
        {
            if (query == null) throw new BusinessException(ErrorCode.BadRequest, "查询参数不能为空");
            return _dailyProductionRepository.GetList(query);
        }

        /// <inheritdoc/>
        public DailySummaryResponse GetSummary(DateTime? startDate, DateTime? endDate, int? workshopId, int? machineId, int? workerId)
        {
            var s = startDate ?? DateTime.Today;
            var e = endDate ?? DateTime.Today;
            var total = _dailyProductionRepository.GetTotalByDateRange(s, e, workshopId);
            // 如果汇总表无数据，从产量分段实时计算
            if (total == 0)
            {
                total = _productionSegmentRepository.GetTotalByDateRange(s, e, workshopId);
            }
            int machineCount = _productionSegmentRepository.GetActiveMachineCount(s, workshopId);
            decimal cuttingTime = _productionSegmentRepository.GetTotalCuttingTimeByDate(s);
            return new DailySummaryResponse
            {
                TotalQuantity = (int)total,
                MachineCount = machineCount,
                NormalCount = 0,
                OfflineCount = 0,
                totalCuttingTime = cuttingTime
            };
        }

        /// <inheritdoc/>
        public decimal GetTotalByDateRange(DateTime startDate, DateTime endDate, int? workshopId)
        {
            return _dailyProductionRepository.GetTotalByDateRange(startDate, endDate, workshopId);
        }

        /// <inheritdoc/>
        public bool Adjust(ProductionAdjustRequest request)
        {
            if (request == null) throw new BusinessException(ErrorCode.BadRequest, "请求参数不能为空");
            decimal newValue;
            decimal.TryParse(request.NewValue, out newValue);
            var entity = new ProductionAdjustment
            {
                TargetTable = request.TargetTable,
                TargetId = request.TargetId,
                FieldName = request.FieldName,
                OldValue = null,
                NewValue = newValue,
                Reason = request.Reason,
                OperatorIp = "",
                CreatedAt = DateTime.Now
            };
            _productionAdjustmentRepository.Create(entity);
            return true;
        }

        /// <inheritdoc/>
        public List<AdjustmentHistoryItem> GetAdjustmentHistory(int recordId)
        {
            var records = _productionAdjustmentRepository.GetByTargetId(recordId);
            var result = new List<AdjustmentHistoryItem>();
            foreach (var r in records)
            {
                result.Add(new AdjustmentHistoryItem
                {
                    Id = (int)r.Id,
                    OldValue = r.OldValue?.ToString() ?? "-",
                    NewValue = r.NewValue.ToString(),
                    Reason = r.Reason ?? "",
                    OperatorIp = r.OperatorIp ?? "",
                    CreatedAt = r.CreatedAt.ToString("yyyy-MM-dd HH:mm:ss")
                });
            }
            return result;
        }
    }
}
