using System;
using System.Collections.Generic;
using System.Linq;
using CncModels.Dto.Brand;
using CncModels.Entity;
using CncRepository.Interface;
using CncService.Interface;
using CncService;
using CncModels.Constants;

namespace CncService.Impl
{
    /// <summary>
    /// 品牌模板实现
    /// </summary>
    public class BrandService : IBrandService
    {
        private readonly IBrandRepository _brandRepository;
        private readonly IBrandFieldMappingRepository _mappingRepository;
        private readonly ICollectAddressRepository _collectAddressRepository;

        public BrandService(IBrandRepository brandRepository,
            IBrandFieldMappingRepository mappingRepository,
            ICollectAddressRepository collectAddressRepository)
        {
            _brandRepository = brandRepository;
            _mappingRepository = mappingRepository;
            _collectAddressRepository = collectAddressRepository;
        }

        public List<BrandListItem> GetList()
        {
            var brands = _brandRepository.GetAll();
            return brands.Select(b => new BrandListItem
            {
                Id = b.Id,
                BrandName = b.BrandName,
                DeviceField = b.DeviceField,
                TagsPath = b.TagsPath,
                IsEnabled = b.IsEnabled == 1,
                FieldCount = _brandRepository.GetFieldMappingCount(b.Id)
            }).ToList();
        }

        public BrandDetailResponse GetById(int id)
        {
            var brand = _brandRepository.GetById(id);
            if (brand == null) throw new BusinessException(ErrorCode.NotFound, "品牌不存在");

            var mappings = _mappingRepository.GetByBrandId(id);
            var detail = new BrandDetailResponse
            {
                Id = brand.Id,
                BrandName = brand.BrandName,
                DeviceField = brand.DeviceField,
                TagsPath = brand.TagsPath,
                IsEnabled = brand.IsEnabled == 1,
                FieldCount = mappings?.Count ?? 0,
                    Mappings = mappings?.Select(m => new BrandFieldMappingDto
                    {
                        StandardField = m.StandardField,
                        FieldName = m.FieldName,
                        MatchBy = m.MatchBy,
                        DataType = m.DataType,
                    	IsRequired = m.IsRequired,
                        IsEnabled = m.IsEnabled
                    }).ToList() ?? new List<BrandFieldMappingDto>()
                };
            return detail;
        }

        public int Create(CreateBrandRequest request)
        {
            if (request == null) throw new BusinessException(ErrorCode.BadRequest, "请求参数错误");
            // 验证唯一性
            if (_brandRepository.GetAll().Any(b => string.Equals(b.BrandName, request.BrandName, StringComparison.OrdinalIgnoreCase)))
            {
                throw new BusinessException(ErrorCode.Conflict, "品牌名称已存在");
            }

            var entity = new Brand
            {
                BrandName = request.BrandName,
                DeviceField = request.DeviceField,
                TagsPath = request.TagsPath,
                IsEnabled = 1,
                CreatedAt = DateTime.Now,
                UpdatedAt = DateTime.Now
            };
            return _brandRepository.Create(entity);
        }

        public bool Update(int id, UpdateBrandRequest request)
        {
            var brand = _brandRepository.GetById(id);
            if (brand == null) throw new BusinessException(ErrorCode.NotFound, "品牌不存在");
            if (request == null) throw new BusinessException(ErrorCode.BadRequest, "请求参数错误");

            brand.BrandName = request.BrandName ?? brand.BrandName;
            brand.DeviceField = request.DeviceField ?? brand.DeviceField;
            brand.TagsPath = request.TagsPath ?? brand.TagsPath;
            brand.UpdatedAt = DateTime.Now;

            return _brandRepository.Update(brand);
        }

        public bool Delete(int id)
        {
            var brand = _brandRepository.GetById(id);
            if (brand == null) throw new BusinessException(ErrorCode.NotFound, "品牌不存在");

            // 删除前检查是否有关联的采集地址
            var countCollectAddress = _collectAddressRepository.GetList(new CncModels.Dto.CollectAddress.CollectAddressQuery { BrandId = id }).Total;
            if (countCollectAddress > 0) return false;

            return _brandRepository.Delete(id);
        }

        public bool ToggleEnabled(int id)
        {
            return _brandRepository.ToggleEnabled(id);
        }

        public int Copy(int id)
        {
            var brand = _brandRepository.GetById(id);
            if (brand == null) throw new BusinessException(ErrorCode.NotFound, "品牌不存在");

            var newBrand = new Brand
            {
                BrandName = brand.BrandName + "_Copy",
                DeviceField = brand.DeviceField,
                TagsPath = brand.TagsPath,
                IsEnabled = brand.IsEnabled,
                CreatedAt = DateTime.Now,
            };
            int newBrandId = _brandRepository.Create(newBrand);

            // 复制字段映射
            var mappings = _mappingRepository.GetByBrandId(id);
            if (mappings != null && mappings.Count > 0)
            {
                    var newMappings = mappings.Select(m => new BrandFieldMapping
                    {
                        BrandId = newBrandId,
                        StandardField = m.StandardField,
                        FieldName = m.FieldName,
                        MatchBy = m.MatchBy,
                        DataType = m.DataType,
                        IsRequired = m.IsRequired,
                        IsEnabled = m.IsEnabled,
                        CreatedAt = DateTime.Now
                    }).ToList();
                _mappingRepository.BatchCreate(newBrandId, newMappings);
            }
            return newBrandId;
        }

        public List<StandardFieldResponse> GetStandardFields()
        {
            // 硬编码的16个标准字段示例
            var list = new List<StandardFieldResponse>();
            for (int i = 1; i <= 16; i++)
            {
                list.Add(new StandardFieldResponse
                {
                    StandardField = $"Field{i}",
                    Description = $"标准字段描述{i}"
                });
            }
            return list;
        }
    }
}
