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 Hotline.Share.Dtos.DataSharingSearch;
using Hotline.Share.Dtos.FlowEngine.Workflow;
using Hotline.Share.Dtos.Order;
using Hotline.Share.Enums.FlowEngine;
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 ZhYBController : 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 ZhYBController(IMapper mapper,
            IRepository<DsReceiveMediaData> dsReceiveMediaDataRepository,
            FwClient fwClient,
            IDsUserTokenInfoService dsUserTokenInfoService)
        {
            _mapper = mapper;
            _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] 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,
                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 = Guid.NewGuid().ToString(),
            };

            data.SourceChannel = "智慧宜宾";
            data.SourceChannelCode = "ZHYB";

            //调用工单创建接口
            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>
        /// 2.3.3查询办理进度
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost("e_GetFlowInfo")]
        [AllowAnonymous]
        public async Task<OpenResponse> GetFlowInfo([FromForm] GetFlowDetailDto 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"));


            GetOrderNoPwdDto getOrder = new()
            {
                No = dto.strCode,
                Password = dto.strCode
            };
            var result = await _fwClient.RequestNoTokenAsync<HotlineClientDataSharingResponse<List<WorkflowTraceDto>>>("api/v1/DataSharing/get_workflow_by_no_pwd",
                "Post", System.Text.Json.JsonSerializer.Serialize(getOrder));

            List<GetFlowInfoReturnDto> getFlowInfos = new();
            if (result != null && result.code == 0)
            {
                if (result.result != null && result.result.Count > 0)
                {
                    foreach (var item in result.result)
                    {
                        getFlowInfos.Add(new GetFlowInfoReturnDto()
                        {
                            AcceptName = item.HandlerOrgName,
                            AcceptUser = item.HandlerName,
                            AcceptContent = item.Opinion,
                            AcceptDate = item.HandleTime.HasValue == true ? item.HandleTime.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                            AcceptState = "已完成"
                        });
                    }
                    if (result.result[result.result.Count - 1].StepType == EStepType.End)
                        getFlowInfos[getFlowInfos.Count - 1].AcceptEnd = "1";
                }
            }

            return OpenResponse.Ok(OtherPlatformsDeResponse<List<GetFlowInfoReturnDto>>.Success(getFlowInfos));
        }

        /// <summary>
        /// 2.3.4查询办理结果
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost("e_GetFlowDetail")]
        [AllowAnonymous]
        public async Task<OpenResponse> GetFlowDetail([FromForm] GetFlowDetailDto 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"));

            GetOrderNoPwdDto getOrder = new()
            {
                No = dto.strCode,
                Password = dto.strCode
            };
            var result = await _fwClient.RequestNoTokenAsync<HotlineClientDataSharingResponse<OrderDto>>("api/v1/DataSharing/get_order_detail_by_no_pwd",
                "Post", System.Text.Json.JsonSerializer.Serialize(getOrder));
            GetFlowDetailReturnDto getFlowDetailReturn = new();
            if (result != null && result.code == 0)
            {
                if (result.result != null)
                {
                    var item = result.result;
                    getFlowDetailReturn.State = item.Status >= EOrderStatus.Filed ? "1" : "0";
                    getFlowDetailReturn.Content = item.ActualOpinion;
                    getFlowDetailReturn.AcceptName = item.ActualHandleOrgName;
                    getFlowDetailReturn.AcceptUser = item.ActualHandlerName;
                    getFlowDetailReturn.AcceptDate = item.ActualHandleTime;
                }
                else
                    return OpenResponse.Ok(OtherPlatformsDeResponse<string>.Failed("编号或密码错误", "0"));
            }

            return OpenResponse.Ok(OtherPlatformsDeResponse<GetFlowDetailReturnDto>.Success(getFlowDetailReturn));
        }

    }
}
