using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
using CNCSystem.Models.User;
using CNCSystem.Data.Repositories;

namespace CNCSystem.Api.Controllers
{
    [RoutePrefix("api/v1/auth")]
    public class AuthController : ApiController
    {
        private readonly UserService _userService;

        public AuthController()
        {
            var context = new CNCBusinessDbContext();
            var userRepo = new UserRepository(context);
            var roleRepo = new RoleRepository(context);
            var employeeRepo = new EmployeeRepository(context);
            var assignmentRepo = new DeviceAssignmentRepository(context);
            
            _userService = new UserService(userRepo, roleRepo, employeeRepo, assignmentRepo);
        }

        [HttpPost]
        [Route("login")]
        public IHttpActionResult Login(LoginRequest request)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(request.Username) || string.IsNullOrWhiteSpace(request.Password))
                {
                    return BadRequest(new
                    {
                        success = false,
                        message = "用户名和密码不能为空",
                        timestamp = DateTime.Now
                    });
                }

                var response = _userService.Login(request);
                return Ok(response);
            }
            catch (Exception ex)
            {
                return InternalServerError(ex);
            }
        }

        [HttpPost]
        [Route("logout")]
        public IHttpActionResult Logout()
        {
            // 在实际应用中，这里应该处理token失效逻辑
            return Ok(new
            {
                success = true,
                message = "退出成功",
                timestamp = DateTime.Now
            });
        }

        [HttpGet]
        [Route("me")]
        [Authorize]
        public IHttpActionResult GetCurrentUser()
        {
            try
            {
                // 这里应该从当前用户上下文中获取用户信息
                // 简化实现，返回示例数据
                var user = new UserViewModel
                {
                    Id = 1,
                    Username = "admin",
                    RealName = "系统管理员",
                    Email = "admin@example.com",
                    Phone = "13800138000",
                    RoleName = "管理员",
                    IsActive = true,
                    LastLoginTime = DateTime.Now,
                    CreatedAt = DateTime.Now
                };

                return Ok(new
                {
                    success = true,
                    data = user,
                    message = "获取成功",
                    timestamp = DateTime.Now
                });
            }
            catch (Exception ex)
            {
                return InternalServerError(ex);
            }
        }
    }

    [RoutePrefix("api/v1/users")]
    public class UserController : ApiController
    {
        private readonly UserService _userService;

        public UserController()
        {
            var context = new CNCBusinessDbContext();
            var userRepo = new UserRepository(context);
            var roleRepo = new RoleRepository(context);
            var employeeRepo = new EmployeeRepository(context);
            var assignmentRepo = new DeviceAssignmentRepository(context);
            
            _userService = new UserService(userRepo, roleRepo, employeeRepo, assignmentRepo);
        }

        [HttpGet]
        [Route("")]
        public IHttpActionResult GetAllUsers()
        {
            try
            {
                var users = _userService.GetAllUserViewModels();
                return Ok(new
                {
                    success = true,
                    data = users,
                    message = "获取成功",
                    timestamp = DateTime.Now
                });
            }
            catch (Exception ex)
            {
                return InternalServerError(ex);
            }
        }

        [HttpGet]
        [Route("{id}")]
        public IHttpActionResult GetUser(int id)
        {
            try
            {
                var user = _userService.GetAllUserViewModels()
                    .FirstOrDefault(u => u.Id == id);
                
                if (user == null)
                {
                    return NotFound();
                }

                return Ok(new
                {
                    success = true,
                    data = user,
                    message = "获取成功",
                    timestamp = DateTime.Now
                });
            }
            catch (Exception ex)
            {
                return InternalServerError(ex);
            }
        }

        [HttpPost]
        [Route("")]
        public IHttpActionResult CreateUser(User user)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(user.Username) || 
                    string.IsNullOrWhiteSpace(user.PasswordHash) ||
                    string.IsNullOrWhiteSpace(user.RealName))
                {
                    return BadRequest(new
                    {
                        success = false,
                        message = "用户名、密码和真实姓名不能为空",
                        timestamp = DateTime.Now
                    });
                }

                var createdUser = _userService.CreateUser(user);
                return Ok(new
                {
                    success = true,
                    data = createdUser,
                    message = "创建成功",
                    timestamp = DateTime.Now
                });
            }
            catch (Exception ex)
            {
                return InternalServerError(ex);
            }
        }

        [HttpPut]
        [Route("{id}")]
        public IHttpActionResult UpdateUser(int id, User user)
        {
            try
            {
                user.Id = id;
                var updatedUser = _userService.UpdateUser(user);
                return Ok(new
                {
                    success = true,
                    data = updatedUser,
                    message = "更新成功",
                    timestamp = DateTime.Now
                });
            }
            catch (Exception ex)
            {
                return InternalServerError(ex);
            }
        }

        [HttpDelete]
        [Route("{id}")]
        public IHttpActionResult DeleteUser(int id)
        {
            try
            {
                var user = _userService.GetAllUserViewModels()
                    .FirstOrDefault(u => u.Id == id);
                
                if (user == null)
                {
                    return NotFound();
                }

                // 这里应该调用删除用户的逻辑
                // 简化实现
                return Ok(new
                {
                    success = true,
                    message = "删除成功",
                    timestamp = DateTime.Now
                });
            }
            catch (Exception ex)
            {
                return InternalServerError(ex);
            }
        }

        [HttpPost]
        [Route("{id}/toggle-active")]
        public IHttpActionResult ToggleUserActive(int id, [FromBody] bool isActive)
        {
            try
            {
                var user = _userService.GetAllUserViewModels()
                    .FirstOrDefault(u => u.Id == id);
                
                if (user == null)
                {
                    return NotFound();
                }

                // 这里应该更新用户激活状态
                // 简化实现
                return Ok(new
                {
                    success = true,
                    message = $"用户状态已更新为{(isActive ? "激活" : "禁用")}",
                    timestamp = DateTime.Now
                });
            }
            catch (Exception ex)
            {
                return InternalServerError(ex);
            }
        }
    }

    [RoutePrefix("api/v1/roles")]
    public class RoleController : ApiController
    {
        private readonly RoleRepository _roleRepository;

        public RoleController()
        {
            var context = new CNCBusinessDbContext();
            _roleRepository = new RoleRepository(context);
        }

        [HttpGet]
        [Route("")]
        public IHttpActionResult GetAllRoles()
        {
            try
            {
                var roles = _roleRepository.GetAllRoles();
                return Ok(new
                {
                    success = true,
                    data = roles.Select(r => new
                    {
                        r.Id,
                        r.RoleName,
                        r.Description,
                        r.Permissions,
                        r.CreatedAt,
                        r.UpdatedAt
                    }),
                    message = "获取成功",
                    timestamp = DateTime.Now
                });
            }
            catch (Exception ex)
            {
                return InternalServerError(ex);
            }
        }

        [HttpGet]
        [Route("{id}")]
        public IHttpActionResult GetRole(int id)
        {
            try
            {
                var role = _roleRepository.GetRoleById(id);
                if (role == null)
                {
                    return NotFound();
                }

                return Ok(new
                {
                    success = true,
                    data = role,
                    message = "获取成功",
                    timestamp = DateTime.Now
                });
            }
            catch (Exception ex)
            {
                return InternalServerError(ex);
            }
        }

        [HttpPost]
        [Route("")]
        public IHttpActionResult CreateRole(Role role)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(role.RoleName))
                {
                    return BadRequest(new
                    {
                        success = false,
                        message = "角色名称不能为空",
                        timestamp = DateTime.Now
                    });
                }

                var createdRole = _roleRepository.CreateRole(role);
                return Ok(new
                {
                    success = true,
                    data = createdRole,
                    message = "创建成功",
                    timestamp = DateTime.Now
                });
            }
            catch (Exception ex)
            {
                return InternalServerError(ex);
            }
        }

        [HttpPut]
        [Route("{id}")]
        public IHttpActionResult UpdateRole(int id, Role role)
        {
            try
            {
                role.Id = id;
                var updatedRole = _roleRepository.UpdateRole(role);
                return Ok(new
                {
                    success = true,
                    data = updatedRole,
                    message = "更新成功",
                    timestamp = DateTime.Now
                });
            }
            catch (Exception ex)
            {
                return InternalServerError(ex);
            }
        }

        [HttpDelete]
        [Route("{id}")]
        public IHttpActionResult DeleteRole(int id)
        {
            try
            {
                _roleRepository.DeleteRole(id);
                return Ok(new
                {
                    success = true,
                    message = "删除成功",
                    timestamp = DateTime.Now
                });
            }
            catch (Exception ex)
            {
                return InternalServerError(ex);
            }
        }
    }

    [RoutePrefix("api/v1/employees")]
    public class EmployeeController : ApiController
    {
        private readonly EmployeeRepository _employeeRepository;

        public EmployeeController()
        {
            var context = new CNCBusinessDbContext();
            _employeeRepository = new EmployeeRepository(context);
        }

        [HttpGet]
        [Route("")]
        public IHttpActionResult GetAllEmployees()
        {
            try
            {
                var employees = _employeeRepository.GetAllEmployees();
                return Ok(new
                {
                    success = true,
                    data = employees.Select(e => new
                    {
                        e.Id,
                        e.EmployeeCode,
                        e.Name,
                        e.Department,
                        e.Position,
                        e.AssignedDevices,
                        e.CreatedAt,
                        e.UpdatedAt
                    }),
                    message = "获取成功",
                    timestamp = DateTime.Now
                });
            }
            catch (Exception ex)
            {
                return InternalServerError(ex);
            }
        }

        [HttpGet]
        [Route("{id}")]
        public IHttpActionResult GetEmployee(int id)
        {
            try
            {
                var employee = _employeeRepository.GetEmployeeById(id);
                if (employee == null)
                {
                    return NotFound();
                }

                return Ok(new
                {
                    success = true,
                    data = employee,
                    message = "获取成功",
                    timestamp = DateTime.Now
                });
            }
            catch (Exception ex)
            {
                return InternalServerError(ex);
            }
        }

        [HttpPost]
        [Route("")]
        public IHttpActionResult CreateEmployee(Employee employee)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(employee.EmployeeCode) || 
                    string.IsNullOrWhiteSpace(employee.Name))
                {
                    return BadRequest(new
                    {
                        success = false,
                        message = "员工编号和姓名不能为空",
                        timestamp = DateTime.Now
                    });
                }

                var createdEmployee = _employeeRepository.CreateEmployee(employee);
                return Ok(new
                {
                    success = true,
                    data = createdEmployee,
                    message = "创建成功",
                    timestamp = DateTime.Now
                });
            }
            catch (Exception ex)
            {
                return InternalServerError(ex);
            }
        }

        [HttpPut]
        [Route("{id}")]
        public IHttpActionResult UpdateEmployee(int id, Employee employee)
        {
            try
            {
                employee.Id = id;
                var updatedEmployee = _employeeRepository.UpdateEmployee(employee);
                return Ok(new
                {
                    success = true,
                    data = updatedEmployee,
                    message = "更新成功",
                    timestamp = DateTime.Now
                });
            }
            catch (Exception ex)
            {
                return InternalServerError(ex);
            }
        }

        [HttpDelete]
        [Route("{id}")]
        public IHttpActionResult DeleteEmployee(int id)
        {
            try
            {
                _employeeRepository.DeleteEmployee(id);
                return Ok(new
                {
                    success = true,
                    message = "删除成功",
                    timestamp = DateTime.Now
                });
            }
            catch (Exception ex)
            {
                return InternalServerError(ex);
            }
        }
    }
}