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

namespace CNCSystem.Api.Controllers
{
    [RoutePrefix("api/v1/templates")]
    public class TemplateController : ApiController
    {
        private readonly TemplateRepository _templateRepository;
        private readonly TemplateMappingService _templateMappingService;

        public TemplateController()
        {
            var context = new CNCBusinessDbContext();
            _templateRepository = new TemplateRepository(context);
            _templateMappingService = new TemplateMappingService(_templateRepository, null);
        }

        [HttpGet]
        [Route("")]
        public IHttpActionResult GetAllTemplates()
        {
            try
            {
                var templates = _templateRepository.GetAllTemplates();
                return Ok(new
                {
                    success = true,
                    data = templates.Select(t => new
                    {
                        t.Id,
                        t.BrandName,
                        t.Description,
                        t.IsEnabled,
                        t.FieldMappings,
                        t.CreatedAt,
                        t.UpdatedAt
                    }),
                    message = "获取成功",
                    timestamp = DateTime.Now
                });
            }
            catch (Exception ex)
            {
                return InternalServerError(ex);
            }
        }

        [HttpGet]
        [Route("enabled")]
        public IHttpActionResult GetEnabledTemplates()
        {
            try
            {
                var templates = _templateRepository.GetEnabledTemplates();
                return Ok(new
                {
                    success = true,
                    data = templates.Select(t => new
                    {
                        t.Id,
                        t.BrandName,
                        t.Description,
                        t.IsEnabled,
                        t.FieldMappings,
                        t.CreatedAt,
                        t.UpdatedAt
                    }),
                    message = "获取成功",
                    timestamp = DateTime.Now
                });
            }
            catch (Exception ex)
            {
                return InternalServerError(ex);
            }
        }

