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

namespace CallCenterApi.Controllers.systemmanagement
{
    /// <summary>
    /// IVR欢迎词控制器，存储IVR欢迎词的文本和需要替换的语音
    /// </summary>
    [ApiVersion("6.0")]
    [Produces("application/json")]
    [Route("api/[controller]")]
    public class SysIVRWordsController : BaseController
    {
        private readonly ILogger<SysIVRWordsController> _logger;
        private readonly ISys_IVRWordsRepository _sys_ivrwordsRepository;

        public SysIVRWordsController(ILogger<SysIVRWordsController> logger, ISys_IVRWordsRepository sys_ivrwordsRepository)
        {
            _logger = logger;
            _sys_ivrwordsRepository = sys_ivrwordsRepository;
        }

        [Authorize]
        [HttpGet("getlistbypage")]
        public async Task<IActionResult> GetListsByPage(string key,string state, string stime, string etime, int pageindex = 1, int pagesize = 10)
        {
            try
            {
                //排序字段
                var sort = Builders<Sys_IVRWords>.Sort.Descending("createtime");
                await upstateAsync();

                //根据条件查询集合
                var list = new List<FilterDefinition<Sys_IVRWords>>();
                var list1 = new List<FilterDefinition<Sys_IVRWords>>();
                var filterBuilder = Builders<Sys_IVRWords>.Filter;
                list.Add(filterBuilder.Eq("isdelete", false));

                if (!string.IsNullOrWhiteSpace(stime)|| !string.IsNullOrWhiteSpace(etime))
                {
                    if (!string.IsNullOrWhiteSpace(stime))
                    {
                        list1.Add(filterBuilder.Lte("startdate", stime) & filterBuilder.Gte("enddate", stime));
                    }
                    if (!string.IsNullOrWhiteSpace(etime))
                    {
                        list1.Add(filterBuilder.Lte("startdate", etime) & filterBuilder.Gte("enddate", etime));
                    }
                    list.Add(filterBuilder.Or(list1));
                }

                if (!string.IsNullOrWhiteSpace(state))
                {//状态：1启动，0不启动
                    list.Add(filterBuilder.Eq("isstate", state));
                }

                if (!string.IsNullOrWhiteSpace(key))
                {
                    list.Add(filterBuilder.Where(s => s.content.Contains(key) || s.title.Contains(key)));
                }
                
                    var filter = Builders<Sys_IVRWords>.Filter.And(list);
                    var ilist = await _sys_ivrwordsRepository.GetByPage(filter, pageindex, pagesize, sort);
                var count = await _sys_ivrwordsRepository.CountAsync(filter);
                //var obj = blacklist.Result;
                //foreach (var item in obj)
                //{
                //更新文件的路径 D:/改为http://ip/
                //}
                var obj = new
                {
                    state = "success",
                    message = "根据条件获取分页数据成功",
                    rows = ilist,
                    total = count,
                };
                return Content(obj.ToJson());
                //return Success("根据条件获取分页数据成功", ilist);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取IVR欢迎词分页数据异常");
                return Error("获取IVR欢迎词分页数据失败");
            }
        }

        /// <summary>
        /// 获取IVR欢迎词列表 - 分页 关联查询
        /// </summary>
        /// <param name="key"></param>
        /// <param name="state"></param>
        /// <param name="stime"></param>
        /// <param name="etime"></param>
        /// <param name="pageindex"></param>
        /// <param name="pagesize"></param>
        /// <returns></returns>
        [Authorize]
        [HttpGet("getlistsbypage")]
        public IActionResult GetListByPage(string key, string state, string stime, string etime, int pageindex = 1, int pagesize = 10)
        {
            try
            {
                int recordCount = 0;
                var result = _sys_ivrwordsRepository.GetListByPage(key, state, stime, etime, pageindex, pagesize, out recordCount);

                var obj = new
                {
                    rows = result,
                    total = recordCount,
                };
                return Success("获取成功", obj);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取IVR欢迎词分页数据异常");
                return Error("获取IVR欢迎词分页数据失败");
            }
        }

        [Authorize]
        [HttpGet("getsingle")]
        public async Task<IActionResult> GetSingle(string id)
        {
            if (id != null && id.Trim() != "")
            {
                try
                {
                    var dModel = await _sys_ivrwordsRepository.GetSingle(id.Trim());

                    #region 更新文件的路径 D:/改为http://ip/
                    //var config = new BLL.T_Sys_SystemConfig().GetModelList(" F_ParamCode='IVRWavPath' ").FirstOrDefault();

                    //if (dModel.F_WavNewName != "" && config != null && !string.IsNullOrEmpty(config.F_ParamValue))
                    //{
                    //    dModel.F_WavPath = config.F_ParamValue + dModel.F_WavNewName;
                    //}
                    #endregion
                    if (dModel != null)
                    {
                        return Success("获取IVR欢迎词成功", dModel);
                    }
                    else
                    {
                        return Error("获取IVR欢迎词失败");
                    }
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, "获取IVR欢迎词实体异常");
                    return Error("获取IVR欢迎词实体失败");
                }
            }
            else
            {
                return Error("获取参数失败");
            }

        }

