using System;
using System.Collections.Generic;
using System.Linq;
using Dapper;
using CncModels.Entity;
using CncModels.Dto.Production;
using CncModels.Dto;
using CncRepository.Base;
using CncRepository.Interface;

namespace CncRepository.Impl
{
    public class DailyProductionRepository : BusinessRepository, IDailyProductionRepository
    {
        public DailyProductionRepository(string connectionString) : base(connectionString) { }

        public DailyProduction GetById(int id)
        {
            using (var conn = CreateConnection())
            {
                string sql = "SELECT * FROM cnc_daily_production WHERE id = @Id";
                return conn.QuerySingleOrDefault<DailyProduction>(sql, new { Id = id });
            }
        }

        public PagedResult<DailyProductionListItem> GetList(ProductionQuery query)
        {
            using (var conn = CreateConnection())
            {
                var parameters = new DynamicParameters();
                string baseSql = @"SELECT dp.machine_id AS MachineId, m.name AS MachineName, 
                                   dp.program_name AS ProgramName, dp.production_date AS ProductionDate,
                                   (dp.end_total_count - dp.base_total_count) AS Quantity
                                   FROM cnc_daily_production dp
                                   JOIN cnc_machine m ON dp.machine_id = m.id
                                   WHERE 1=1";
                if (query?.WorkshopId.HasValue == true)
                {
                    baseSql += " AND m.workshop_id = @WorkshopId";
                    parameters.Add("WorkshopId", query.WorkshopId);
                }
                if (query?.MachineId.HasValue == true)
                {
                    baseSql += " AND dp.machine_id = @MachineId";
                    parameters.Add("MachineId", query.MachineId);
                }
                if (query?.WorkerId.HasValue == true)
                {
                    baseSql += " AND EXISTS (SELECT 1 FROM cnc_worker_machine wm WHERE wm.machine_id = dp.machine_id AND wm.worker_id = @WorkerId)";
                    parameters.Add("WorkerId", query.WorkerId);
                }
                string countSql = $"SELECT COUNT(*) FROM ({baseSql}) AS t";
                int offset = (query.Page - 1) * query.PageSize;
                string paging = " ORDER BY ProductionDate DESC, MachineName LIMIT @Limit OFFSET @Offset";
                parameters.Add("Limit", query.PageSize);
                parameters.Add("Offset", offset);
                var items = conn.Query<DailyProductionListItem>(baseSql + paging, parameters).ToList();
                int total = conn.ExecuteScalar<int>(countSql, parameters);
                return new PagedResult<DailyProductionListItem> { Items = items, Total = total, Page = query.Page, PageSize = query.PageSize };
            }
        }

        public List<DailyProduction> GetByMachineAndDate(int machineId, DateTime date)
        {
            using (var conn = CreateConnection())
            {
                string sql = "SELECT * FROM cnc_daily_production WHERE machine_id = @MachineId AND production_date = @Date";
                return conn.Query<DailyProduction>(sql, new { MachineId = machineId, Date = date }).ToList();
            }
        }

        public List<DailyProduction> GetByDateRange(DateTime startDate, DateTime endDate)
        {
            using (var conn = CreateConnection())
            {
                string sql = @"SELECT dp.* FROM cnc_daily_production dp LEFT JOIN cnc_machine m ON dp.machine_id = m.id WHERE dp.production_date BETWEEN @Start AND @End ORDER BY dp.production_date DESC";
                return conn.Query<DailyProduction>(sql, new { Start = startDate, End = endDate }).ToList();
            }
        }

        public decimal GetTotalByDateRange(DateTime startDate, DateTime endDate, int? workshopId)
        {
            using (var conn = CreateConnection())
            {
                string sql = @"SELECT SUM(dp.end_total_count - dp.base_total_count) FROM cnc_daily_production dp LEFT JOIN cnc_machine m ON dp.machine_id = m.id WHERE dp.production_date BETWEEN @Start AND @End";
                if (workshopId.HasValue) { sql += " AND m.workshop_id = @WorkshopId"; return conn.ExecuteScalar<decimal>(sql, new { Start = startDate, End = endDate, WorkshopId = workshopId.Value }); }
                return conn.ExecuteScalar<decimal>(sql, new { Start = startDate, End = endDate });
            }
        }

