using DataSharing.FwDataExchange;
using DataSharing.RawData;
using DataSharing.Share.Dtos;
using DataSharing.Share.Dtos.HotlineSetting;
using DataSharing.Share.Dtos.ZiGong.TianQue;
using DotNetCore.CAP;
using Hotline.Share.Dtos.DataSharing.PusherHotlineDto;
using Hotline.Share.Dtos.DataSharingSearch;
using Hotline.Share.Dtos.File;
using MapsterMapper;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using SharpCompress.Common;
using System.Net;
using XF.Domain.Filters;
using XF.Domain.Repository;

namespace DataSharing.Host.Controllers.ZiGong
{
    /// <summary>
    /// 天阙
    /// </summary>
    public class TianQueController : BaseController
    {
        private readonly IMapper _mapper;
        private readonly ICapPublisher _capPublisher;
        private readonly IChannelConfigurationManager _channelConfigurationManager;
        private readonly IDsUserTokenInfoService _dsUserTokenInfoService;
        private readonly IRepository<DsReceiveHandleData> _dsReceiveHandleDataRepository;
        private readonly IHttpClientFactory _httpClientFactory;
        private readonly FwClient _fwClient;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="mapper"></param>
        /// <param name="capPublisher"></param>
        /// <param name="channelConfigurationManager"></param>
        /// <param name="dsUserTokenInfoService"></param>
        /// <param name="dsReceiveHandleDataRepository"></param>
        /// <param name="httpClientFactory"></param>
        /// <param name="fwClient"></param>
        public TianQueController(IMapper mapper,
            ICapPublisher capPublisher,
            IChannelConfigurationManager channelConfigurationManager,
            IDsUserTokenInfoService dsUserTokenInfoService,
            IRepository<DsReceiveHandleData> dsReceiveHandleDataRepository,
            IHttpClientFactory httpClientFactory,
            FwClient fwClient)
        {
            _mapper = mapper;
            _capPublisher = capPublisher;
            _channelConfigurationManager = channelConfigurationManager;
            _dsUserTokenInfoService = dsUserTokenInfoService;
            _dsReceiveHandleDataRepository = dsReceiveHandleDataRepository;
            _httpClientFactory = httpClientFactory;
            _fwClient = fwClient;
        }

        /// <summary>
        /// 随手拍网格员、回复办理结果
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost("writeResult")]
        [AllowAnonymous]
        public async Task<OpenResponse> ReceiverOpinion([FromBody] OrderResultOpinionDto dto)
        {
            //写入对外展示表数据
            DsReceiveHandleData dsReceive = new()
            {
                OrderNo = dto.ReplyCode,
                Source = "随手拍天阙",
                PlatformsName = "随手拍天阙",
                OperationType = dto.ReplyResultType,
                Opinion = dto.ReplyContent,
                ReceiveData = System.Text.Json.JsonSerializer.Serialize(dto)
            };
            var id = await _dsReceiveHandleDataRepository.AddAsync(dsReceive, HttpContext.RequestAborted);

            var accountDto = await _dsUserTokenInfoService.CheckAccountAsync(dto.VailCode, HttpContext.RequestAborted);
            if (accountDto is null || accountDto.IsCheckAccount == false)
                return OpenResponse.Ok(TianQueResponse.Failed("密钥错误"));

            //验证数据
            string strResult = dto.Validate();
            if (!string.IsNullOrEmpty(strResult))
                return OpenResponse.Ok(TianQueResponse.Failed(strResult));

            if (false == IsDate(dto.ReplyDate))
                return OpenResponse.Ok(TianQueResponse.Failed("办理时间格式错误"));

            //todo
            //处理推送数据导hotline
            TianQueReceiverOpinionDto receiverOpinionDto = new()
            {
                No = dto.ReplyCode,
                HandleUser = dto.ReplyUserName,
                HandleOrgName = dto.ReplyBMName,
                HandleType = dto.ReplyResultType,
                ISTrue = dto.ReplyISTrue == "1",
                IsRepeat = dto.IsRepeat == "1",
                RepeatNo = dto.RepeatReplyCode,
                IsHiddenDanger = dto.IsHiddenDanger == "1",
                IsMajorHidden = dto.IsMajorHidden == "1",
                MemberName = dto.MemberName,
                MemberMobile = dto.MemberMobile,
                AppealNumber = dto.AppealNumber,
                ReplyContent = dto.ReplyContent,
                AreaId = dto.OrgId,
                AreaName = dto.OrgName,
                AreaFullName = dto.OrgFullName,
                DepartmentNo = dto.DepartmentNo,
                ParentAreaId = dto.ParentOrgId,
                FileDtos = await GetFiles(dto.ReplyFileList)
            };
            if (!string.IsNullOrEmpty(dto.ReplyDate))
                receiverOpinionDto.HandleTime = DateTime.Parse(dto.ReplyDate);

            //推送业务系统
            await _capPublisher.PublishAsync(Hotline.Share.Mq.EventNames.TianQueReceiverOpinion, receiverOpinionDto, cancellationToken: HttpContext.RequestAborted);

            if (!string.IsNullOrEmpty(id))
                return OpenResponse.Ok(TianQueResponse.Success("回复提交成功"));
            else
                return OpenResponse.Ok(TianQueResponse.Failed("回复提交失败"));
        }

