using BLL.Interfaces;
using MDL.Models;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Threading.Tasks;
using Common.Util;

namespace CONTROLLER.Controllers
{
    [Route("api/arrival-handover")]
    [ApiController]
    public class ArrivalHandoverFormController : ControllerBase
    {
        private readonly IArrivalHandoverFormService _arrivalHandoverFormService;

        public ArrivalHandoverFormController(IArrivalHandoverFormService arrivalHandoverFormService)
        {
            _arrivalHandoverFormService = arrivalHandoverFormService;
        }

        [HttpGet("create")]
        public async Task<IActionResult> CreateArrivalHandoverForm(
            [FromQuery] string HandoverNumber,
            [FromQuery] string LogisticsProviderArrivalTime,
            [FromQuery] string ReceiptTime,
            [FromQuery] string? POD,
            [FromQuery] string? Remarks,
            [FromQuery] string Creator,
            [FromQuery] string TimeZone,
            [FromQuery] string callback = null)
        {
            try
            {
                var form = new ArrivalHandoverFormEntity
                {
                    HandoverNumber = HandoverNumber,
                    LogisticsProviderArrivalTime = string.IsNullOrEmpty(LogisticsProviderArrivalTime) ? (DateTime?)null : DateTime.Parse(LogisticsProviderArrivalTime),
                    ReceiptTime = string.IsNullOrEmpty(ReceiptTime) ? (DateTime?)null : DateTime.Parse(ReceiptTime),
                    POD = POD,
                    Remarks = Remarks,
                    Creator = Creator,
                    TimeZone = TimeZone,
                    CreatedAt = DateTime.UtcNow,
                    UpdatedAt = DateTime.UtcNow
                };

                if (string.IsNullOrEmpty(form.HandoverNumber))
                {
                    form.HandoverNumber = await _arrivalHandoverFormService.GenerateArrivalHandoverNumberAsync();
                }
                
                var result = await _arrivalHandoverFormService.CreateArrivalHandoverFormAsync(form);
                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);
            }
        }

        [HttpGet("get/{id}")]
        public async Task<IActionResult> GetArrivalHandoverFormById(int id, [FromQuery] string callback = null)
        {
            try
            {
                var form = await _arrivalHandoverFormService.GetArrivalHandoverFormByIdAsync(id);
                var transformedForm = new
                {
                    form.Id,
                    form.HandoverNumber,
                    logisticsProviderArrivalTime = form.LogisticsProviderArrivalTime.ToTimestamp(),
                    receiptTime = form.ReceiptTime.ToTimestamp(),
                    form.POD,
                    form.Remarks,
                    form.Creator,
                    createdAt = form.CreatedAt.ToTimestamp(),
                    updatedAt = form.UpdatedAt.ToTimestamp(),
                    form.TimeZone,
                    form.Status
                };
                
                var result = new
                {
                    code = 0,
                    message = "success",
                    data = transformedForm
                };

                // 处理 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);
            }
        }

        [HttpGet("get-by-number/{handoverNumber}")]
        public async Task<IActionResult> GetArrivalHandoverFormByNumber(string handoverNumber, [FromQuery] string callback = null)
        {
            try
            {
                var form = await _arrivalHandoverFormService.GetArrivalHandoverFormByNumberAsync(handoverNumber);
                var transformedForm = new
                {
                    form.Id,
                    form.HandoverNumber,
                    logisticsProviderArrivalTime = form.LogisticsProviderArrivalTime.ToTimestamp(),
                    receiptTime = form.ReceiptTime.ToTimestamp(),
                    form.POD,
                    form.Remarks,
                    form.Creator,
                    createdAt = form.CreatedAt.ToTimestamp(),
                    updatedAt = form.UpdatedAt.ToTimestamp(),
                    form.TimeZone,
                    form.Status
                };
                
                var result = new
                {
                    code = 0,
                    message = "success",
                    data = transformedForm
                };

                // 处理 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);
            }
        }