        public decimal GetTotalByWorkerAndDateRange(int workerId, DateTime startDate, DateTime endDate)
        {
            using (var conn = CreateConnection())
            {
                string sql = @"SELECT SUM(end_total_count - base_total_count) FROM cnc_daily_production WHERE production_date BETWEEN @Start AND @End";
                var res = conn.ExecuteScalar<decimal?>(sql, new { Start = startDate, End = endDate });
                return res ?? 0m;
            }
        }

        public List<DailyProduction> GetMachineRankByDateRange(DateTime startDate, DateTime endDate, int top)
        {
            using (var conn = CreateConnection())
            {
                string sql = @"SELECT m.id AS Id, m.id AS MachineId, m.name AS MachineName, SUM(dp.end_total_count - dp.base_total_count) AS TotalQuantity, NULL AS ProgramName, NULL AS ProductionDate FROM cnc_daily_production dp JOIN cnc_machine m ON dp.machine_id = m.id WHERE dp.production_date BETWEEN @Start AND @End GROUP BY m.id, m.name ORDER BY SUM(dp.end_total_count - dp.base_total_count) DESC LIMIT @Top";
                return conn.Query<DailyProduction>(sql, new { Start = startDate, End = endDate, Top = top }).ToList();
            }
        }

        public List<DailyProduction> GetWorkerRankByDateRange(DateTime startDate, DateTime endDate, int top)
        {
            using (var conn = CreateConnection())
            {
                string sql = @"SELECT 0 AS Id, NULL AS MachineId, NULL AS MachineName, SUM(end_total_count - base_total_count) AS TotalQuantity, NULL AS ProductionDate, NULL AS ProgramName FROM cnc_daily_production WHERE production_date BETWEEN @Start AND @End GROUP BY machine_id ORDER BY SUM(end_total_count - base_total_count) DESC LIMIT @Top";
                return conn.Query<DailyProduction>(sql, new { Start = startDate, End = endDate, Top = top }).ToList();
            }
        }

        public MachineProductionSummaryResponse GetMachineSummary(DateTime startDate, DateTime endDate, int? workshopId)
        {
            using (var conn = CreateConnection())
            {
                string sql = @"SELECT COALESCE(SUM(dp.end_total_count - dp.base_total_count), 0) AS TotalQuantity, COUNT(DISTINCT dp.machine_id) AS RunningMachineCount FROM cnc_daily_production dp LEFT JOIN cnc_machine m ON dp.machine_id = m.id WHERE dp.production_date BETWEEN @Start AND @End";
                var parameters = new DynamicParameters();
                parameters.Add("Start", startDate); parameters.Add("End", endDate);
                if (workshopId.HasValue) { sql += " AND m.workshop_id = @WorkshopId"; parameters.Add("WorkshopId", workshopId.Value); }
                var result = conn.QuerySingleOrDefault<MachineProductionSummaryResponse>(sql, parameters);
                if (result == null) return new MachineProductionSummaryResponse();
                if (result.RunningMachineCount > 0) result.AvgPerMachine = Math.Round((decimal)result.TotalQuantity / result.RunningMachineCount, 1);
                string topSql = @"SELECT m.name FROM cnc_daily_production dp LEFT JOIN cnc_machine m ON dp.machine_id = m.id WHERE dp.production_date BETWEEN @Start AND @End";
                if (workshopId.HasValue) topSql += " AND m.workshop_id = @WorkshopId";
                topSql += " GROUP BY dp.machine_id ORDER BY SUM(dp.end_total_count - dp.base_total_count) DESC LIMIT 1";
                result.TopMachineName = result.TotalQuantity > 0 ? (conn.ExecuteScalar<string>(topSql, parameters) ?? "-") : "-";
                return result;
            }
        }