        /// <summary>
        /// 随手拍网格员-短信接口
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost("SendSMS")]
        [AllowAnonymous]
        public async Task<OpenResponse> SendSms([FromBody] SendSmsDto dto)
        {
            //写入对外展示表数据
            DsReceiveHandleData dsReceive = new()
            {
                OrderNo = dto.ReplyCode,
                Source = "随手拍天阙",
                PlatformsName = "随手拍天阙",
                OperationType = "SMS",
                Opinion = dto.SendType,
                ReceiveData = System.Text.Json.JsonSerializer.Serialize(dto)
            };
            await _dsReceiveHandleDataRepository.AddAsync(dsReceive, HttpContext.RequestAborted);

            var accountDto = await _dsUserTokenInfoService.CheckAccountAsync(dto.VailCode, HttpContext.RequestAborted);
            if (accountDto is null || accountDto.IsCheckAccount == false)
                return OpenResponse.Ok(TianQueResponse.Failed("密钥错误"));

            //验证数据
            string strResult = dto.Validate();
            if (!string.IsNullOrEmpty(strResult))
                return OpenResponse.Ok(TianQueResponse.Failed(strResult));

            var data = _mapper.Map<GridOperatorSendSmsDto>(dto);

            var result = await _fwClient.RequestNoTokenAsync<HotlineClientDataSharingResponse<string>>("api/v1/DataSharing/grid_operator_send_sms",
               "Post", System.Text.Json.JsonSerializer.Serialize(data));
            if (result != null && result.code == 0)
            {
                if (result.result == "提交成功")
                    return OpenResponse.Ok(TianQueResponse.Success("提交成功"));
                else
                    return OpenResponse.Ok(TianQueResponse.Failed(result.result));
            }
            else
                return OpenResponse.Ok(TianQueResponse.Failed("提交失败"));
        }

        /// <summary>
        /// 处理附件
        /// </summary>
        /// <param name="FilePath"></param>
        /// <returns></returns>
        private async Task<List<FileDto>> GetFiles(List<string> FilePath)
        {
            List<FileDto> fileDtos = [];
            if (FilePath != null && FilePath.Count > 0)
            {
                var businessFile = _channelConfigurationManager.GetConfigurationBusinessFile();
                foreach (var file in FilePath)
                {
                    //HttpWebRequest request = (HttpWebRequest)WebRequest.Create(file);

                    //byte[] fileContentBytes;
                    //using (Stream stream = request.GetResponse().GetResponseStream())
                    //{
                    //    using (MemoryStream mstream = new MemoryStream())
                    //    {
                    //        int count = 0;
                    //        byte[] buffer = new byte[1024];
                    //        int readNum = 0;
                    //        while ((readNum = stream.Read(buffer, 0, 1024)) > 0)
                    //        {
                    //            count = count + readNum;
                    //            mstream.Write(buffer, 0, readNum);
                    //        }
                    //        mstream.Position = 0;
                    //        using (BinaryReader br = new BinaryReader(mstream))
                    //        {
                    //            fileContentBytes = br.ReadBytes(count);
                    //        }
                    //    }
                    //}
                    var fileName = "";
                    if (file.IndexOf('/') > 1)
                    {
                        fileName = file.Split('/')[file.Split('/').Length - 1].ToString();
                        //fileName = fileName.Substring(0, fileName.LastIndexOf("."));
                        fileName = "WGY_" + fileName;
                    }
                    byte[] fileContentBytes = null;
                    using (var client = _httpClientFactory.CreateClient())
                    using (var response = await client.GetAsync(file))
                    {
                        if (response.StatusCode == HttpStatusCode.OK)
                        {
                            using var memoryStream = new MemoryStream();
                            await response.Content.CopyToAsync(memoryStream);
                            memoryStream.Seek(0, SeekOrigin.Begin);
                            fileContentBytes = memoryStream.ToArray();
                        }
                    }
                    //上传附件到业务服务器
                    if (fileContentBytes != null)
                    {
                        CFormUpload.FileParameter fileParameter = new CFormUpload.FileParameter("fileData", fileContentBytes, fileName, "multipart/form-data");

                        Dictionary<string, object> dicParam = new()
                        {
                            { fileName, fileParameter }
                        };
                        string url = string.Format("{0}{1}?source={2}", businessFile.BaseUrl, businessFile.UploadUrlAddress, businessFile.Source);
                        var result = CFormUpload.MultipartFormDataPost(url, null, dicParam, "");
                        if (!string.IsNullOrEmpty(result))
                        {
                            var resultData = Newtonsoft.Json.JsonConvert.DeserializeObject<BusinessFileResponse>(result);
                            if (resultData != null && resultData.code == 0)
                            {
                                string strSuffix = fileName.LastIndexOf(".") > 0 ? fileName.Substring(fileName.LastIndexOf(".") + 1) : "";
                                strSuffix = strSuffix.Trim('.');
                                fileDtos.Add(new FileDto()
                                {
                                    Name = fileName,
                                    Type = strSuffix,
                                    Classify = "办理上传",
                                    Additions = resultData.result.id,
                                    Path = resultData.result.path,
                                });
                            }
                        }
                    }
                }
            }
            return fileDtos;
        }

        /// <summary>
        /// 校验时间格式
        /// </summary>
        /// <param name="strDate"></param>
        /// <returns></returns>
        private bool IsDate(string strDate)
        {
            try
            {
                DateTime.Parse(strDate);  //不是字符串时会出现异常
                return true;
            }
            catch
            {
                return false;
            }
        }

    }
}
