using DataSharing.FwDataExchange;
using DataSharing.RawData;
using DataSharing.Share.Dtos;
using DataSharing.Share.Dtos.HotlineSetting;
using DataSharing.Share.Dtos.YiBin.ConvergenceMedia;
using DataSharing.Share.Dtos.YiBin.WllzYB;
using DataSharing.Share.Dtos.YiBin.ZzptPlatformsYB;
using DataSharing.YiBin.ConvergenceMedia;
using Hotline.Share.Dtos;
using Hotline.Share.Dtos.DataSharingSearch;
using Hotline.Share.Dtos.Order;
using Hotline.Share.Enums.Order;
using MapsterMapper;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using XF.Domain.Filters;
using XF.Domain.Repository;

namespace DataSharing.Host.Controllers.YiBin
{
    /// <summary>
    /// 网络理政
    /// </summary>
    public class WllzYBController : BaseController
    {
        private readonly IMapper _mapper;
        private readonly IRepository<DsReceiveMediaData> _dsReceiveMediaDataRepository;
        private readonly FwClient _fwClient;
        private readonly IDsUserTokenInfoService _dsUserTokenInfoService;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="mapper"></param>
        /// <param name="dsReceiveMediaDataRepository"></param>
        /// <param name="fwClient"></param>
        /// <param name="dsUserTokenInfoService"></param>
        public WllzYBController(IMapper mapper,
            IRepository<DsReceiveMediaData> dsReceiveMediaDataRepository,
            FwClient fwClient,
            IDsUserTokenInfoService dsUserTokenInfoService)
        {
            _mapper = mapper;
            _dsReceiveMediaDataRepository = dsReceiveMediaDataRepository;
            _fwClient = fwClient;
            _dsUserTokenInfoService = dsUserTokenInfoService;
        }

        /// <summary>
        /// 1.3.1查询受理类型
        /// </summary>
        /// <param name="strVailCode"></param>
        /// <returns></returns>
        [HttpPost("e_GetTypeID")]
        [AllowAnonymous]
        public async Task<OpenResponse> GetAcceptType([FromForm] string strVailCode)
        {
            var accountDto = await _dsUserTokenInfoService.CheckAccountAsync(strVailCode, HttpContext.RequestAborted);
            if (accountDto is null || accountDto.IsCheckAccount == false)
                return OpenResponse.Ok(OtherPlatformsDeResponse<string>.Failed("密钥错误", "-900"));
            var result = await _fwClient.RequestNoTokenAsync<HotlineClientDataSharingResponse<List<AcceptTypeListDto>>>("api/v1/DataSharing/get_accept_type_list",
               "Post", "");
            List<AcceptTypeListDto> data = [];
            if (result != null && result.code == 0 && result.result != null && result.result.Count > 0)
            {
                data = result.result;
            }

            return OpenResponse.Ok(OtherPlatformsDeResponse<List<AcceptTypeListDto>>.Success(data));
        }