        [HttpGet("list")]
        public async Task<IActionResult> GetArrivalHandoverForms(
            [FromQuery] int page = 1,
            [FromQuery] int pageSize = 10,
            [FromQuery] string sortBy = "CreatedAt",
            [FromQuery] string sortOrder = "desc",
            [FromQuery] string handoverNumber = "",
            [FromQuery] string creator = "",
            [FromQuery] string callback = null)
        {
            try
            {
                var (forms, totalCount) = await _arrivalHandoverFormService.GetArrivalHandoverFormsBatchAsync(
                    page, pageSize, sortBy, sortOrder, handoverNumber, creator);
                
                var transformedForms = forms.ConvertAll(form => new
                {
                    form.Id,
                    form.HandoverNumber,
                    logisticsProviderArrivalTime = form.LogisticsProviderArrivalTime.ToTimestamp(),
                    receiptTime = form.ReceiptTime.ToTimestamp(),
                    form.POD,
                    form.Remarks,
                    form.Creator,
                    createdAt = form.CreatedAt.ToTimestamp(),
                    updatedAt = form.UpdatedAt.ToTimestamp(),
                    form.TimeZone,
                    form.Status
                });
                
                var result = new
                {
                    code = 0,
                    message = "success",
                    data = new
                    {
                        forms = transformedForms,
                        totalCount
                    }
                };

                // 处理 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);
            }
        }

        [HttpGet("update/{id}")]
        public async Task<IActionResult> UpdateArrivalHandoverForm(
            int id,
            [FromQuery] string? LogisticsProviderArrivalTime,
            [FromQuery] string? ReceiptTime,
            [FromQuery] string? POD,
            [FromQuery] string? Remarks,
            [FromQuery] string? TimeZone,
            [FromQuery] string callback = null)
        {
            try
            {
                var form = await _arrivalHandoverFormService.GetArrivalHandoverFormByIdAsync(id);
                if (form == null)
                {
                    throw new Exception("到货交接单不存在");
                }
                
                if (!string.IsNullOrEmpty(LogisticsProviderArrivalTime))
                {
                    form.LogisticsProviderArrivalTime = DateTime.Parse(LogisticsProviderArrivalTime);
                }
                if (!string.IsNullOrEmpty(ReceiptTime))
                {
                    form.ReceiptTime = DateTime.Parse(ReceiptTime);
                }
                if (POD != null)
                {
                    form.POD = POD;
                }
                if (Remarks != null)
                {
                    form.Remarks = Remarks;
                }
                if (TimeZone != null)
                {
                    form.TimeZone = TimeZone;
                }
                form.UpdatedAt = DateTime.UtcNow;
                
                var result = await _arrivalHandoverFormService.UpdateArrivalHandoverFormAsync(form);
                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);
            }
        }

        [HttpGet("delete/{id}")]
        public async Task<IActionResult> DeleteArrivalHandoverForm(int id, [FromQuery] string callback = null)
        {
            try
            {
                var result = await _arrivalHandoverFormService.DeleteArrivalHandoverFormAsync(id);
                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);
            }
        }

        [HttpGet("generate-number")]
        public async Task<IActionResult> GenerateArrivalHandoverNumber([FromQuery] string callback = null)
        {
            try
            {
                var number = await _arrivalHandoverFormService.GenerateArrivalHandoverNumberAsync();
                var result = new
                {
                    code = 0,
                    message = "success",
                    data = number
                };

                // 处理 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);
            }
        }

        public class ReceiptQueryRequest
        {
            public string ArrivalNumber { get; set; }
            public string Callback { get; set; }
        }

        [HttpPost("receipt-query")]
        public async Task<IActionResult> GetReceiptInfo([FromBody] ReceiptQueryRequest request)
        {
            try
            {
                var (packageCount, labelRate, arrivalTime, billOfLadingNumber, masterPackageNumber) = await _arrivalHandoverFormService.GetReceiptInfoAsync(request.ArrivalNumber);
                var result = new
                {
                    code = 0,
                    message = "success",
                    data = new
                    {
                        packageCount,
                        labelRate,
                        arrivalTime,
                        billOfLadingNumber,
                        masterPackageNumber
                    }
                };

                // 处理 JSONP 请求
                if (!string.IsNullOrEmpty(request.Callback))
                {
                    var jsonResult = System.Text.Json.JsonSerializer.Serialize(result);
                    var jsonpResult = $"{request.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(request.Callback))
                {
                    var jsonResult = System.Text.Json.JsonSerializer.Serialize(errorResult);
                    var jsonpResult = $"{request.Callback}({jsonResult})";
                    return Content(jsonpResult, "application/javascript");
                }

                return Ok(errorResult);
            }
        }
    }
}
