using BLL.Interfaces;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using CONTROLLER.Extensions;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace CONTROLLER.Controllers
{
    /// <summary>
    /// 出货交接单与袋牌关联控制器
    /// </summary>
    [Route("api/shipping-handover/bag-tag")]
    [ApiController]
    public class ShippingHandoverFormBagTagController : ControllerBase
    {
        private readonly IShippingHandoverFormBagTagService _service;
        private readonly ILogger<ShippingHandoverFormBagTagController> _logger;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="service">关联服务</param>
        /// <param name="logger">日志记录器</param>
        public ShippingHandoverFormBagTagController(IShippingHandoverFormBagTagService service, ILogger<ShippingHandoverFormBagTagController> logger)
        {
            _service = service;
            _logger = logger;
        }

        /// <summary>
        /// 关联袋牌到出货交接单
        /// </summary>
        /// <param name="shippingHandoverFormId">出货交接单ID</param>
        /// <param name="bagTagIds">袋牌ID列表</param>
        /// <returns>操作结果</returns>
        [HttpPost("associate/{shippingHandoverFormId}")]
        public async Task<IActionResult> AssociateBagTags(int shippingHandoverFormId, [FromBody] List<int> bagTagIds)
        {
            try
            {
                var result = await _service.AssociateBagTagsAsync(shippingHandoverFormId, bagTagIds);
                return Ok(new
                {
                    code = 0,
                    message = "success",
                    data = result
                });
            }
            catch (Exception ex)
            {
                return Ok(new
                {
                    code = 9999,
                    message = ex.Message
                });
            }
        }

        /// <summary>
        /// 获取出货交接单关联的袋牌列表
        /// </summary>
        /// <param name="shippingHandoverFormId">出货交接单ID</param>
        /// <param name="callback">JSONP回调函数</param>
        /// <returns>袋牌列表</returns>
        [HttpGet("list/{shippingHandoverFormId}")]
        public async Task<IActionResult> GetAssociatedBagTags(int shippingHandoverFormId, [FromQuery] string callback = null)
        {
            try
            {
                var bagTags = await _service.GetAssociatedBagTagsAsync(shippingHandoverFormId);
                var result = new
                {
                    code = 0,
                    message = "success",
                    data = bagTags
                };

                // 处理 JSONP 请求
                if (!string.IsNullOrEmpty(callback))
                {
                    var jsonResult = System.Text.Json.JsonSerializer.Serialize(result);
                    var jsonpResult = $"{callback}({jsonResult})";
                    return Content(jsonpResult, "application/javascript");
                }

                return Ok(result);
            }
            catch (Exception ex)
            {
                var errorResult = new
                {
                    code = 9999,
                    message = ex.Message
                };

                // 处理 JSONP 错误
                if (!string.IsNullOrEmpty(callback))
                {
                    var jsonResult = System.Text.Json.JsonSerializer.Serialize(errorResult);
                    var jsonpResult = $"{callback}({jsonResult})";
                    return Content(jsonpResult, "application/javascript");
                }

                return Ok(errorResult);
            }
        }

        /// <summary>
        /// 从出货交接单中移除袋牌
        /// </summary>
        /// <param name="relationId">关联ID</param>
        /// <param name="callback">JSONP回调函数</param>
        /// <returns>操作结果</returns>
        [HttpGet("remove/{relationId}")]
        public async Task<IActionResult> RemoveBagTag(int relationId, [FromQuery] string callback = null)
        {
            try
            {
                var result = await _service.RemoveBagTagAsync(relationId);
                var response = new
                {
                    code = 0,
                    message = "success",
                    data = result
                };

                // 处理 JSONP 请求
                if (!string.IsNullOrEmpty(callback))
                {
                    var jsonResult = System.Text.Json.JsonSerializer.Serialize(response);
                    var jsonpResult = $"{callback}({jsonResult})";
                    return Content(jsonpResult, "application/javascript");
                }

                return Ok(response);
            }
            catch (Exception ex)
            {
                var errorResult = new
                {
                    code = 9999,
                    message = ex.Message
                };

                // 处理 JSONP 错误
                if (!string.IsNullOrEmpty(callback))
                {
                    var jsonResult = System.Text.Json.JsonSerializer.Serialize(errorResult);
                    var jsonpResult = $"{callback}({jsonResult})";
                    return Content(jsonpResult, "application/javascript");
                }

                return Ok(errorResult);
            }
        }

        /// <summary>
        /// 清空出货交接单的所有袋牌关联
        /// </summary>
        /// <param name="shippingHandoverFormId">出货交接单ID</param>
        /// <param name="callback">JSONP回调函数</param>
        /// <returns>操作结果</returns>
        [HttpGet("clear/{shippingHandoverFormId}")]
        public async Task<IActionResult> ClearBagTags(int shippingHandoverFormId, [FromQuery] string callback = null)
        {
            try
            {
                var result = await _service.ClearBagTagsAsync(shippingHandoverFormId);
                var response = new
                {
                    code = 0,
                    message = "success",
                    data = result
                };

                // 处理 JSONP 请求
                if (!string.IsNullOrEmpty(callback))
                {
                    var jsonResult = System.Text.Json.JsonSerializer.Serialize(response);
                    var jsonpResult = $"{callback}({jsonResult})";
                    return Content(jsonpResult, "application/javascript");
                }

                return Ok(response);
            }
            catch (Exception ex)
            {
                var errorResult = new
                {
                    code = 9999,
                    message = ex.Message
                };

                // 处理 JSONP 错误
                if (!string.IsNullOrEmpty(callback))
                {
                    var jsonResult = System.Text.Json.JsonSerializer.Serialize(errorResult);
                    var jsonpResult = $"{callback}({jsonResult})";
                    return Content(jsonpResult, "application/javascript");
                }

                return Ok(errorResult);
            }
        }

        /// <summary>
        /// 统计出货交接单的袋牌数量和包裹数量
        /// </summary>
        /// <param name="shippingHandoverFormId">出货交接单ID</param>
        /// <param name="callback">JSONP回调函数</param>
        /// <returns>统计结果</returns>
        [HttpGet("count/{shippingHandoverFormId}")]
        public async Task<IActionResult> CountBagTagsAndPackages(int shippingHandoverFormId, [FromQuery] string callback = null)
        {
            try
            {
                var (bagTagCount, packageCount) = await _service.CountBagTagsAndPackagesAsync(shippingHandoverFormId);
                var result = new
                {
                    code = 0,
                    message = "success",
                    data = new
                    {
                        bagTagCount,
                        packageCount
                    }
                };

                // 处理 JSONP 请求
                if (!string.IsNullOrEmpty(callback))
                {
                    var jsonResult = System.Text.Json.JsonSerializer.Serialize(result);
                    var jsonpResult = $"{callback}({jsonResult})";
                    return Content(jsonpResult, "application/javascript");
                }

                return Ok(result);
            }
            catch (Exception ex)
            {
                var errorResult = new
                {
                    code = 9999,
                    message = ex.Message
                };

                // 处理 JSONP 错误
                if (!string.IsNullOrEmpty(callback))
                {
                    var jsonResult = System.Text.Json.JsonSerializer.Serialize(errorResult);
                    var jsonpResult = $"{callback}({jsonResult})";
                    return Content(jsonpResult, "application/javascript");
                }

                return Ok(errorResult);
            }
        }

        /// <summary>
        /// 检查袋牌是否已关联到出货交接单
        /// </summary>
        /// <param name="bagTagId">袋牌ID</param>
        /// <param name="callback">JSONP回调函数</param>
        /// <returns>检查结果</returns>
        [HttpGet("check/{bagTagId}")]
        public async Task<IActionResult> CheckBagTagAssociation(int bagTagId, [FromQuery] string callback = null)
        {
            try
            {
                var isAssociated = await _service.IsBagTagAssociatedAsync(bagTagId);
                var result = new
                {
                    code = 0,
                    message = "success",
                    data = isAssociated
                };

                // 处理 JSONP 请求
                if (!string.IsNullOrEmpty(callback))
                {
                    var jsonResult = System.Text.Json.JsonSerializer.Serialize(result);
                    var jsonpResult = $"{callback}({jsonResult})";
                    return Content(jsonpResult, "application/javascript");
                }

                return Ok(result);
            }
            catch (Exception ex)
            {
                var errorResult = new
                {
                    code = 9999,
                    message = ex.Message
                };

                // 处理 JSONP 错误
                if (!string.IsNullOrEmpty(callback))
                {
                    var jsonResult = System.Text.Json.JsonSerializer.Serialize(errorResult);
                    var jsonpResult = $"{callback}({jsonResult})";
                    return Content(jsonpResult, "application/javascript");
                }

                return Ok(errorResult);
            }
        }

        /// <summary>
        /// 通过袋牌号关联袋牌到出货交接单
        /// </summary>
        /// <param name="shippingHandoverFormId">出货交接单ID</param>
        /// <param name="bagTagNumbers">袋牌号列表（逗号分隔）</param>
        /// <param name="callback">JSONP回调函数</param>
        /// <returns>操作结果</returns>
        [HttpGet("associate-by-number/{shippingHandoverFormId}")]
        public async Task<IActionResult> AssociateBagTagsByNumber(int shippingHandoverFormId, [FromQuery] string bagTagNumbers, [FromQuery] string callback = null)
        {
            try
            {
                var caller = HttpContext.GetCaller();
                _logger.LogInformation("[Caller: {Caller}] AssociateBagTagsByNumber, ShippingHandoverFormId: {Id}, TagNumbers: {Tags}", caller, shippingHandoverFormId, bagTagNumbers);

                var bagTagNumberList = bagTagNumbers.Split(',').Select(n => n.Trim()).Where(n => !string.IsNullOrEmpty(n)).ToList();
                var result = await _service.AssociateBagTagsByNumberAsync(shippingHandoverFormId, bagTagNumberList);
                var response = new
                {
                    code = 0,
                    message = "success",
                    data = result
                };

                // 处理 JSONP 请求
                if (!string.IsNullOrEmpty(callback))
                {
                    var jsonResult = System.Text.Json.JsonSerializer.Serialize(response);
                    var jsonpResult = $"{callback}({jsonResult})";
                    return Content(jsonpResult, "application/javascript");
                }

                return Ok(response);
            }
            catch (Exception ex)
            {
                var errorResult = new
                {
                    code = 9999,
                    message = ex.Message
                };

                // 处理 JSONP 错误
                if (!string.IsNullOrEmpty(callback))
                {
                    var jsonResult = System.Text.Json.JsonSerializer.Serialize(errorResult);
                    var jsonpResult = $"{callback}({jsonResult})";
                    return Content(jsonpResult, "application/javascript");
                }

                return Ok(errorResult);
            }
        }
    }
}