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, sort_order as SortOrder, is_enabled as IsEnabled, created_at as CreatedAt, updated_at 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, sort_order as SortOrder, is_enabled as IsEnabled, created_at as CreatedAt, updated_at as UpdatedAt FROM cnc_workshop ORDER BY sort_order 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, sort_order as SortOrder, is_enabled as IsEnabled, created_at as CreatedAt, updated_at as UpdatedAt 
                              FROM cnc_workshop {where} ORDER BY sort_order 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, sort_order, is_enabled, created_at, updated_at) 
                            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, sort_order = @SortOrder, is_enabled = @IsEnabled, updated_at = @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 is_enabled = CASE WHEN is_enabled = 1 THEN 0 ELSE 1 END, updated_at = 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 workshop_id = @WorkshopId";
                return conn.ExecuteScalar<int>(sql, new { WorkshopId = workshopId });
            }
        }
    }
}
