using DataSharing.FwDataExchange;
using DataSharing.RawData;
using DataSharing.Share.Dtos.HotlineSetting;
using DataSharing.Share.Dtos.YiBin.ConvergenceMedia;
using DataSharing.YiBin.ConvergenceMedia;
using Hotline.Share.Dtos.DataSharingSearch;
using Hotline.Share.Dtos.File;
using Hotline.Share.Dtos.FlowEngine.Workflow;
using Hotline.Share.Dtos.Order;
using Hotline.Share.Dtos;
using Hotline.Share.Enums.Order;
using MapsterMapper;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json.Linq;
using XF.Domain.Filters;
using XF.Domain.Repository;
using DataSharing.Share.Dtos;
using DataSharing.Share.Dtos.ZiGong.DockingPlatform;
using System.Net;
using System.Text;
using Newtonsoft.Json;

namespace DataSharing.Host.Controllers.ZiGong
{
    /// <summary>
    /// 自贡12345天府通办、自贡12345观察
    /// 测试地址：http://110.188.24.28:50105
    /// 天府通办密钥：FWZGTFTB001
    /// 自贡观察密钥：FWZGGC716
    /// </summary>
    public class DockingPlatformController : BaseController
    {
        #region 注入
        private readonly IMapper _mapper;
        private readonly IChannelConfigurationManager _channelConfigurationManager;
        private readonly IRepository<DsReceiveMediaData> _dsReceiveMediaDataRepository;
        private readonly FwClient _fwClient;
        private readonly IDsUserTokenInfoService _dsUserTokenInfoService;
        private readonly ISharingConfigurationManager _sharingConfigurationManager;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="mapper"></param>
        /// <param name="channelConfigurationManager"></param>
        /// <param name="dsReceiveMediaDataRepository"></param>
        /// <param name="fwClient"></param>
        /// <param name="dsUserTokenInfoService"></param>
        /// <param name="sharingConfigurationManager"></param>
        public DockingPlatformController(IMapper mapper,
            IChannelConfigurationManager channelConfigurationManager,
            IRepository<DsReceiveMediaData> dsReceiveMediaDataRepository,
            FwClient fwClient,
            IDsUserTokenInfoService dsUserTokenInfoService,
            ISharingConfigurationManager sharingConfigurationManager)
        {
            _mapper = mapper;
            _channelConfigurationManager = channelConfigurationManager;
            _dsReceiveMediaDataRepository = dsReceiveMediaDataRepository;
            _fwClient = fwClient;
            _dsUserTokenInfoService = dsUserTokenInfoService;
            _sharingConfigurationManager = sharingConfigurationManager;
        }
        #endregion

        #region 2.1.1 工单写信

