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

namespace CncRepository.Impl
{
    /// <summary>
    /// 车间仓储实现
    /// </summary>
    public class WorkshopRepository : BusinessRepository, IWorkshopRepository
    {
        public WorkshopRepository(string connectionString) : base(connectionString) { }

        public Workshop GetById(int id)
        {
            using (var conn = CreateConnection())
            {
                var sql = @"SELECT Id as Id, Name as Name, SortOrder as SortOrder, IsEnabled as IsEnabled, CreatedAt as CreatedAt, UpdatedAt as UpdatedAt FROM cnc_workshop WHERE Id = @Id";
                return conn.QuerySingleOrDefault<Workshop>(sql, new { Id = id });
            }
        }

        public List<Workshop> GetAll()
        {
            using (var conn = CreateConnection())
            {
                var sql = @"SELECT Id as Id, Name as Name, SortOrder as SortOrder, IsEnabled as IsEnabled, CreatedAt as CreatedAt, UpdatedAt as UpdatedAt FROM cnc_workshop ORDER BY SortOrder ASC";
                return conn.Query<Workshop>(sql).ToList();
            }
        }

        public PagedResult<Workshop> GetList(string keyword)
        {
            using (var conn = CreateConnection())
            {
                var where = string.Empty;
                var param = new DynamicParameters();
                if (!string.IsNullOrWhiteSpace(keyword))
                {
                    where = " WHERE Name LIKE @Keyword";
                    param.Add("Keyword", $"%{keyword}%");
                }
                var limit = 20;
                var sql = $@"SELECT Id as Id, Name as Name, SortOrder as SortOrder, IsEnabled as IsEnabled, CreatedAt as CreatedAt, UpdatedAt as UpdatedAt 
                              FROM cnc_workshop {where} ORDER BY SortOrder ASC LIMIT {limit} OFFSET 0";
                var totalSql = $@"SELECT COUNT(*) FROM cnc_workshop {where}";
                var items = conn.Query<Workshop>(sql, param).ToList();
                var total = conn.ExecuteScalar<int>(totalSql, param);
                return new PagedResult<Workshop>
                {
                    Items = items,
                    Total = total,
                    Page = 1,
                    PageSize = limit
                };
            }
        }

        public int Create(Workshop entity)
        {
            using (var conn = CreateConnection())
            {
                var sql = @"INSERT INTO cnc_workshop (Name, SortOrder, IsEnabled, CreatedAt, UpdatedAt) 
                            VALUES (@Name, @SortOrder, @IsEnabled, @CreatedAt, @UpdatedAt); 
                          SELECT LAST_INSERT_ID();";
                return conn.QuerySingle<int>(sql, entity);
            }
        }

        public bool Update(Workshop entity)
        {
            using (var conn = CreateConnection())
            {
                var sql = @"UPDATE cnc_workshop SET Name = @Name, SortOrder = @SortOrder, IsEnabled = @IsEnabled, UpdatedAt = @UpdatedAt WHERE Id = @Id";
                return conn.Execute(sql, entity) > 0;
            }
        }

        public bool Delete(int id)
        {
            using (var conn = CreateConnection())
            {
                var sql = @"DELETE FROM cnc_workshop WHERE Id = @Id";
                return conn.Execute(sql, new { Id = id }) > 0;
            }
        }

        public bool ToggleEnabled(int id)
        {
            using (var conn = CreateConnection())
            {
                var sql = @"UPDATE cnc_workshop SET IsEnabled = CASE WHEN IsEnabled = 1 THEN 0 ELSE 1 END, UpdatedAt = NOW() WHERE Id = @Id";
                return conn.Execute(sql, new { Id = id }) > 0;
            }
        }

        public int GetMachineCount(int workshopId)
        {
            using (var conn = CreateConnection())
            {
                var sql = @"SELECT COUNT(*) FROM cnc_machine WHERE WorkshopId = @WorkshopId";
                return conn.ExecuteScalar<int>(sql, new { WorkshopId = workshopId });
            }
        }
    }
}
