using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using CallCenterApi.IRepositories;
using MadRunFabric.Common;
using MadRunFabric.Model.CallCenterApi;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using MongoDB.Bson;
using MongoDB.Driver;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace CallCenterApi.Controllers.systemmanagement
{
    [ApiVersion("6.0")]
    [Produces("application/json")]
    [Route("api/[controller]")]
    public class SysIVRConfigController : BaseController
    {
        private readonly ILogger<SysIVRConfigController> _logger;
        private readonly ISys_SystemConfigRepository _sys_systemconfigRepository;
        private readonly ISys_IVRConfigsRepository _sys_ivrconfigsRepository;
        private readonly ISys_IVRConfigsLogRepository _sys_ivrconfigslogRepository;
        public SysIVRConfigController(ILogger<SysIVRConfigController> logger, 
            ISys_SystemConfigRepository sys_systemconfigRepository,
            ISys_IVRConfigsRepository sys_ivrconfigsRepository,
            ISys_IVRConfigsLogRepository sys_ivrconfigslogRepository)
        {
            _logger = logger;
            _sys_systemconfigRepository = sys_systemconfigRepository;
            _sys_ivrconfigsRepository = sys_ivrconfigsRepository;
            _sys_ivrconfigslogRepository = sys_ivrconfigslogRepository;
        }
        #region 存库
        /// <summary>
        /// 获取IVR配置列表
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        [Authorize]
        [HttpGet("getlistbypage")]
        public IActionResult GetListsByPageAsync(string groupcode, string stime, string etime, int pageindex = 1, int pagesize = 10)
        {
            int recordCount = 0;
            var result = _sys_ivrconfigsRepository.GetListsByPage(groupcode, stime, etime, pageindex, pagesize, out recordCount);
            var list = result.ToList();
            var obj = new
            {
                rows = list,
                total = recordCount,
            };
            return Success("获取成功", obj);
        }

        /// <summary>
        /// 获取实体
        /// </summary>
        [Authorize]
        [HttpGet("getsingle")]
        public IActionResult GetSingleAsync(string id)
        {
            if (id != null && id.Trim() != "")
            {
                var dModel = _sys_ivrconfigsRepository.GetDetails(id.Trim());

                if (dModel != null)
                {
                    return Success("获取IVR配置成功", dModel);
                }
                else
                {
                    return Error("获取IVR配置失败");
                }
            }
            else
            {
                return Error("获取参数失败");
            }

        }

        /// <summary>
        /// 添加IVR配置
        /// </summary>
        [Authorize]
        [HttpPost("add")]
        public async Task<IActionResult> AddAsync(string groupcode, int ivrtype, string ivrcontent, int isenable = 1)
        {
            try
            {
                #region 已有坐席组的同一类型IVR不能添加
                var ss = await _sys_ivrconfigsRepository.Get(s => s.isdelete == false && s.groupcode.Equals(groupcode) && s.ivrtype == ivrtype);
                if (ss.Count() > 0)
                { return Error("此坐席组已有同一类型IVR,不能重复添加"); }
                #endregion
                Sys_IVRConfigs clmodel = new Sys_IVRConfigs();
                var res = false;
                clmodel.id= ObjectId.GenerateNewId().ToString();
                var ivrname = groupcode;
                clmodel.groupcode = groupcode;
                clmodel.ivrcontent = ivrcontent;
                clmodel.isenable = isenable;
                clmodel.ivrtype = ivrtype;
                if (string.IsNullOrWhiteSpace(groupcode))
                    ivrname = "Nomal";
                if (ivrtype == (int)enumivrtype.myd)
                {
                    clmodel.ivrname = "MYD_" + ivrname;
                }
                else if (ivrtype == (int)enumivrtype.autocall)
                {
                    clmodel.ivrname = "Auto_" + ivrname;
                }
                else
                {
                    clmodel.ivrname = "IVR_" + ivrname;
                    clmodel.isenable = (int)enumivrenable.enable;
                }
                clmodel.createby = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value; //"8000";
                clmodel.createtime = DateTime.Now.ToLocalTime();
                clmodel.isdelete = false;

                res = await _sys_ivrconfigsRepository.Add(clmodel);
                if (res)
                {
                    if (clmodel.isenable == (int)enumivrenable.enable)
                        await editivrAsync(clmodel.ivrcontent, (int)enumconfigtype.save);
                    addlogs(clmodel, "add");
                    return Success("IVR配置保存成功");
                }
                else
                {
                    return Error("IVR配置保存失败");
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "IVR配置保存异常");
                return Error("IVR配置保存失败");
            }
        }

        /// <summary>
        /// 修改IVR配置
        /// </summary>
        [Authorize]
        [HttpPost("update")]
        public async Task<IActionResult> EditAsync(string id, string ivrcontent, int isenable = 1)
        {
            var res = false;
            if (id != null && id.Trim() != "")
            {
                try
                {
                    var clmodel = await _sys_ivrconfigsRepository.GetSingle(id);
                    if (clmodel != null)
                    {
                        clmodel.ivrcontent = ivrcontent;
                        clmodel.isenable = isenable;
                        res = _sys_ivrconfigsRepository.UpdateOne(clmodel).Result;
                        if (res)
                        {
                            if (clmodel.isenable == (int)enumivrenable.enable)
                                await editivrAsync(clmodel.ivrcontent,(int)enumconfigtype.save);
                            addlogs(clmodel, "update");
                        }
                    }
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, "IVR配置保存异常");
                    return Error("IVR配置保存失败");
                }
            }
            if (res)
                return Success("IVR配置保存成功");
            else
            {
                return Error("IVR配置保存失败");
            }
        }

        /// <summary>
        /// 启动/停用ivr
        /// </summary>
        /// <param name="id"></param>
        /// <param name="isenable"></param>
        /// <returns></returns>
        [Authorize]
        [HttpPost("enable")]
        public async Task<IActionResult> EnableAsync(string id, int isenable)
        {
            var res = false;
            if (id != null && id.Trim() != "")
            {
                try
                {
                    var clmodel = await _sys_ivrconfigsRepository.GetSingle(id);
                    if (clmodel != null)
                    {
                        if(string.IsNullOrWhiteSpace(clmodel.groupcode)&&isenable == (int)enumivrenable.unenable )
                            return Error("默认的IVR流程不能停用");
                        clmodel.isenable = isenable;
                        
                        res = await _sys_ivrconfigsRepository.UpdateOne(clmodel);
                        if (res)
                        {
                            if (clmodel.isenable == (int)enumivrenable.enable)
                                await editivrAsync(clmodel.ivrcontent, (int)enumconfigtype.save);
                            if (clmodel.isenable == (int)enumivrenable.unenable)
                                await editivrAsync(clmodel.ivrcontent, (int)enumconfigtype.del);
                            addlogs(clmodel, "enable");
                        }
                    }
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, "IVR配置保存异常");
                    return Error("IVR配置保存失败");
                }
            }
            if (res)
                return Success("IVR配置保存成功");
            else
            {
                return Error("IVR配置保存失败");
            }
        }

        [Authorize]
        [HttpPost("delete")]
        public async Task<IActionResult> RemoveAsync(string[] ids)
        {
            //使用逻辑删除
            //物理删除的数据无法恢复
            var res = 0;
            if (ids != null && ids.Length > 0)
            {
                try
                {
                    foreach (var item in ids)
                    {
                        var ml = await _sys_ivrconfigsRepository.GetSingle(item);
                        ml.isdelete = true;
                        if (await _sys_ivrconfigsRepository.Update(ml))
                        {
                            await editivrAsync(ml.ivrcontent, (int)enumconfigtype.del);
                            addlogs(ml, "del");
                            res += 1;
                        }
                    }
                    if (res == ids.Length)
                        return Success("删除成功");
                    else if (res > 0 && res < ids.Length)
                        return Error("部分删除失败，请查看后重新操作");
                    else
                        return Error("删除失败，请查看后重新操作");
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, "IVR配置删除异常");
                    return Error("IVR配置删除失败");
                }
            }
            else
                return Error("请选择要删除的记录");
        }

        #region 记录操作日志
        private void addlogs(Sys_IVRConfigs ivrmodel,string opt)
        {
            var model = new Sys_IVRConfigsLog();
            model.ivrid = ivrmodel.id;
            model.groupcode = ivrmodel.groupcode;
            model.ivrcontent = ivrmodel.ivrcontent;
            model.isenable = ivrmodel.isenable;
            model.ivrtype = ivrmodel.ivrtype;
            model.ivrname = ivrmodel.ivrname;
            model.optby = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
            model.opttime = DateTime.Now;
            model.opttype = opt;
            _sys_ivrconfigslogRepository.Add(model);
        }
        #endregion
        #endregion
        #region 不存库
        [HttpGet("loadivrlist")]
        public async Task<IActionResult> LoadIVRListAsync()
        {
            string url = await gethttpipAsync();
            var m = new
            {
                type = 2,
            };
            //实体序列化和反序列化
            string json1 = JsonConvert.SerializeObject(m);
            string strHTML = MadRunFabric.Common.HttpMethods.HttpPost(url, json1);
            JObject jo1 = (JObject)JsonConvert.DeserializeObject(strHTML);
            
            if (jo1 != null && jo1["state"].ToString() == "success")
            {
                var constr = jo1["data"].ToArray();
                return Success("读取IVR列表", constr);
            }
            return Error("读取IVR列表");
        }

        [HttpGet("loadivr")]
        public async Task<IActionResult> LoadIVRAsync(string ivrname= "Ivr4SLWY")
        {
            string url = await gethttpipAsync();
            var m = new
            {
                type = 1,
                data = ivrname
            };
            //实体序列化和反序列化
            string json1 = JsonConvert.SerializeObject(m);
            string strHTML = MadRunFabric.Common.HttpMethods.HttpPost(url, json1);
            JObject jo1 = (JObject)JsonConvert.DeserializeObject(strHTML);
            var constr = "";
            if (jo1 != null && jo1["state"].ToString() == "success")
            {
                var data = jo1["data"];

                constr = ConvertHelper.GetStringFromBase64String(data.ToString(), Encoding.Default);
            }
            return Success("读取IVR", constr);
        }

        [HttpPost("editivr")]
        public async Task<IActionResult> EditIVRAsync(string ivrcontent)
        {
            string url = await gethttpipAsync();
            var ivrdata = ConvertHelper.GetBase64String(ivrcontent, Encoding.Default);
            var m = new
            {
                type = 10,
                data = ivrdata
            };
            //实体序列化和反序列化
            string json1 = JsonConvert.SerializeObject(m);
            string strHTML = MadRunFabric.Common.HttpMethods.HttpPost(url, json1);
            JObject jo1 = (JObject)JsonConvert.DeserializeObject(strHTML);
            if (jo1 != null)
            {
                if (jo1["state"].ToString() == "success")
                    return Success("编辑IVR成功");
                else
                {
                    var data = jo1["message"].ToString();
                    return Error("编辑IVR失败,失败原因：" + data);
                }
            }
            else
            {
                return Error("编辑失败，请稍后重试");
            }
        }
        #endregion
        #region 私有方法
        /// <summary>
        /// 编辑ivr
        /// </summary>
        /// <param name="ivrcontent"></param>
        /// <returns></returns>
        private async Task<bool> editivrAsync(string ivrcontent,int type)
        {
            string url = await gethttpipAsync();
            var ivrdata = ConvertHelper.GetBase64String(ivrcontent, Encoding.Default);
            var m = new
            {
                type = type,
                data = ivrdata
            };
            //实体序列化和反序列化
            string json1 = JsonConvert.SerializeObject(m);
            string strHTML = MadRunFabric.Common.HttpMethods.HttpPost(url, json1);
            JObject jo1 = (JObject)JsonConvert.DeserializeObject(strHTML);
            if (jo1 != null)
            {
                if (jo1["state"].ToString() == "success")
                    return true;
            }
            return false;
        }

        /// <summary>
        /// 获取ip地址
        /// </summary>
        /// <returns></returns>
        private async Task<string> gethttpipAsync()
        {
            var pModel = await _sys_systemconfigRepository.GetSingle(s => s.paramcode.Equals("IVRConfigURL") & s.isdelete == false, null);
            string strPURL = pModel != null ? pModel.paramvalue : "";
            return strPURL;
            #region
            //#region 获取路径
            //var pModel = await _sys_systemconfigRepository.GetSingle(s => s.paramcode.Equals("IVRConfigURL") & s.isdelete == false, null);
            ////var pModel = await _sys_systemconfigRepository.GetSingle(s => s.paramcode.Equals("ACDIP") & s.isdelete == false, null);
            //string strPURL = pModel != null ? pModel.paramvalue : "";
            //#endregion
            ////http://192.168.5.41:9003/v1/ivr/flow/mgr
            //string strPURL = "http://" + ip + ":9003/v1/ivr/flow/mgr";
            //return strPURL;
            #endregion
        }
        #endregion
    }
    /// <summary>
    /// IVR配置操作类型
    /// </summary>
    public enum enumconfigtype
    {
        /// <summary>
        /// 读取流程文本
        /// </summary>
        get = 1,
        /// <summary>
        /// 查询流程名子
        /// </summary>
        getname = 2,
        /// <summary>
        /// 保存流程
        /// </summary>
        save = 10,
        /// <summary>
        /// 删除流程
        /// </summary>
        del = 11
    }
}