using DataSharing.FwDataExchange;
using DataSharing.RawData;
using DataSharing.Share.Dtos;
using DataSharing.Share.Dtos.HotlineSetting;
using DataSharing.Share.Dtos.YiBin.ZzptPlatformsYB;
using DataSharing.YiBin.ConvergenceMedia;
using DotNetCore.CAP;
using Hotline.Share.Dtos.DataSharingSearch;
using Hotline.Share.Dtos.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 ZzptYBController : BaseController
    {
        private readonly IMapper _mapper;
        private readonly ICapPublisher _capPublisher;
        private readonly IRepository<DsReceiveMediaData> _dsReceiveMediaDataRepository;
        private readonly FwClient _fwClient;
        private readonly IDsUserTokenInfoService _dsUserTokenInfoService;

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

        /// <summary>
        /// 2.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>
        /// 2.3.2网上写信
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost("e_WriteInfo")]
        [AllowAnonymous]
        public async Task<OpenResponse> WriteInfo([FromForm] ZzptAddWriteInfoDto 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);

            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,
                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,
                ExternalId = dto.strZZCode,
                AreaCode = dto.strArea
            };

            data.SourceChannel = "综治平台";
            data.SourceChannelCode = "ZZPT";

            //调用工单创建接口
            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<string>.Success("新增成功"));
            }
            else
                return OpenResponse.Ok(OtherPlatformsDeResponse<string>.Failed("接口调用失败！", "0"));

        }

        /// <summary>
        /// 2.3.3新增办理结果
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost("e_WriteResult")]
        [AllowAnonymous]
        public async Task<OpenResponse> GetFlowInfo([FromForm] ZzptWriteResult 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"));

            if (!IsDate(dto.strDate))
                return OpenResponse.Ok(OtherPlatformsDeResponse<string>.Failed("操作时间日期格式不正确", "0"));

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

            GetOrderDetailDto getOrder = new()
            {
                No = dto.strCode
            };
            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)
                return OpenResponse.Ok(OtherPlatformsDeResponse<string>.Failed("该工单不属于12345", "0"));

            var count = await _dsReceiveMediaDataRepository.Queryable()
            .Where(p => p.ServiceInterface == "e_WriteResult" && p.PlatformsName == accountDto.PlatformSourceName && p.OrderCode == dto.strCode)
            .CountAsync();
            if (count <= 1)
            {
                Hotline.Share.Dtos.DataSharing.PusherHotlineDto.OrderResultDto orderResultDto = new()
                {
                    OrderId = result.result.Id,
                    FinishType = "1",
                    Opinion = dto.strResult,
                    Source = "zzpt"
                };
                await _capPublisher.PublishAsync(Hotline.Share.Mq.EventNames.SharingOrderReultSend, orderResultDto, cancellationToken: HttpContext.RequestAborted);
            }
            return OpenResponse.Ok(OtherPlatformsDeResponse<string>.Success("新增成功"));

        }

        /// <summary>
        /// 验证是否是正确日期
        /// </summary>
        /// <param name="strDate"></param>
        /// <returns></returns>
        private bool IsDate(string strDate)
        {
            try
            {
                DateTime.Parse(strDate);
                return true;
            }
            catch
            {
                return false;
            }
        }

    }
}