        /// <summary>
        ///1.3.2网上写信
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost("e_WriteInfo")]
        [AllowAnonymous]
        public async Task<OpenResponse> WriteInfo([FromForm] AddWriteInfoDto dto)
        {
            var accountDto = await _dsUserTokenInfoService.CheckAccountAsync(dto.strVailCode, HttpContext.RequestAborted);
            if (accountDto is null || accountDto.IsCheckAccount == false)
                return OpenResponse.Ok(OtherPlatformsDeResponse<string>.Failed("密钥错误", "-900"));

            //验证数据
            string strResult = dto.Validate();
            if (!string.IsNullOrEmpty(strResult))
                return OpenResponse.Ok(OtherPlatformsDeResponse<string>.Failed(strResult, "0"));

            //写入原始数据
            DsReceiveMediaData dsReceiveMediaData = new()
            {
                ServiceInterface = "e_WriteInfo",
                PlatformsName = accountDto.PlatformSourceName,
                // ExternalId = dto.strZZCode,
                ReceiveData = System.Text.Json.JsonSerializer.Serialize(dto)
            };
            dsReceiveMediaData.Id = await _dsReceiveMediaDataRepository.AddAsync(dsReceiveMediaData, HttpContext.RequestAborted);

            var resultType = await _fwClient.RequestNoTokenAsync<HotlineClientDataSharingResponse<List<AcceptTypeListDto>>>("api/v1/DataSharing/get_accept_type_list",
              "Post", "");
            var acceptType = "";
            if (resultType != null && resultType.code == 0 && resultType.result != null && resultType.result.Count > 0)
            {
                var typelist = resultType.result.Find(p => p.Value == dto.strTypeID);
                if (typelist == null || string.IsNullOrEmpty(typelist.Value) || string.IsNullOrEmpty(typelist.Name))
                    return OpenResponse.Ok(OtherPlatformsDeResponse<string>.Failed("不包含此类型ID", "0"));
                acceptType = typelist.Name;
            }

            Hotline.Share.Dtos.Order.AddOrderDto data = new()
            {
                Title = dto.strTitle,
                FromName = dto.strUserName,
                Contact = dto.strPhone,
                FullAddress = dto.strAddress,
                Content = dto.strContent,
                IsSecret = false,
                AcceptTypeCode = dto.strTypeID,
                AcceptType = acceptType,
                Source = (Hotline.Share.Enums.Order.ESource)Enum.Parse(typeof(Hotline.Share.Enums.Order.ESource), accountDto.PlatformSource),
                FromGender = dto.strGender switch
                {
                    "1" => Hotline.Share.Enums.Order.EGender.Male,
                    "2" => Hotline.Share.Enums.Order.EGender.Female,
                    _ => Hotline.Share.Enums.Order.EGender.Unknown,
                },
                IdentityType = Hotline.Share.Enums.Order.EIdentityType.Citizen,
                Transpond = false,
                IsEnforcementOrder = false,
                SourceChannel = accountDto.PlatformSourceName,
                SourceChannelCode = accountDto.PlatformSource,
                ExternalId = Guid.NewGuid().ToString()
            };


            //调用工单创建接口
            var result = await _fwClient.RequestNoTokenAsync<HotlineClientResponse>("api/v1/Order/add-anonymous", "Post", System.Text.Json.JsonSerializer.Serialize(data));
            if (result != null && result.code == 0)
            {
                dsReceiveMediaData.ExternalId = result.result.id;
                dsReceiveMediaData.OrderCode = result.result.no;
                await _dsReceiveMediaDataRepository.UpdateAsync(dsReceiveMediaData, HttpContext.RequestAborted);

                List<WriteInfoReturnDto> returnData = new()
                {
                    new WriteInfoReturnDto() { LetterCode = result.result.no, LetterPwd = result.result.password }
                };
                return OpenResponse.Ok(OtherPlatformsDeResponse<List<WriteInfoReturnDto>>.Success(returnData));
            }
            else
                return OpenResponse.Ok(OtherPlatformsDeResponse<string>.Failed("接口调用失败！", "0"));

        }