        public List<MachineProductionListItem> GetMachineList(DateTime startDate, DateTime endDate, int? workshopId, int? machineId)
        {
            using (var conn = CreateConnection())
            {
                string sql = @"SELECT m.name AS MachineName, dp.program_name AS ProgramName, SUM(dp.end_total_count - dp.base_total_count) AS TotalQuantity FROM cnc_daily_production dp LEFT JOIN cnc_machine m ON dp.machine_id = m.id WHERE dp.production_date BETWEEN @Start AND @End";
                var parameters = new DynamicParameters();
                parameters.Add("Start", startDate); parameters.Add("End", endDate);
                if (workshopId.HasValue) { sql += " AND m.workshop_id = @WorkshopId"; parameters.Add("WorkshopId", workshopId.Value); }
                if (machineId.HasValue) { sql += " AND dp.machine_id = @MachineId"; parameters.Add("MachineId", machineId.Value); }
                sql += " GROUP BY dp.machine_id, dp.program_name, m.name ORDER BY TotalQuantity DESC";
                var items = conn.Query<MachineProductionListItem>(sql, parameters).ToList();
                for (int i = 0; i < items.Count; i++) { items[i].Rank = i + 1; items[i].DayStatus = items[i].DayStatus ?? ""; }
                return items;
            }
        }

        public WorkerProductionSummaryResponse GetWorkerSummary(DateTime startDate, DateTime endDate)
        {
            using (var conn = CreateConnection())
            {
                string sql = @"SELECT COALESCE(SUM(dp.end_total_count - dp.base_total_count), 0) AS TotalQuantity, COUNT(DISTINCT w.id) AS ActiveWorkerCount FROM cnc_daily_production dp JOIN cnc_worker_machine wm ON dp.machine_id = wm.machine_id JOIN cnc_worker w ON wm.worker_id = w.id WHERE dp.production_date BETWEEN @Start AND @End";
                var result = conn.QuerySingleOrDefault<WorkerProductionSummaryResponse>(sql, new { Start = startDate, End = endDate });
                if (result == null) return new WorkerProductionSummaryResponse();
                if (result.ActiveWorkerCount > 0) result.AvgPerWorker = Math.Round((decimal)result.TotalQuantity / result.ActiveWorkerCount, 1);
                string topSql = @"SELECT w.name FROM cnc_daily_production dp JOIN cnc_worker_machine wm ON dp.machine_id = wm.machine_id JOIN cnc_worker w ON wm.worker_id = w.id WHERE dp.production_date BETWEEN @Start AND @End GROUP BY w.id, w.name ORDER BY SUM(dp.end_total_count - dp.base_total_count) DESC LIMIT 1";
                result.TopWorkerName = result.TotalQuantity > 0 ? (conn.ExecuteScalar<string>(topSql, new { Start = startDate, End = endDate }) ?? "-") : "-";
                return result;
            }
        }

        public List<WorkerProductionListItem> GetWorkerList(DateTime startDate, DateTime endDate, int? workerId)
        {
            using (var conn = CreateConnection())
            {
                string sql = @"SELECT w.name AS WorkerName, COUNT(DISTINCT wm.machine_id) AS MachineCount, COUNT(DISTINCT dp.program_name) AS ProgramCount, COALESCE(SUM(dp.end_total_count - dp.base_total_count), 0) AS TotalQuantity FROM cnc_worker w JOIN cnc_worker_machine wm ON wm.worker_id = w.id LEFT JOIN cnc_daily_production dp ON dp.machine_id = wm.machine_id AND dp.production_date BETWEEN @Start AND @End";
                var parameters = new DynamicParameters();
                parameters.Add("Start", startDate); parameters.Add("End", endDate);
                if (workerId.HasValue) { sql += " AND w.id = @WorkerId"; parameters.Add("WorkerId", workerId.Value); }
                sql += " GROUP BY w.id, w.name ORDER BY TotalQuantity DESC";
                var items = conn.Query<WorkerProductionListItem>(sql, parameters).ToList();
                if (items.Count > 0) { int grandTotal = items.Sum(x => x.TotalQuantity); for (int i = 0; i < items.Count; i++) { items[i].Rank = i + 1; if (grandTotal > 0) items[i].Percentage = Math.Round((decimal)items[i].TotalQuantity / grandTotal * 100, 1); } }
                return items;
            }
        }