        [HttpGet]
        [Route("{id}")]
        public IHttpActionResult GetTemplate(int id)
        {
            try
            {
                var template = _templateRepository.GetTemplateById(id);
                if (template == null)
                {
                    return NotFound();
                }

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

        [HttpGet]
        [Route("brand/{brandName}")]
        public IHttpActionResult GetTemplateByBrandName(string brandName)
        {
            try
            {
                var template = _templateRepository.GetTemplateByBrandName(brandName);
                if (template == null)
                {
                    return NotFound();
                }

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

        [HttpPost]
        [Route("")]
        public IHttpActionResult CreateTemplate(CNCBrandTemplate template)
        {
            try
            {
                // 验证模板
                _templateMappingService.ValidateTemplate(template);

                // 验证品牌名称唯一性
                var existingTemplate = _templateRepository.GetTemplateByBrandName(template.BrandName);
                if (existingTemplate != null)
                {
                    return BadRequest(new
                    {
                        success = false,
                        message = "品牌名称已存在",
                        timestamp = DateTime.Now
                    });
                }

                var createdTemplate = _templateRepository.CreateTemplate(template);
                return Ok(new
                {
                    success = true,
                    data = createdTemplate,
                    message = "创建成功",
                    timestamp = DateTime.Now
                });
            }
            catch (Exception ex)
            {
                return InternalServerError(ex);
            }
        }

        [HttpPut]
        [Route("{id}")]
        public IHttpActionResult UpdateTemplate(int id, CNCBrandTemplate template)
        {
            try
            {
                var existingTemplate = _templateRepository.GetTemplateById(id);
                if (existingTemplate == null)
                {
                    return NotFound();
                }

                // 验证模板
                _templateMappingService.ValidateTemplate(template);

                template.Id = id;
                var updatedTemplate = _templateRepository.UpdateTemplate(template);
                return Ok(new
                {
                    success = true,
                    data = updatedTemplate,
                    message = "更新成功",
                    timestamp = DateTime.Now
                });
            }
            catch (Exception ex)
            {
                return InternalServerError(ex);
            }
        }

        [HttpDelete]
        [Route("{id}")]
        public IHttpActionResult DeleteTemplate(int id)
        {
            try
            {
                var template = _templateRepository.GetTemplateById(id);
                if (template == null)
                {
                    return NotFound();
                }

                _templateRepository.DeleteTemplate(id);
                return Ok(new
                {
                    success = true,
                    message = "删除成功",
                    timestamp = DateTime.Now
                });
            }
            catch (Exception ex)
            {
                return InternalServerError(ex);
            }
        }

        [HttpPost]
        [Route("{id}/enable")]
        public IHttpActionResult EnableTemplate(int id)
        {
            try
            {
                _templateRepository.EnableTemplate(id);
                return Ok(new
                {
                    success = true,
                    message = "模板已启用",
                    timestamp = DateTime.Now
                });
            }
            catch (Exception ex)
            {
                return InternalServerError(ex);
            }
        }

        [HttpPost]
        [Route("{id}/disable")]
        public IHttpActionResult DisableTemplate(int id)
        {
            try
            {
                _templateRepository.DisableTemplate(id);
                return Ok(new
                {
                    success = true,
                    message = "模板已禁用",
                    timestamp = DateTime.Now
                });
            }
            catch (Exception ex)
            {
                return InternalServerError(ex);
            }
        }

        [HttpGet]
        [Route("{id}/field-mappings")]
        public IHttpActionResult GetFieldMappings(int id)
        {
            try
            {
                var mappings = _templateRepository.GetFieldMappingsByTemplateId(id);
                return Ok(new
                {
                    success = true,
                    data = mappings,
                    message = "获取成功",
                    timestamp = DateTime.Now
                });
            }
            catch (Exception ex)
            {
                return InternalServerError(ex);
            }
        }

        [HttpPost]
        [Route("{templateId}/field-mappings")]
        public IHttpActionResult CreateFieldMapping(int templateId, TemplateFieldMapping mapping)
        {
            try
            {
                mapping.TemplateId = templateId;
                var createdMapping = _templateRepository.CreateFieldMapping(mapping);
                return Ok(new
                {
                    success = true,
                    data = createdMapping,
                    message = "字段映射创建成功",
                    timestamp = DateTime.Now
                });
            }
            catch (Exception ex)
            {
                return InternalServerError(ex);
            }
        }

        [HttpPut]
        [Route("field-mappings/{id}")]
        public IHttpActionResult UpdateFieldMapping(int id, TemplateFieldMapping mapping)
        {
            try
            {
                mapping.Id = id;
                var updatedMapping = _templateRepository.UpdateFieldMapping(mapping);
                return Ok(new
                {
                    success = true,
                    data = updatedMapping,
                    message = "字段映射更新成功",
                    timestamp = DateTime.Now
                });
            }
            catch (Exception ex)
            {
                return InternalServerError(ex);
            }
        }

        [HttpDelete]
        [Route("field-mappings/{id}")]
        public IHttpActionResult DeleteFieldMapping(int id)
        {
            try
            {
                _templateRepository.DeleteFieldMapping(id);
                return Ok(new
                {
                    success = true,
                    message = "字段映射删除成功",
                    timestamp = DateTime.Now
                });
            }
            catch (Exception ex)
            {
                return InternalServerError(ex);
            }
        }

        [HttpPost]
        [Route("test-mapping")]
        public IHttpActionResult TestMapping([FromBody] TestMappingRequest request)
        {
            try
            {
                var result = _templateMappingService.MapRawDataToStandardFormat(
                    request.BrandName, request.RawData);

                return Ok(new
                {
                    success = true,
                    data = result,
                    message = "映射测试成功",
                    timestamp = DateTime.Now
                });
            }
            catch (Exception ex)
            {
                return InternalServerError(ex);
            }
        }

        public class TestMappingRequest
        {
            public string BrandName { get; set; }
            public Dictionary<string, object> RawData { get; set; }
        }
    }
}