        /// <summary>
        /// 1.3.3办件结果查询
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost("e_OrderInfo")]
        [AllowAnonymous]
        public async Task<OpenResponse> GetFlowInfo([FromForm] WllzGetOrderInfo dto)
        {
            var accountDto = await _dsUserTokenInfoService.CheckAccountAsync(dto.strVailCode, HttpContext.RequestAborted);
            if (accountDto is null || accountDto.IsCheckAccount == false)
                return OpenResponse.Ok(OtherPlatformsDeResponse<string>.Failed("密钥错误", "-900"));

            //验证数据
            string strResult = dto.Validate();
            if (!string.IsNullOrEmpty(strResult))
                return OpenResponse.Ok(OtherPlatformsDeResponse<string>.Failed(strResult, "0"));

            string[] arrCode = dto.strCodes.Split(',');
            if (arrCode == null || arrCode.Length == 0)
                return OpenResponse.Ok(OtherPlatformsDeResponse<string>.Failed("工单编号错误", "0"));

            List<WllzOrderInfoReturnDto> returnDtos = new();
            foreach (var item in arrCode)
            {
                GetOrderDetailDto getOrder = new()
                {
                    No = item
                };
                var result = await _fwClient.RequestNoTokenAsync<HotlineClientDataSharingResponse<OrderDto>>("api/v1/DataSharing/get_order_detail_by_no",
                    "Post", System.Text.Json.JsonSerializer.Serialize(getOrder));

                if (result != null && result.code == 0 && result.result != null)
                {
                    var itemOrder = result.result;
                    returnDtos.Add(new()
                    {
                        Code = itemOrder.No,
                        State = itemOrder.Status >= EOrderStatus.Filed ? "办理完成" : "办理中",
                        Ccontent = itemOrder.ActualOpinion,
                        AcceptName = itemOrder.ActualHandleOrgName,
                        AcceptDate = itemOrder.ActualHandleTime != null ? itemOrder.ActualHandleTime.Value.ToString("yyyy-MM-dd HH:mm:ss") : ""
                    }); ;
                }
                else
                {
                    returnDtos.Add(new()
                    {
                        Code = item,
                        State = "受理中",
                        Ccontent = "",
                        AcceptName = "热线中心",
                        AcceptDate = ""
                    });
                }
            }
            return OpenResponse.Ok(OtherPlatformsDeResponse<List<WllzOrderInfoReturnDto>>.Success(returnDtos));
        }

        /// <summary>
        /// 办件摘编
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost("GetFlowExtract")]
        [AllowAnonymous]
        public async Task<OpenResponse> GetFlowExtract([FromForm] GetOrderWllzReceiveOpenDto dto)
        {
            var accountDto = await _dsUserTokenInfoService.CheckAccountAsync(dto.strVailCode, HttpContext.RequestAborted);
            if (accountDto is null || accountDto.IsCheckAccount == false)
                return OpenResponse.Ok(OtherPlatformsDeResponse<string>.Failed("密钥错误", "-900"));

            //验证数据
            string strResult = dto.Validate();
            if (!string.IsNullOrEmpty(strResult))
                return OpenResponse.Ok(OtherPlatformsDeResponse<string>.Failed(strResult, "0"));

            int pageIndex = string.IsNullOrEmpty(dto.CurrentPage) == true ? 1 : Convert.ToInt32(dto.CurrentPage);
            int pageSize = string.IsNullOrEmpty(dto.PageSize) == true ? 1 : Convert.ToInt32(dto.PageSize);
            GetOrderList getOrder = new GetOrderList()
            {
                PageIndex = pageIndex,
                PageSize = pageSize
            };

            var result = await _fwClient.RequestNoTokenAsync<HotlineClientDataSharingResponse<PagedDto<PublishDto>>>("api/v1/DataSharing/get_order_list_publish",
               "Post", System.Text.Json.JsonSerializer.Serialize(getOrder));
            int nPageCount = 0;
            List<GetOrderWllzDataListDto> listData = [];
            if (result != null && result.code == 0)
            {
                if (result.result.Items != null && result.result.Items.Count > 0)
                {
                    nPageCount = result.result.Total;
                    foreach (var item in result.result.Items)
                    {
                        listData.Add(new GetOrderWllzDataListDto()
                        {
                            FlowID = item.Id,
                            Code = item.No,
                            Title = item.Title,
                            AddDate = item.CreationTime.ToString("yyyy-MM-dd"),
                            FromName = item.SourceChannel,
                            PurTypeName = item.AcceptType,
                            StateName = item.Status >= EOrderStatus.Filed ? "办理完成" : "办理中",
                            PubDate = item.PublishTime.HasValue == true ? item.PublishTime.Value.ToString("yyyy-MM-dd") : ""
                        });
                    }
                }
            }
            //返回数据处理
            List<GetOrderWllzDataDto> dataDto = new()
            {
              new(){  TotalNum = nPageCount,
                List = listData
              }
            };

            return OpenResponse.Ok(OtherPlatformsDeResponse<List<GetOrderWllzDataDto>>.Success(dataDto));
        }

        /// <summary>
        /// 每日统计
        /// </summary>
        /// <param name="strVailCode"></param>
        /// <returns></returns>
        [HttpPost("GetPortalStatisticsNew")]
        [AllowAnonymous]
        public async Task<OpenResponse> GetPortalStatisticsNew([FromForm] string strVailCode)
        {
            var accountDto = await _dsUserTokenInfoService.CheckAccountAsync(strVailCode, HttpContext.RequestAborted);
            if (accountDto is null || accountDto.IsCheckAccount == false)
                return OpenResponse.Ok(OtherPlatformsDeResponse<string>.Failed("密钥错误", "-900"));

            #region 总量
            //总量
            var resultCount = await _fwClient.RequestNoTokenAsync<HotlineClientDataSharingResponse<DayStatisticsDto>>("api/v1/DataSharing/get_day_count",
               "Post", "");
            List<DayStatisticsDto> dataCount = [];
            if (resultCount != null && resultCount.code == 0 && resultCount.result != null)
                dataCount.Add(resultCount.result);
            #endregion

            #region 查询受理类型
            //查询受理类型
            var resultType = await _fwClient.RequestNoTokenAsync<HotlineClientDataSharingResponse<List<GetPurTypeReportDataDto>>>("api/v1/DataSharing/get_pur_type_report",
               "Post", "");
            List<KeyValueDto> dataType = [];
            if (resultType != null && resultType.code == 0 && resultType.result != null && resultType.result.Count > 0)
            {
                foreach (var kv in resultType.result)
                {
                    dataType.Add(new()
                    {
                        Name = kv.PurTypeName,
                        Value = kv.Count
                    });
                }
            }
            #endregion

            #region 查询热点
            //查询热点
            var resultHotspot = await _fwClient.RequestNoTokenAsync<HotlineClientDataSharingResponse<List<KeyValueDto>>>("api/v1/DataSharing/get_hotspot_statistics_list",
               "Post", "");
            List<KeyValueDto> dataHotspot = [];
            if (resultHotspot != null && resultHotspot.code == 0 && resultHotspot.result != null && resultHotspot.result.Count > 0)
                dataHotspot = resultHotspot.result;

            PortalStatisticsDto statisticsDto = new PortalStatisticsDto()
            {
                Info = dataCount,
                Type = dataType,
                From = dataHotspot,
                Overdue = []
            };
            #endregion

            return OpenResponse.Ok(OtherPlatformsDeResponse<PortalStatisticsDto>.Success(statisticsDto));
        }
    }
}
