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

namespace CncRepository.Impl
{
    /// <summary>
    /// 工人-机床绑定实现
    /// </summary>
    public class WorkerMachineRepository : BusinessRepository, IWorkerMachineRepository
    {
        public WorkerMachineRepository(string connectionString) : base(connectionString) { }

        private const string SelectColumns = @"id as Id, worker_id as WorkerId, machine_id as MachineId, created_at as CreatedAt";

        public WorkerMachine GetByMachineId(int machineId)
        {
            using (var conn = CreateConnection())
            {
                var sql = $"SELECT {SelectColumns} FROM cnc_worker_machine WHERE machine_id = @MachineId";
                return conn.QuerySingleOrDefault<WorkerMachine>(sql, new { MachineId = machineId });
            }
        }

        public List<WorkerMachine> GetByWorkerId(int workerId)
        {
            using (var conn = CreateConnection())
            {
                var sql = $"SELECT {SelectColumns} FROM cnc_worker_machine WHERE worker_id = @WorkerId";
                return conn.Query<WorkerMachine>(sql, new { WorkerId = workerId }).ToList();
            }
        }

        public int Create(int workerId, int machineId)
        {
            using (var conn = CreateConnection())
            {
                var sql = @"INSERT INTO cnc_worker_machine (worker_id, machine_id, created_at) VALUES (@WorkerId, @MachineId, NOW()); SELECT LAST_INSERT_ID();";
                return conn.QuerySingle<int>(sql, new { WorkerId = workerId, MachineId = machineId });
            }
        }

        public bool DeleteByMachineId(int machineId)
        {
            using (var conn = CreateConnection())
            {
                var sql = @"DELETE FROM cnc_worker_machine WHERE machine_id = @MachineId";
                return conn.Execute(sql, new { MachineId = machineId }) > 0;
            }
        }

        public bool DeleteByWorkerId(int workerId)
        {
            using (var conn = CreateConnection())
            {
                var sql = @"DELETE FROM cnc_worker_machine WHERE worker_id = @WorkerId";
                return conn.Execute(sql, new { WorkerId = workerId }) > 0;
            }
        }
    }
}