        public ProgramProductionSummaryResponse GetProgramSummary(DateTime startDate, DateTime endDate, int? workshopId)
        {
            using (var conn = CreateConnection())
            {
                string sql = @"SELECT COALESCE(SUM(dp.end_total_count - dp.base_total_count), 0) AS TotalQuantity, COUNT(DISTINCT dp.program_name) AS RunningProgramCount FROM cnc_daily_production dp LEFT JOIN cnc_machine m ON dp.machine_id = m.id WHERE dp.production_date BETWEEN @Start AND @End";
                var parameters = new DynamicParameters();
                parameters.Add("Start", startDate); parameters.Add("End", endDate);
                if (workshopId.HasValue) { sql += " AND m.workshop_id = @WorkshopId"; parameters.Add("WorkshopId", workshopId.Value); }
                var result = conn.QuerySingleOrDefault<ProgramProductionSummaryResponse>(sql, parameters);
                if (result == null) return new ProgramProductionSummaryResponse();
                if (result.RunningProgramCount > 0) result.AvgPerProgram = Math.Round((decimal)result.TotalQuantity / result.RunningProgramCount, 1);
                string topSql = @"SELECT dp.program_name FROM cnc_daily_production dp LEFT JOIN cnc_machine m ON dp.machine_id = m.id WHERE dp.production_date BETWEEN @Start AND @End";
                if (workshopId.HasValue) topSql += " AND m.workshop_id = @WorkshopId";
                topSql += " GROUP BY dp.program_name ORDER BY SUM(dp.end_total_count - dp.base_total_count) DESC LIMIT 1";
                result.TopProgramName = result.TotalQuantity > 0 ? (conn.ExecuteScalar<string>(topSql, parameters) ?? "-") : "-";
                return result;
            }
        }

        public List<ProgramProductionListItem> GetProgramList(DateTime startDate, DateTime endDate, string programName)
        {
            using (var conn = CreateConnection())
            {
                string sql = @"SELECT dp.program_name AS ProgramName, COUNT(DISTINCT dp.machine_id) AS MachineCount, SUM(dp.end_total_count - dp.base_total_count) AS TotalQuantity FROM cnc_daily_production dp LEFT JOIN cnc_machine m ON dp.machine_id = m.id WHERE dp.production_date BETWEEN @Start AND @End";
                var parameters = new DynamicParameters();
                parameters.Add("Start", startDate); parameters.Add("End", endDate);
                if (!string.IsNullOrWhiteSpace(programName)) { sql += " AND dp.program_name = @ProgramName"; parameters.Add("ProgramName", programName); }
                sql += " GROUP BY dp.program_name ORDER BY TotalQuantity DESC";
                var items = conn.Query<ProgramProductionListItem>(sql, parameters).ToList();
                if (items.Count > 0) { int grandTotal = items.Sum(x => x.TotalQuantity); for (int i = 0; i < items.Count; i++) { items[i].Rank = i + 1; if (items[i].MachineCount > 0) items[i].AvgPerMachine = Math.Round((decimal)items[i].TotalQuantity / items[i].MachineCount, 1); if (grandTotal > 0) items[i].Percentage = Math.Round((decimal)items[i].TotalQuantity / grandTotal * 100, 1); } }
                return items;
            }
        }
    }
}
