using iTextSharp.text;
using Newtonsoft.Json;
using NPOI.HPSF;
using NPOI.SS.Formula.Functions;
using RestSharp;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using XYY.Core.Standard.Data.Infrastructure;
using XYY.Core.Standard.ExcelHelper.MSExcelHelper;
using XYY.Model.Standard.Channel;
using XYY.Model.Standard.Dto.order;

namespace XYY.Service.Standard.Order
{
    public interface IAddressVerifService
    {
        Task<string> DHLAddressVerify(System.IO.Stream stream);
    }
    public class AddressVerifService : IAddressVerifService
    {
        IUnitOfWork _unitOfWork;
        private IExcelHelper _excelHelper;
        public AddressVerifService(IUnitOfWork unitOfWork, IExcelHelper excelHelper)
        {
            _unitOfWork = unitOfWork;
            _excelHelper = excelHelper;
        }
        public async Task<string> DHLAddressVerify(System.IO.Stream stream)
        {
            List<DHLInputModel> models = new List<DHLInputModel>();
            models = _excelHelper.LoadDataAsStream<DHLInputMapping, DHLInputModel>(stream);
            foreach (var item in models)
            {
                var result = await GetDHLVerifyResult(item);
                item.Message = result.Item2;
            }
            var data = _excelHelper.OutDataAsByte<DHLInputMapping, DHLInputModel>(models);
            //直接保存文件
            string pathName = $"检测结果{DateTime.Now.ToString("yyyyMMddHHmmss")}";
            string path = getTempFilePath(pathName);
            FileStream file = new FileStream(path, FileMode.Create);
            file.Write(data, 0, data.Length);
            file.Dispose();
            return pathName;
        }
        private string getTempFilePath(string name)
        {
            string basePath = System.IO.Path.Combine(System.AppContext.BaseDirectory, "temp", "DHLAddressVerifyResult");
            if (!System.IO.Directory.Exists(basePath))
                System.IO.Directory.CreateDirectory(basePath);
            return System.IO.Path.Combine(basePath, name + ".xlsx");
        }
        private async Task<Tuple<bool, string>> GetDHLVerifyResult(DHLInputModel model)
        {
            var client = new RestClient($"http://express.api.dhl.com/mydhlapi/rates?accountNumber={model.accountNumber}&originCountryCode={model.originCountryCode}&isCustomsDeclarable={model.isCustomsDeclarable}&originCityName={model.originCityName}&unitOfMeasurement={model.unitOfMeasurement}&length={model.length}&width={model.width}&height={model.height}&weight={model.weight}&destinationCountryCode={model.destinationCountryCode}&plannedShippingDate={model.plannedShippingDate.ToString("yyyy-MM-dd")}&destinationCityName={model.destinationCityName}&destinationPostalCode={model.destinationPostalCode}");
            client.Timeout = -1;
            var request = new RestRequest(Method.GET);
            request.AddHeader("Authorization", "Basic Z29uZ2hla2VqaWNDTjpLJDVkTV40eVVeNmtRXjV0");
            IRestResponse response = client.Execute(request);
            if (response.StatusCode == System.Net.HttpStatusCode.OK) {
                try
                {
                    var result = JsonConvert.DeserializeObject<DHLOutputModel>(response.Content);
                    if (result.products.Any(x => x.detailedPriceBreakdown.Any(y => y.breakdown.Any(z => z.name == "REMOTE AREA DELIVERY"))))
                    {
                        return Tuple.Create<bool, string>(false, "该地址属于偏远地址");
                    }
                    else
                    {
                        return Tuple.Create<bool, string>(true, "地址正常");
                    }

                }
                catch (Exception ex)
                {
                    return Tuple.Create<bool, string>(false, "解析异常，请联系技术！"+ex.Message);
                }
            }
            else { 
                return Tuple.Create<bool, string>(false,"验证接口请求异常，请检查参数是否正确！");
            }
        }


    }
}