        /// <summary>
        /// 2.1 写信---1 
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost("WriteOrder")]
        [AllowAnonymous]
        public async Task<OpenResponse> WriteOrder([FromBody] WriteOrderReceiveDto dto)
        {
            var accountDto = await _dsUserTokenInfoService.CheckAccountAsync(dto.Code, HttpContext.RequestAborted);
            if (accountDto is null || accountDto.IsCheckAccount == false)
            {
                List<WriteOrderResponseDto> responseDtos = new()
                {
                    new WriteOrderResponseDto() { AcceptCode = "", AcceptPwd = "", Msg = "密钥错误", Code = "-900" }
                };

                return OpenResponse.Ok(ConvergenceMediaDeResponse<List<WriteOrderResponseDto>>.Failed(responseDtos, "0", "密钥错误"));
            }

            //验证数据
            string strResult = dto.Validate();
            if (!string.IsNullOrEmpty(strResult))
            {
                List<WriteOrderResponseDto> responseDtos = new()
                {
                    new WriteOrderResponseDto() { AcceptCode = "", AcceptPwd = "", Msg = strResult, Code = "0" }
                };
                return OpenResponse.Ok(ConvergenceMediaDeResponse<List<WriteOrderResponseDto>>.Failed(responseDtos, "0", description: strResult));
            }

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

            AddOrderDto data = new()
            {
                Title = dto.Title,
                FromName = dto.LinkName,
                Contact = dto.Mobile,
                FullAddress = dto.Address,
                Content = dto.Content,
                IsSecret = dto.Secrecy == 0 ? false : true,
                Source = (Hotline.Share.Enums.Order.ESource)System.Enum.Parse(typeof(Hotline.Share.Enums.Order.ESource), accountDto.PlatformSource),
                FromGender = dto.Gender 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()
            };

            switch (accountDto.PlatformSource)
            {
                case "ZGGC":
                    data.SourceChannel = "自贡观察";
                    data.SourceChannelCode = "observe";
                    break;
                case "ZGTFTB":
                    data.SourceChannel = "天府通办";
                    data.SourceChannelCode = "TFTB001";
                    break;
                default:
                    break;
            }

            switch (dto.PurTypeID)
            {
                case 17:
                    data.AcceptType = "咨询";
                    data.AcceptTypeCode = "10";
                    break;
                case 18:
                    data.AcceptType = "举报";
                    data.AcceptTypeCode = "30";
                    break;
                case 19:
                    data.AcceptType = "投诉";
                    data.AcceptTypeCode = "35";
                    break;
                case 20:
                    data.AcceptType = "求助";
                    data.AcceptTypeCode = "20";
                    break;
                case 21:
                    data.AcceptType = "建议";
                    data.AcceptTypeCode = "15";
                    break;
                case 1906:
                    data.AcceptType = "表扬";
                    data.AcceptTypeCode = "25";
                    break;
                default:
                    data.AcceptType = "咨询";
                    data.AcceptTypeCode = "10";
                    break;
            }

            string areaName = "";
            switch (dto.AreaID)
            {
                case 2:
                    data.AreaCode = "510302"; areaName = "自流井区";
                    break;
                case 3:
                    data.AreaCode = "510303"; areaName = "贡井区";
                    break;
                case 4:
                    data.AreaCode = "510304"; areaName = "大安区";
                    break;
                case 5:
                    data.AreaCode = "510311"; areaName = "沿滩区";
                    break;
                case 6:
                    data.AreaCode = "510321"; areaName = "荣县";
                    break;
                case 7:
                    data.AreaCode = "510322"; areaName = "富顺县";
                    break;
                case 59:
                    data.AreaCode = "519800"; areaName = "高新区";
                    break;
                default:
                    data.AreaCode = "510300";
                    break;
            }
            data.Address = "四川省自贡市" + areaName;

            //调用工单创建接口
            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<WriteOrderResponseDto> responseDtos = new()
                {
                    new WriteOrderResponseDto() { AcceptCode = result.result.no, AcceptPwd = result.result.password, Msg = "写信成功", Code = "1" }
                };
                return OpenResponse.Ok(ConvergenceMediaDeResponse<List<WriteOrderResponseDto>>.Success(responseDtos, "您已成功提交数据！"));
            }
            else
            {
                List<WriteOrderResponseDto> responseDtos = new()
                {
                  new WriteOrderResponseDto() { AcceptCode = "", AcceptPwd = "", Msg = "接口调用失败", Code = "0" }
                };
                return OpenResponse.Ok(ConvergenceMediaDeResponse<List<WriteOrderResponseDto>>.Failed(responseDtos, "0", description: "接口调用失败！"));
            }

        }

        #endregion

        #region 2.1.2 上传附件

        /// <summary>
        /// 2.1.2 上传附件---1
        /// </summary>
        /// <param name="formData"></param>
        /// <returns></returns>
        [HttpPost("WriteFiles")]
        [AllowAnonymous]
        public async Task<OpenResponse> WriteFiles([FromForm] IFormCollection formData)
        {
            string Code = formData["Code"];
            string AcceptCode = formData["AcceptCode"];
            string AcceptPwd = formData["AcceptPwd"];

            //验证密钥
            var accountDto = await _dsUserTokenInfoService.CheckAccountAsync(Code, HttpContext.RequestAborted);
            if (accountDto is null || accountDto.IsCheckAccount == false)
            {
                List<ConvergenceMediaDeResponse<string>> convergenceMediaDes = new() {
                new()
                {
                    msg = "密钥错误",
                    code = "-900",
                    data = ""
                } };

                return OpenResponse.Ok(ConvergenceMediaDeResponse<List<ConvergenceMediaDeResponse<string>>>.Failed(convergenceMediaDes, "0", "失败"));
            }

            //验证数据
            if (string.IsNullOrEmpty(AcceptCode) || string.IsNullOrEmpty(AcceptPwd))
                return OpenResponse.Ok(ConvergenceMediaDeResponse<string>.Failed("编号、密码不能为空！", "0", "失败"));

            var dataRaw = await _dsReceiveMediaDataRepository.GetAsync(p => p.OrderCode == AcceptCode, HttpContext.RequestAborted);

            IFormFileCollection files = formData.Files;//等价于Request.Form.Files

            List<FileDto> fileDtos = new();

            foreach (var item in files)
            {
                //这里需要上文件服务器上传
                var businessFileDto = await SendFileData(item);

                string strFileName = item.FileName;
                string strSuffix = strFileName.LastIndexOf(".") > 0 ? strFileName.Substring(strFileName.LastIndexOf(".") + 1) : "";
                string strSubFileName = strFileName.LastIndexOf(".") > 0 ? strFileName.Substring(0, strFileName.LastIndexOf(".")) : strFileName;
                fileDtos.Add(new FileDto()
                {
                    Name = strSubFileName,
                    Type = strSuffix,
                    Classify = "受理上传",
                    Additions = businessFileDto.id,
                    Path = businessFileDto.path,
                    AllPath = businessFileDto.path,
                    FileName = item.FileName,
                });
            }

            UpdateOrderFilesDto updateOrderFiles = new()
            {
                Files = fileDtos,
                Id = dataRaw.ExternalId,
                OrderNo = dataRaw.OrderCode
            };

            //推送数据
            var result = await _fwClient.RequestNoTokenAsync<HotlineClientResponse>("api/v1/Order/update-orderfiles", "Post", System.Text.Json.JsonSerializer.Serialize(updateOrderFiles));
            return OpenResponse.Ok(ConvergenceMediaDeResponse<string>.Success("", "上传成功"));
        }

        #endregion

        #region 2.2.1 工单列表

        /// <summary>
        /// 2.2.1 工单列表
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost("GetOrderByList")]
        [AllowAnonymous]
        public async Task<OpenResponse> GetOrderByList([FromBody] GetOrderMediaReceiveDto dto)
        {
            //密钥验证
            var accountDto = await _dsUserTokenInfoService.CheckAccountAsync(dto.Code, HttpContext.RequestAborted);
            if (accountDto is null || accountDto.IsCheckAccount == false)
            {
                List<ConvergenceMediaDeResponse<string>> convergenceMediaDes = new() {
                new()
                {
                    msg = "密钥错误",
                    code = "-900",
                    data = ""
                } };

                return OpenResponse.Ok(ConvergenceMediaDeResponse<List<ConvergenceMediaDeResponse<string>>>.Failed(convergenceMediaDes, "0", "失败"));
            }

            //数据处理
            string acceptTypeCode = dto.PurTypeID switch
            {
                17 => "10",
                18 => "30",
                19 => "35",
                20 => "20",
                21 => "15",
                1906 => "25",
                _ => "",
            };
            GetOrderList orderList = new()
            {
                SourceChannelCode = GetChannelCode(accountDto.PlatformSource),
                No = dto.AcceptCode,
                Title = dto.Title,
                Mobile = dto.Mobile,
                AcceptTypeCode = acceptTypeCode,
                StartTime = string.IsNullOrEmpty(dto.StartDate) == true ? null : Convert.ToDateTime(dto.StartDate),
                EndTime = string.IsNullOrEmpty(dto.EndDate) == true ? null : Convert.ToDateTime(dto.EndDate).AddDays(1),
                PageIndex = dto.CurrentPage,
                PageSize = dto.PageSize,
                HandleStateCode = dto.HandleStateCode,
            };

            List<GetOrderMediaDataListDto> listData = [];
            string strFromType = accountDto.PlatformSource;
            //查询旧系统
            Dictionary<string, object> dic = new Dictionary<string, object>
                {
                    { "AcceptCode", dto.AcceptCode },
                    { "Title", dto.Title },
                    { "Mobile", dto.Mobile},
                    { "PurTypeID", dto.PurTypeID},
                    { "HandleStateCode", dto.HandleStateCode},
                    { "StartDate", dto.StartDate},
                    { "EndDate", dto.EndDate},
                    {"StrFromType",strFromType },
                    { "CurrentPage", 1},
                    { "PageSize", 500 },
                };
            var strUrl = _sharingConfigurationManager.GetZiGongConfig().TFTB.QueryOldList + "zg12345/OrderAccept.asmx/GetOrderByListNew";
            var strResultData = e_SendHttpPostBySync(strUrl, dic);
            if (!string.IsNullOrEmpty(strResultData))
            {
                JObject job = (JObject)JsonConvert.DeserializeObject(strResultData);
                if (job != null && "1" == job["code"].ToString())
                {
                    if (!string.IsNullOrEmpty(job["dataInfo"].ToString()) && !string.IsNullOrEmpty(job["dataInfo"]["data"].ToString()))
                    {
                        listData = Newtonsoft.Json.JsonConvert.DeserializeObject<List<GetOrderMediaDataListDto>>(job["dataInfo"]["data"].ToString().ToString());
                    }
                }
            }

            var result = await _fwClient.RequestNoTokenAsync<HotlineClientDataSharingResponse<PagedDto<OrderDto>>>("api/v1/DataSharing/get_order_list_own",
                "Post", System.Text.Json.JsonSerializer.Serialize(orderList));
            int nPageCount = 0;
            if (result != null && result.code == 0)
            {
                if (result.result.Items != null && result.result.Items.Count > 0)
                {
                    //计算总页数
                    nPageCount = Convert.ToInt32(Math.Ceiling(Convert.ToDouble(result.result.Total) / dto.PageSize));
                    int rowID = 0;
                    foreach (var item in result.result.Items)
                    {
                        rowID++;
                        listData.Add(new GetOrderMediaDataListDto()
                        {
                            RowID = ((dto.CurrentPage - 1) * dto.PageSize) + rowID + "",
                            FlowID = item.Id,
                            Code = item.No,
                            Title = item.Title,
                            AddDate = item.CreationTime.ToString("yyyy-MM-dd HH:mm:ss"),
                            FromName = item.SourceChannel,
                            PurTypeName = item.AcceptType,
                            ResultState = item.Status >= EOrderStatus.Filed ? "办理完成" : "办理中"
                        });
                    }
                }
            }
            var list = listData.OrderByDescending(p => p.AddDate).ToList();
            int skip = dto.CurrentPage - 1;
            List<GetOrderMediaDataListDto> listDataReturn = [];
            listDataReturn = list.Skip(skip * dto.PageSize).Take(dto.PageSize).ToList();
            int rowIDNew = 0;
            foreach (var item in listDataReturn)
            {
                rowIDNew++;
                item.RowID = ((dto.CurrentPage - 1) * dto.PageSize) + rowIDNew + "";
            }
            nPageCount = Convert.ToInt32(Math.Ceiling(Convert.ToDouble(list.Count) / dto.PageSize));

            List<GetOrderMediaDataDto> returnData = new()
            {
            //处理返回
            new()
            {
                PageCount = nPageCount,
                data = listDataReturn
            } };

            return OpenResponse.Ok(ConvergenceMediaDeResponse<List<GetOrderMediaDataDto>>.Success(returnData, "成功"));

        }

        #endregion

        #region 2.2.2 工单列表（暂不使用）

        /// <summary>
        /// 2.2.2 工单列表
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost("GetOrderByListWatch")]
        [AllowAnonymous]
        public async Task<OpenResponse> GetOrderByListIyb([FromBody] GetOrderMediaReceiveDto dto)
        {
            //密钥验证
            var accountDto = await _dsUserTokenInfoService.CheckAccountAsync(dto.Code, HttpContext.RequestAborted);
            if (accountDto is null || accountDto.IsCheckAccount == false)
            {
                List<ConvergenceMediaDeResponse<string>> convergenceMediaDes = new() {
                new()
                {
                    msg = "密钥错误",
                    code = "-900",
                    data = ""
                } };

                return OpenResponse.Ok(ConvergenceMediaDeResponse<List<ConvergenceMediaDeResponse<string>>>.Failed(convergenceMediaDes, "0", "失败"));
            }

            //数据处理
            string acceptTypeCode = dto.PurTypeID switch
            {
                17 => "10",
                18 => "30",
                19 => "35",
                20 => "20",
                21 => "15",
                25 => "40",
                _ => "",
            };
            GetOrderList orderList = new()
            {
                SourceChannelCode = accountDto.PlatformSource,
                No = dto.AcceptCode,
                Title = dto.Title,
                Mobile = dto.Mobile,
                AcceptTypeCode = acceptTypeCode,
                StartTime = string.IsNullOrEmpty(dto.StartDate) == true ? null : Convert.ToDateTime(dto.StartDate),
                EndTime = string.IsNullOrEmpty(dto.EndDate) == true ? null : Convert.ToDateTime(dto.EndDate).AddDays(1),
                PageIndex = dto.CurrentPage,
                PageSize = dto.PageSize,
                HandleStateCode = dto.HandleStateCode,
            };

            List<GetOrderMediaDataListDto> listData = [];
            string strFromType = accountDto.PlatformSource;
            //查询旧系统
            Dictionary<string, object> dic = new Dictionary<string, object>
                {
                    { "AcceptCode", dto.AcceptCode },
                    { "Title", dto.Title },
                    { "Mobile", dto.Mobile},
                    { "PurTypeID", dto.PurTypeID},
                    { "HandleStateCode", dto.HandleStateCode},
                    { "StartDate", dto.StartDate},
                    { "EndDate", dto.EndDate},
                    {"StrFromType",strFromType },
                    { "CurrentPage", 1},
                    { "PageSize", 500 },
                };
            var strUrl = _sharingConfigurationManager.GetZiGongConfig().TFTB.QueryOldList + "zg12345/OrderAccept.asmx/GetOrderByListNew";
            var strResultData = e_SendHttpPostBySync(strUrl, dic);
            if (!string.IsNullOrEmpty(strResultData))
            {
                JObject job = (JObject)JsonConvert.DeserializeObject(strResultData);
                if (job != null && "1" == job["code"].ToString())
                {
                    if (!string.IsNullOrEmpty(job["dataInfo"].ToString()) && !string.IsNullOrEmpty(job["dataInfo"]["data"].ToString()))
                    {
                        listData = Newtonsoft.Json.JsonConvert.DeserializeObject<List<GetOrderMediaDataListDto>>(job["dataInfo"]["data"].ToString().ToString());
                    }
                }
            }

            var result = await _fwClient.RequestNoTokenAsync<HotlineClientDataSharingResponse<PagedDto<OrderDto>>>("api/v1/DataSharing/get_order_list_own",
                "Post", System.Text.Json.JsonSerializer.Serialize(orderList));
            int nPageCount = 0;
            if (result != null && result.code == 0)
            {
                if (result.result.Items != null && result.result.Items.Count > 0)
                {
                    //计算总页数
                    nPageCount = Convert.ToInt32(Math.Ceiling(Convert.ToDouble(result.result.Total) / dto.PageSize));
                    int rowID = 0;
                    foreach (var item in result.result.Items)
                    {
                        rowID++;
                        listData.Add(new GetOrderMediaDataListDto()
                        {
                            RowID = ((dto.CurrentPage - 1) * dto.PageSize) + rowID + "",
                            FlowID = item.Id,
                            Code = item.No,
                            Title = item.Title,
                            AddDate = item.CreationTime.ToString("yyyy-MM-dd HH:mm:ss"),
                            FromName = item.SourceChannel,
                            PurTypeName = item.AcceptType,
                            ResultState = item.Status >= EOrderStatus.Filed ? "办理完成" : "办理中"
                        });
                    }
                }
            }
            var list = listData.OrderByDescending(p => p.AddDate).ToList();
            int skip = dto.CurrentPage - 1;
            List<GetOrderMediaDataListDto> listDataReturn = [];
            listDataReturn = list.Skip(skip * dto.PageSize).Take(dto.PageSize).ToList();
            int rowIDNew = 0;
            foreach (var item in listDataReturn)
            {
                rowIDNew++;
                item.RowID = ((dto.CurrentPage - 1) * dto.PageSize) + rowIDNew + "";
            }
            nPageCount = Convert.ToInt32(Math.Ceiling(Convert.ToDouble(list.Count) / dto.PageSize));

            List<GetOrderMediaDataDto> returnData = new()
            {
            //处理返回
            new()
            {
                PageCount = nPageCount,
                data = listDataReturn
            } };

            return OpenResponse.Ok(ConvergenceMediaDeResponse<List<GetOrderMediaDataDto>>.Success(returnData, "成功"));

        }

        #endregion

        #region 2.3 工单查询

        /// <summary>
        /// 2.3 工单查询---1
        /// </summary>
        /// <returns></returns>
        [HttpPost("GetOrderDetail")]
        [AllowAnonymous]
        public async Task<OpenResponse> GetOrderDetail([FromBody] MediaOrderDetailReceiveDto dto)
        {
            //验证密钥
            var accountDto = await _dsUserTokenInfoService.CheckAccountAsync(dto.Code, HttpContext.RequestAborted);
            if (accountDto is null || accountDto.IsCheckAccount == false)
            {
                List<ConvergenceMediaDeResponse<string>> convergenceMediaDes = new() {
                new()
                {
                    msg = "密钥错误",
                    code = "-900",
                    data = ""
                } };

                return OpenResponse.Ok(ConvergenceMediaDeResponse<List<ConvergenceMediaDeResponse<string>>>.Failed(convergenceMediaDes, "0", "失败"));
            }

            //验证数据
            string strResult = dto.Validate();
            if (!string.IsNullOrEmpty(strResult))
                return OpenResponse.Ok(ConvergenceMediaDeResponse<List<ReturnData>>.Failed(ReturnData.ReturnDataInfo(strResult), "0", "失败"));
            if (dto.AcceptCode.Length == 12)
            {
                Dictionary<string, object> dic = new Dictionary<string, object>
                {
                    { "AcceptCode", dto.AcceptCode },
                    { "AcceptPwd", dto.AcceptPwd }
                };
                var strUrl = _sharingConfigurationManager.GetZiGongConfig().TFTB.QueryOldList + "zg12345/OrderAccept.asmx/GetOrderDetailNew";
                var strResultData = e_SendHttpPostBySync(strUrl, dic);
                if (!string.IsNullOrEmpty(strResultData))
                {
                    JObject job = (JObject)JsonConvert.DeserializeObject(strResultData);
                    if (job != null && "1" == job["code"].ToString())
                    {
                        var recData = Newtonsoft.Json.JsonConvert.DeserializeObject<MediaOrderDetailDataDto>(job["dataInfo"].ToString());
                        List<MediaOrderDetailDataDto> items = new() { recData };
                        return OpenResponse.Ok(ConvergenceMediaDeResponse<IReadOnlyList<MediaOrderDetailDataDto>>.Success(items, "成功"));
                    }
                }

                return OpenResponse.Ok(ConvergenceMediaDeResponse<List<ReturnData>>.Failed(ReturnData.ReturnDataInfo("查询失败！"), "0", "失败"));
            }
            else
            {
                GetOrderNoPwdDto getOrder = new()
                {
                    No = dto.AcceptCode,
                    Password = dto.AcceptPwd,
                    // SourceChannelCode = GetChannelCode(accountDto.PlatformSource)
                };
                var result = await _fwClient.RequestNoTokenAsync<HotlineClientDataSharingResponse<OrderDto>>("api/v1/DataSharing/get_order_detail_by_no_pwd",
                    "Post", System.Text.Json.JsonSerializer.Serialize(getOrder));
                List<MediaOrderDetailDataDto> items = new();
                if (result != null && result.code == 0)
                {
                    if (result.result != null)
                    {
                        var item = result.result;
                        items.Add(new()
                        {
                            FlowID = item.Id,
                            FlowCode = item.No,
                            FlowTitle = item.Title,
                            FlowFromName = item.SourceChannel,
                            FlowPurTypeName = item.AcceptType,
                            FlowConTypeName = item.HotspotName,
                            FlowAddDate = item.CreationTime.ToString("yyyy-MM-dd HH:mm:ss"),
                            FlowLKName = item.FromName,
                            FlowBMName = item.ActualHandleOrgName,
                            FlowRSFlagName = item.Status >= EOrderStatus.Filed ? "办理完成" : "办理中",
                            FlowContent = item.Content,
                            FlowResult = item.ActualOpinion,
                            OrderFiles = GetOrderFiles(item.FileJson),
                        });
                    }
                }
                if (items == null || items.Count == 0)
                    return OpenResponse.Ok(ConvergenceMediaDeResponse<List<ReturnData>>.Failed(ReturnData.ReturnDataInfo("编号、密码错误！"), "0", "失败"));
                else
                    return OpenResponse.Ok(ConvergenceMediaDeResponse<IReadOnlyList<MediaOrderDetailDataDto>>.Success(items, "成功"));
            }
        }

        #endregion

        #region 2.4 今日受理分类统计

        /// <summary>
        /// 2.4 今日受理分类统计---1
        /// </summary>
        /// <param name="Code"></param>
        /// <returns></returns>
        [HttpPost("GetPurTypeReport")]
        [AllowAnonymous]
        public async Task<OpenResponse> GetPurTypeReport([FromBody] MediaOrderReportReceiveDto dto)
        {
            //验证密钥
            var accountDto = await _dsUserTokenInfoService.CheckAccountAsync(dto.Code, HttpContext.RequestAborted);
            if (accountDto is null || accountDto.IsCheckAccount == false)
            {
                List<ConvergenceMediaDeResponse<string>> convergenceMediaDes = new() {
                new()
                {
                    msg = "密钥错误",
                    code = "-900",
                    data = ""
                } };

                return OpenResponse.Ok(ConvergenceMediaDeResponse<List<ConvergenceMediaDeResponse<string>>>.Failed(convergenceMediaDes, "0", "失败"));
            }

            var result = await _fwClient.RequestNoTokenAsync<HotlineClientDataSharingResponse<List<GetPurTypeReportDataDto>>>("api/v1/DataSharing/get_pur_type_report",
               "Post", "");
            List<GetPurTypeReportDataDto> data = new List<GetPurTypeReportDataDto>();
            if (result != null && result.code == 0)
            {
                if (result.result != null)
                {
                    data = _mapper.Map<List<GetPurTypeReportDataDto>>(result.result);
                }
            }

            return OpenResponse.Ok(ConvergenceMediaDeResponse<List<GetPurTypeReportDataDto>>.Success(data, "成功"));
        }

        #endregion

        #region 2.5 答复公开

        /// <summary>
        /// 2.5 答复公开---1
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost("GetOrderByListOpen")]
        [AllowAnonymous]
        public async Task<OpenResponse> GetOrderByListOpen([FromBody] GetOrderMediaReceiveOpenDto dto)
        {
            //密钥验证
            var accountDto = await _dsUserTokenInfoService.CheckAccountAsync(dto.Code, HttpContext.RequestAborted);
            if (accountDto is null || accountDto.IsCheckAccount == false)
            {
                List<ConvergenceMediaDeResponse<string>> convergenceMediaDes = new() {
                new()
                {
                    msg = "密钥错误",
                    code = "-900",
                    data = ""
                } };

                return OpenResponse.Ok(ConvergenceMediaDeResponse<List<ConvergenceMediaDeResponse<string>>>.Failed(convergenceMediaDes, "0", "失败"));
            }

            //数据处理
            string acceptTypeCode = dto.PurTypeID switch
            {
                "17" => "10",
                "18" => "30",
                "19" => "35",
                "20" => "20",
                "21" => "15",
                "25" => "40",
                _ => "",
            };
            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()
            {
                Title = dto.Title,
                AcceptTypeCode = acceptTypeCode,
                StartTime = string.IsNullOrEmpty(dto.StartDate) == true ? null : Convert.ToDateTime(dto.StartDate),
                EndTime = string.IsNullOrEmpty(dto.EndDate) == true ? null : Convert.ToDateTime(dto.EndDate).AddDays(1),
                PageIndex = pageIndex,
                PageSize = pageSize,
            };

            List<GetOrderMediaDataListDto> listData = [];

            //查询新系统
            var result = await _fwClient.RequestNoTokenAsync<HotlineClientDataSharingResponse<PagedDto<PublishOrderAllDto>>>("api/v1/DataSharing/get_order_list_publish_all",
               "Post", System.Text.Json.JsonSerializer.Serialize(getOrder));
            int nPageCount = 0;

            if (result != null && result.code == 0)
            {
                if (result.result.Items != null && result.result.Items.Count > 0)
                {
                    //计算总页数
                    nPageCount = Convert.ToInt32(Math.Ceiling(Convert.ToDouble(result.result.Total) / pageSize));
                    int rowID = 0;
                    foreach (var item in result.result.Items)
                    {
                        rowID++;
                        listData.Add(new GetOrderMediaDataListDto()
                        {
                            RowID = ((pageIndex - 1) * pageSize) + rowID + "",
                            FlowID = item.OrderId,
                            Code = item.OrderNo,
                            Title = item.Title,
                            AddDate = item.AcceptTime.Value.ToString("yyyy-MM-dd HH:mm:ss"),
                            FromName = item.SourceChannel,
                            PurTypeName = item.AcceptType,
                            ResultState = item.State,
                            PubDate = item.PubDate.HasValue == true ? item.PubDate.Value.ToString("yyyy-MM-dd HH:mm:ss") : ""
                        });
                    }
                }
            }

            List<GetOrderMediaDataDto> dataDto = new()
            {
            //处理返回
            new()
            {
                PageCount = nPageCount,
                data = listData
            } };

            return OpenResponse.Ok(ConvergenceMediaDeResponse<List<GetOrderMediaDataDto>>.Success(dataDto, "成功"));
        }

        #endregion

        #region 2.6 办理明细

        /// <summary>
        /// 2.6 办理明细
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost("GetOrderByRun")]
        [AllowAnonymous]
        public async Task<OpenResponse> GetOrderByRun([FromBody] MediaOrderDetailReceiveDto dto)
        {
            //密钥验证
            var accountDto = await _dsUserTokenInfoService.CheckAccountAsync(dto.Code, HttpContext.RequestAborted);
            if (accountDto is null || accountDto.IsCheckAccount == false)
            {
                List<ConvergenceMediaDeResponse<string>> convergenceMediaDes = new() {
                new()
                {
                    msg = "密钥错误",
                    code = "-900",
                    data = ""
                } };

                return OpenResponse.Ok(ConvergenceMediaDeResponse<List<ConvergenceMediaDeResponse<string>>>.Failed(convergenceMediaDes, "0", "失败"));
            }

            //验证数据
            string strResult = dto.Validate();
            if (!string.IsNullOrEmpty(strResult))
                return OpenResponse.Ok(ConvergenceMediaDeResponse<List<ReturnData>>.Failed(ReturnData.ReturnDataInfo(strResult), "0", "失败"));

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

            List<GetOrderByRunDataDto> orderByRunData = new();
            if (result != null && result.code == 0)
            {
                if (result.result != null && result.result.Count > 0)
                {
                    foreach (var item in result.result)
                    {
                        orderByRunData.Add(new GetOrderByRunDataDto()
                        {
                            BMName = item.HandlerOrgName,
                            TTime = item.StepExpiredTime.HasValue == true ? item.StepExpiredTime.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                            DisposeDate = item.HandleTime.HasValue == true ? item.HandleTime.Value.ToString("yyyy-MM-dd HH:mm:ss") : ""
                        });
                    }
                }
            }

            return OpenResponse.Ok(ConvergenceMediaDeResponse<IReadOnlyList<GetOrderByRunDataDto>>.Success(orderByRunData, "成功"));
        }

        #endregion

        #region 私有方法-将文件转化为文件流

        /// <summary>
        /// 组装附件参数
        /// </summary>
        /// <param name="fileJson"></param>
        /// <returns></returns>
        private List<GetFiles> GetOrderFiles(List<FileJson> fileJson)
        {
            var businessFile = _channelConfigurationManager.GetConfigurationBusinessFile();
            var baseUrl = businessFile.BaseUrl.Remove(businessFile.BaseUrl.Length - 1);
            List<GetFiles> getFiles = [];
            if (fileJson != null && fileJson.Count > 0)
            {
                foreach (var item in fileJson)
                {
                    GetFiles files = new()
                    {
                        FileID = item.FileId,
                        FileName = item.FileName + "." + item.FileType,
                        FileContent = baseUrl + item.Path
                    };
                    getFiles.Add(files);
                }
            }
            return getFiles;
        }

        private string GetChannelCode(string platformSource)
        {
            var sourceChannelCode = "";
            switch (platformSource)
            {
                case "ZGTFTB":
                    sourceChannelCode = "TFTB001";
                    break;
                case "ZGGC":
                    sourceChannelCode = "observe";
                    break;
                default:
                    break;
            }
            return sourceChannelCode;
        }

        /// <summary>
        /// 将文件流上传到附件服务器    
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        private async Task<BusinessFileDto> SendFileData(IFormFile file)
        {
            var businessFile = _channelConfigurationManager.GetConfigurationBusinessFile();
            // 文件名称
            string fileName = file.FileName;

            // 文件内容字节数据
            using var memoryStream = new MemoryStream();
            await file.CopyToAsync(memoryStream);
            memoryStream.Seek(0, SeekOrigin.Begin);
            byte[] fileContentBytes = memoryStream.ToArray();

            // 构造字典文件数据
            // 接口参数名称为files
            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)
                {
                    return resultData.result;
                }
            }
            return new BusinessFileDto();
        }

        /// <summary>
        /// POST 提交数据
        /// </summary>
        /// <param name="strUrl"> 地址</param>
        /// <param name="headers">参数</param>
        /// <param name="strEncoding"></param>
        /// <param name="strContentType"></param>
        /// <returns></returns>
        private string e_SendHttpPostBySync(string strUrl, Dictionary<string, object> headers = null, string strEncoding = "UTF-8",
            string strContentType = "application/x-www-form-urlencoded")
        {
            // 返回数据
            string strResult = "";

            try
            {
                ServicePointManager.Expect100Continue = false;
                string postDataStr = SerializeDictionaryToParam2(headers);
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(strUrl);
                request.Method = "POST";
                request.ContentType = strContentType;
                request.ContentLength = postDataStr.Length;

                StreamWriter write = new StreamWriter(request.GetRequestStream(), Encoding.ASCII);
                write.Write(postDataStr);
                write.Flush();
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                string encoding = "UTF-8";
                StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding(encoding));
                strResult = reader.ReadToEnd();
            }
            catch (Exception ex)
            {
                strResult = "";
            }
            finally
            {
            }
            return strResult;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <typeparam name="TKey"></typeparam>
        /// <typeparam name="TValue"></typeparam>
        /// <param name="dict"></param>
        /// <returns></returns>
        private string SerializeDictionaryToParam2<TKey, TValue>(Dictionary<TKey, TValue> dict)
        {
            string strParam = "";
            int nIndex = 0;
            foreach (var item in dict)
            {
                if (0 == nIndex)
                    strParam += item.Key + "=" + item.Value;
                else
                    strParam += "&" + item.Key + "=" + item.Value;
                nIndex++;
            }
            return strParam;
        }
        #endregion
    }
}