        /// <summary>
        ///  获取详情 - 关联查询
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [Authorize]
        [HttpGet("getsingles")]
        public IActionResult GetInfo(string id)
        {
            if (id != null && id.Trim() != "")
            {
                try
                {
                    var dModel = _sys_ivrwordsRepository.GetDetails(id.Trim());

                    #region 更新文件的路径 D:/改为http://ip/
                    //var config = new BLL.T_Sys_SystemConfig().GetModelList(" F_ParamCode='IVRWavPath' ").FirstOrDefault();

                    //if (dModel.F_WavNewName != "" && config != null && !string.IsNullOrEmpty(config.F_ParamValue))
                    //{
                    //    dModel.F_WavPath = config.F_ParamValue + dModel.F_WavNewName;
                    //}
                    #endregion
                    if (dModel != null)
                    {
                        return Success("获取IVR欢迎词成功", dModel);
                    }
                    else
                    {
                        return Error("获取IVR欢迎词失败");
                    }
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, "获取IVR欢迎词实体异常");
                    return Error("获取IVR欢迎词实体失败");
                }
            }
            else
            {
                return Error("获取参数失败");
            }

        }

        [Authorize]
        [HttpPost("add")]
        public async Task<IActionResult> Add(string title, string content,
             string sdate, string edate, string remark, string groupcode,
            List<FileBaseModel> wavstr, int isstate = 0, int type=0)
        {
            try
            {
                Sys_IVRWords clmodel = new Sys_IVRWords();
                var res = false;
                int iss = await returnisaddAsync("", sdate, edate);
                if (iss <= 0)
                {
                    if (!string.IsNullOrWhiteSpace(title))
                        clmodel.title = title.Trim();
                    if (!string.IsNullOrWhiteSpace(groupcode))
                        clmodel.groupcode = groupcode.Trim();
                    if (!string.IsNullOrWhiteSpace(content))
                        clmodel.content = content.Trim();
                    if (!string.IsNullOrWhiteSpace(remark))
                        clmodel.remark = remark.Trim();
                    if (!string.IsNullOrWhiteSpace(sdate))
                    {
                        DateTime dt2 = new DateTime();
                        if (DateTime.TryParse(sdate.Trim(), out dt2))
                            clmodel.startdate = Convert.ToDateTime(dt2);
                    }
                    if (!string.IsNullOrWhiteSpace(edate))
                    {
                        DateTime dt2 = new DateTime();
                        if (DateTime.TryParse(edate.Trim(), out dt2))
                            clmodel.enddate = Convert.ToDateTime(dt2);
                    }
                    clmodel.wavfile = wavstr;
                    //if (!string.IsNullOrWhiteSpace(newname))
                    //    clmodel.wavnewname = newname.Trim();
                    //if (!string.IsNullOrWhiteSpace(oldname))
                    //    clmodel.wavoldname = oldname.Trim();
                    //if (!string.IsNullOrWhiteSpace(path))
                    //    clmodel.wavpath = path.Trim();
                    
                    clmodel.type = type;
                    clmodel.isstate = isstate;
                    clmodel.createby = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value; //"8000";
                    clmodel.createtime = DateTime.Now.ToLocalTime();
                    clmodel.isdelete = false;

                    res = await _sys_ivrwordsRepository.Add(clmodel);
                }
                if (res)
                    return Success("IVR欢迎词保存成功");
                else
                {
                    if (iss > 0)
                    {
                        return Error("存在已启动的IVR欢迎词在此有效期间，请查看记录后另外选择有效期！");
                    }
                    else
                    {
                        return Error("IVR欢迎词保存失败");
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "IVR欢迎词保存异常");
                return Error("IVR欢迎词保存失败");
            }
        }

        [Authorize]
        [HttpPost("update")]
        public async Task<IActionResult> Update(string id, string title, string content,
            string sdate, string edate, string remark, string groupcode,
            List<FileBaseModel> wavstr, int isstate = 0, int type = 0)
        {
            try
            {
                var res = false;
                int iss = await returnisaddAsync(id, sdate, edate);
                if (iss <= 0)
                {
                    if (id != null && id.Trim() != "")
                    {
                        var clmodel = await _sys_ivrwordsRepository.GetSingle(id);
                        if (clmodel != null)
                        {
                            if (!string.IsNullOrWhiteSpace(title))
                                clmodel.title = title.Trim();
                            if (!string.IsNullOrWhiteSpace(groupcode))
                                clmodel.groupcode = groupcode.Trim();
                            if (!string.IsNullOrWhiteSpace(title))
                                clmodel.title = title.Trim();
                            if (!string.IsNullOrWhiteSpace(content))
                                clmodel.content = content.Trim();
                            if (!string.IsNullOrWhiteSpace(remark))
                                clmodel.remark = remark.Trim();
                            if (!string.IsNullOrWhiteSpace(sdate))
                            {
                                DateTime dt2 = new DateTime();
                                if (DateTime.TryParse(sdate.Trim(), out dt2))
                                    clmodel.startdate = Convert.ToDateTime(dt2);
                            }
                            if (!string.IsNullOrWhiteSpace(edate))
                            {
                                DateTime dt2 = new DateTime();
                                if (DateTime.TryParse(edate.Trim(), out dt2))
                                    clmodel.enddate = Convert.ToDateTime(dt2);
                            }

                            clmodel.wavfile = wavstr;
                            //if (!string.IsNullOrWhiteSpace(newname))
                            //    clmodel.wavnewname = newname.Trim();
                            //if (!string.IsNullOrWhiteSpace(oldname))
                            //    clmodel.wavoldname = oldname.Trim();
                            //if (!string.IsNullOrWhiteSpace(path))
                            //    clmodel.wavpath = path.Trim();
                            clmodel.type = type;
                            clmodel.isstate = isstate;

                            res = await _sys_ivrwordsRepository.Update(clmodel);
                        }
                    }
                }
                if (res)
                    return Success("IVR欢迎词保存成功");
                else
                {
                    if (iss > 0)
                    {
                        return Error("存在已启动的IVR欢迎词在此有效期间，请查看记录后另外选择有效期！");
                    }
                    else
                    {
                        return Error("IVR欢迎词保存失败");
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "IVR欢迎词保存异常");
                return Error("IVR欢迎词保存失败");
            }
        }

        [Authorize]
        [HttpPost("delete")]
        public async Task<IActionResult> Remove(string[] ids)
        {
            //使用逻辑删除
            //物理删除的数据无法恢复
            var res = 0;
            if (ids != null && ids.Length > 0)
            {
                try
                {
                    foreach (var item in ids)
                    {
                        var ml = await _sys_ivrwordsRepository.GetSingle(item);
                        ml.isdelete = true;
                        if (await _sys_ivrwordsRepository.Update(ml))
                            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("请选择要删除的记录");
        }

        //将超过有效期的设置为失效状态
        private async Task upstateAsync()
        {
            Sys_IVRWords imodel = new Sys_IVRWords();
            Dictionary<string, string> dic = new Dictionary<string, string>();
            dic.Add("isstate", "2");

            var list = new List<FilterDefinition<Sys_IVRWords>>();
            var filterBuilder = Builders<Sys_IVRWords>.Filter;
            list.Add(filterBuilder.Eq("isdelete", false));
            list.Add(filterBuilder.Eq("isstate", 1));//启动状态
            list.Add(filterBuilder.Lt("enddate", DateTime.Now.ToLocalTime()));
            var filter = Builders<Sys_IVRWords>.Filter.And(list);
            var tt=await _sys_ivrwordsRepository.UpdateManay(imodel,dic, filter);
        }

        //获取ivr欢迎词是否有添加/修改权限
        private async Task<int> returnisaddAsync(string id, string sdate, string edate)
        {
            //根据条件查询集合
            var list = new List<FilterDefinition<Sys_IVRWords>>();
            var list1 = new List<FilterDefinition<Sys_IVRWords>>();
            var filterBuilder = Builders<Sys_IVRWords>.Filter;
            list.Add(filterBuilder.Eq("isdelete", false));
            #region 有效期处理
            var nowtime = DateTime.Now.ToLocalTime();
            if (sdate != null || sdate != null)
            {
                if (sdate != null)
                {
                    list1.Add(filterBuilder.Lte("startdate", sdate) & filterBuilder.Gte("enddate", sdate));
                }
                else
                {
                    list1.Add(filterBuilder.Lte("startdate", nowtime) & filterBuilder.Gte("enddate", nowtime));
                }
                if (edate != null)
                {
                    list1.Add(filterBuilder.Lte("startdate", edate) & filterBuilder.Gte("enddate", edate));
                }
                else
                {
                    list1.Add(filterBuilder.Lte("startdate", nowtime) & filterBuilder.Gte("enddate", nowtime));
                }
                list.Add(filterBuilder.Or(list1));
            }
            #endregion
            list.Add(filterBuilder.Eq("isstate", 1));//生效中状态
            if (id != null && id != "")
            {
                list.Add(filterBuilder.Ne("id", id));//sql += " and F_ID<>" + id;
            }
            var filter = Builders<Sys_IVRWords>.Filter.And(list);
            var ff = await _sys_ivrwordsRepository.CountAsync(filter);

            return int.Parse(ff.ToString());
        }
    }
}