using Fw.Utility.UnifyResponse;
using Hotline.Ai.CallOut;
using Hotline.Ai.Jths.OrderVisits;
using Hotline.Ai.Visit;
using Hotline.Share.Dtos.Order;
using Hotline.Share.Enums.Order;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using RestSharp;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Hotline.Ai.Jths
{
    public class AiVisitService : IAiVisitService
    {
        private readonly RestClient _client;
        private readonly string _baseUrl;
        private readonly string _appkey;
        private readonly string _serviceversion;

        public AiVisitService(string baseUrl, string appkey, string serviceversion)
        {
            _baseUrl = baseUrl;
            _appkey = appkey;
            _serviceversion = serviceversion;
            var options = new RestClientOptions(_baseUrl);
            _client = new RestClient(options);
        }

        public async Task<bool> ChangeStatusAsync(string batchUid, string status, CancellationToken cancellationToken)
        {
            string posturl = _baseUrl + "/edas/task/status/" + status + "?batchUid=" + batchUid;
            var requestData = new AiVisitServiceRequest(){ };
            var response = await ExecuteAsync<AiVisitServiceRequest, AiVisitServiceResponse>(posturl, Method.Post, requestData, cancellationToken);
            if (response.Code== 10000)
            {
                return true;
            }
            return false;
        }

        public async Task<CallOutTask> CreateAiCallOutTask(CallOutTask callOutTask, string sceneuid, string ruleuId, string callOutContentKey, CancellationToken cancellationToken)
        {
            string content = callOutTask.CallOutTemplate.TemplateContent;
            var requestData = new AiVisitServiceRequest()
            {
                BatchName = callOutTask.TaskName,
                BatchStatus = 1,
                SceneUid = sceneuid,
                Priority = 1,
                StartDate = callOutTask.BeginTime.ToString("yyyy/MM/dd HH:mm:ss"),
                EndDate = callOutTask.EndTime.ToString("yyyy/MM/dd HH:mm:ss"),
                FestivalBan = callOutTask.FestivalBan,
                RuleType = 2,
                RuleUid = ruleuId,
            };
            var taskDataList = new List<TaskData>();
            foreach (var item in callOutTask.CallOutTaskDetails)
            {
                var taskData = new TaskData();
                taskData.CalledNumber = item.OuterNo;
                taskData.VariableList = new List<Variable>();
                taskData.VariableList.Add(new Variable() { Code = callOutContentKey, Value = content });
                taskDataList.Add(taskData);
            }
            requestData.TaskDataList = taskDataList;
            var response = await ExecuteAsync<AiVisitServiceRequest, AiVisitServiceResponse>(_baseUrl + "/edas/batchTask", Method.Post, requestData, cancellationToken);
            if (response.Result != null && response.Result.TaskInfoList != null && !string.IsNullOrEmpty(response.Result.BatchUid))
            {
                //拼对象
                callOutTask.BatchUid = response.Result.BatchUid;
                for (int i = 0; i < callOutTask.CallOutTaskDetails.Count; i++)
                {
                    var taskInfo = response.Result.TaskInfoList.FirstOrDefault(x => x.CalledNumber == callOutTask.CallOutTaskDetails[i].OuterNo);
                    if (taskInfo != null && !string.IsNullOrEmpty(taskInfo.TaskUid))
                    {
                        callOutTask.CallOutTaskDetails[i].AiCallOutState =  Share.Enums.Ai.EAiCallOutState.NoStarted;
                        callOutTask.CallOutTaskDetails[i].TaskUid = taskInfo.TaskUid;
                    }
                    else
                    {
                        callOutTask.CallOutTaskDetails[i].AiCallOutState = Share.Enums.Ai.EAiCallOutState.LoseEfficacy;
                    }
                }
            }
            return callOutTask;
        }


        public async Task<AiOrderVisit> CreateAiOrderVisitTask(AiOrderVisit aiOrderVisit,string sceneuid,string ruleuId,string visitFromNameKey,string visitFromGenderKey,string visitCreationTimeKey,string visitOrderTitleKey,string visitIsCallOrderKey, CancellationToken cancellationToken)
        {

            var requestData = new AiVisitServiceRequest()
            {
                BatchName = aiOrderVisit.Name,
                BatchStatus = 1,
                SceneUid = sceneuid,
                Priority = 1,
                StartDate = aiOrderVisit.BeginTime.ToString("yyyy/MM/dd HH:mm:ss"),
                EndDate = aiOrderVisit.EndTime.ToString("yyyy/MM/dd HH:mm:ss"),
                FestivalBan = aiOrderVisit.FestivalBan,
                RuleType = aiOrderVisit.RuleType,
                RuleUid = ruleuId,
            };
            var taskDataList = new List<TaskData>();
            foreach (var item in aiOrderVisit.AiOrderVisitDetails)
            {
                var taskData = new TaskData();
                taskData.CalledNumber = item.OuterNo;
                taskData.VariableList = new List<Variable>();
               
               
                //if (!string.IsNullOrEmpty(item.Order.FromName))
                //{
                //    //来电名称
                //    //开发环境 :OC_SCENE_VAR_FIELD11
                //    //生产环境：OC_SCENE_VAR_FIELD12
                //    taskData.VariableList.Add(new Variable() { Code = visitFromNameKey, Value = item.Order.FromName });
                //}
                //else
                //{
                //    //来电名称
                //    //开发环境 :OC_SCENE_VAR_FIELD11
                //    //生产环境：OC_SCENE_VAR_FIELD12
                //    taskData.VariableList.Add(new Variable() { Code = visitFromNameKey, Value = "市民" });
                //}
                ////来电性别
                ////开发环境: OC_SCENE_VAR_FIELD14
                ////生产环境：OC_SCENE_VAR_FIELD14
                //taskData.VariableList.Add(new Variable() { Code = visitFromGenderKey, Value = item.Order.FromGender == EGender.Female ? "女士" : "先生" });
                //来电时间
                //开发环境:OC_SCENE_VAR_FIELD17
                //生产环境：OC_SCENE_VAR_FIELD19
                taskData.VariableList.Add(new Variable() { Code = visitCreationTimeKey, Value = item.Order.CreationTime.ToString("yyyy年MM月dd日hh点mm分") });
                //工单标题
                //开发环境:OC_SCENE_VAR_FIELD18
                //生产环境：OC_SCENE_VAR_FIELD20
                taskData.VariableList.Add(new Variable() { Code = visitOrderTitleKey, Value = item.Order.Title });

                ////是否来电工单
                ////开发环境：
                ////生产环境：
                //taskData.VariableList.Add(new Variable() { Code = visitIsCallOrderKey, Value = item.Order.SourceChannelCode == "RGDH" ? "income" : "outbound" });
                taskDataList.Add(taskData);
            }
            requestData.TaskDataList = taskDataList;
            var response = await ExecuteAsync<AiVisitServiceRequest, AiVisitServiceResponse>(_baseUrl + "/edas/batchTask",Method.Post, requestData,cancellationToken);
            if (response.Result!=null && response.Result.TaskInfoList!=null && !string.IsNullOrEmpty(response.Result.BatchUid))
            {
                //拼对象
                aiOrderVisit.BatchUid = response.Result.BatchUid;
                for (int i = 0; i < aiOrderVisit.AiOrderVisitDetails.Count; i++)
                {
                    var taskInfo = response.Result.TaskInfoList.FirstOrDefault(x => x.CalledNumber == aiOrderVisit.AiOrderVisitDetails[i].OuterNo);
                    if (taskInfo != null && !string.IsNullOrEmpty(taskInfo.TaskUid))
                    {
                        aiOrderVisit.AiOrderVisitDetails[i].AiOrderVisitState = Share.Enums.Ai.EAiOrderVisitState.NoStarted;
                        aiOrderVisit.AiOrderVisitDetails[i].TaskUid = taskInfo.TaskUid;
                    }
                    else
                    {
                        aiOrderVisit.AiOrderVisitDetails[i].AiOrderVisitState = Share.Enums.Ai.EAiOrderVisitState.LoseEfficacy;
                    }
                }
            }
            return aiOrderVisit;
        }


        public async Task<AiVisitQueryData> QueryAiVisitTask(string batchId, string taskId, CancellationToken cancellationToken)
        {
            var dto = new AiVisitServiceQueryRequest() { BatchUid = batchId, TaskUid = taskId,PageNo=1, PageSize=100 };
            var response = await ExecuteAsync<AiVisitServiceQueryRequest, AiVisitServiceQueryResponse>(_baseUrl + "/edas/task/status/real", Method.Get, dto, cancellationToken);
            if (response!=null && response.Result!=null && response.Result.Result.Count>0)
            {
                return new AiVisitQueryData() { Uid = response.Result.Result[0].Uid, Status = response.Result.Result[0].Status };
            }
            return null;
        }

        public async Task<AiVisitQueryData> QueryAiVisitTaskEx(string batchId, string taskId, CancellationToken cancellationToken)
        {
            var dto = new AiVisitServiceQueryRequest() { BatchUid = batchId, TaskUid = taskId, PageNo = 1, PageSize = 100 };
            var response = await ExecuteAsync<AiVisitServiceQueryRequest, AiVisitServiceQueryResponse>(_baseUrl + "/edas/task/status/history", Method.Get, dto, cancellationToken);
            if (response != null && response.Result != null && response.Result.Result.Count > 0)
            {
                return new AiVisitQueryData() { Uid = response.Result.Result[0].Uid, Status = response.Result.Result[0].Status };
            }
            return null;
        }

        public async Task<AiVisitQueryData> QueryAiVisitTaskResult(string batchId,DateTime beginTime,DateTime endTime,CancellationToken cancellationToken)
        {
            var dto = new AiVisitServiceQueryResultRequest { StartTime = beginTime, EndTime = endTime, BatchUid = batchId };
            var response = await ExecuteAsync<AiVisitServiceQueryResultRequest, AiVisitServiceQueryResultResponse>(_baseUrl + "/edas/task/result", Method.Get, dto, cancellationToken) ;
            return new AiVisitQueryData() {  };
        }


        public async Task<TResponse> ExecuteAsync<TRequest,TResponse>(string path, Method httpMethod, TRequest request,
            CancellationToken cancellationToken)
            where TRequest : class
        {
            var req = new RestRequest(path, httpMethod);
            req.AddHeader("content-type", "application/json");
            req.AddHeader("token", "");
            req.AddHeader("version", _serviceversion);
            req.AddHeader("appkey", _appkey);
            if (httpMethod is Method.Get)
            {
                req.AddObject(request);
            }
            else
            {
                req.AddJsonBody(request);
            }
            try
            {
                var response = await _client.ExecuteAsync<TResponse>(req, cancellationToken);
                return response.Data;
            }
            catch (Exception e)
            {
                throw new HttpRequestException($"智能回访平台错误，Error: {e.Message}");
            }
        }
    }
}
