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

namespace CallCenterApi.Controllers
{
    /// <summary>
    /// 知识库控制器
    /// </summary>
    [Authorize]
    [ApiVersion("6.0")]
    [Produces("application/json")]
    [Route("api/[controller]")]
    public class KnowledgeController : BaseController
    {
        private readonly ILogger<KnowledgeController> _logger;
        private readonly IKnowledge_BaseRepository _knowledge_baseRepository;
        private readonly IKnowledge_TypeRepository _knowledge_typeRepository;

        public KnowledgeController(ILogger<KnowledgeController> logger, IKnowledge_TypeRepository knowledge_typeRepository, IKnowledge_BaseRepository knowledge_baseRepository)
        {
            _logger = logger;
            _knowledge_baseRepository = knowledge_baseRepository;
            _knowledge_typeRepository = knowledge_typeRepository;
        }

        #region 知识库分类
        /// <summary>
        /// 获取
        /// </summary>
        [HttpGet("gettypelist")]
        public async Task<IActionResult> GetTypeListAsync(string id)
        {
            if (id != null)
            {
                //1级
                var listmodel= new List<Knowledge_Type>();
                var list = await _knowledge_typeRepository.Get(p => p.id == id&&  p.isdelete == 0);
                
                foreach (var item in list)
                {
                    //2级
                    listmodel.Add(item);
                    var list1= await _knowledge_typeRepository.Get(p => p.parentid == item.id && p.isdelete == 0);
                    foreach (var item1 in list1)
                    {
                        //3级
                        listmodel.Add(item1);
                        var list2 = await _knowledge_typeRepository.Get(p => p.parentid == item1.id && p.isdelete == 0);
                        foreach (var item2 in list2)
                        {
                            //4级
                            listmodel.Add(item2);
                            var list3 = await _knowledge_typeRepository.Get(p => p.parentid == item2.id && p.isdelete == 0);
                            foreach (var item3 in list3)
                            {
                                //5级
                                listmodel.Add(item3);
                                var list4 = await _knowledge_typeRepository.Get(p => p.parentid == item3.id && p.isdelete == 0);
                                foreach (var item4 in list4)
                                {
                                    listmodel.Add(item4);
                                    var list5 = await _knowledge_typeRepository.Get(p => p.parentid == item4.id && p.isdelete == 0);
                                    foreach (var item5 in list5)
                                    {
                                        listmodel.Add(item5);
                                    }
                                }
                            }
                        }
                    }
                }

                return Success("获取成功", listmodel);
            }
            else
            {
                var list = await _knowledge_typeRepository.Get(p => p.isdelete == 0);
                return Success("获取成功", list);
            }
            

            
        }

        /// <summary>
        /// 获取树结构
        /// </summary>
        [HttpGet("gettypetreelist")]
        public async Task<IActionResult> GetTypeTreeListAsync()
        {
            var list = (await _knowledge_typeRepository.Get(p => p.isdelete == 0)).ToList();

            return Success("获取成功", gettreeinfo(list, null));
        }

        /// <summary>
        /// 循环获取树结构
        /// </summary>
        /// <param name="list"></param>
        /// <param name="pid"></param>
        /// <returns></returns>
        public object gettreeinfo(List<Knowledge_Type> list, string pid)
        {
            var children = list.Where(p => p.parentid == pid).Select(p => new {
                p.id,
                p.name,
                p.sort,
                p.parentid,
                children = gettreeinfo(list, p.id)
            });

            return children;
        }

        /// <summary>
        /// 获取
        /// </summary>
        [HttpGet("gettypesingle")]
        public async Task<IActionResult> GetTypeSingleAsync(string id)
        {
            var model = await _knowledge_typeRepository.GetSingle(id);
            var typenames = await GetTypeNameAsync(model.id);
            var typeids = await GetTypeIdAsync(model.id);
            var obj = new
            {
                model,
                typeids = typeids.Split(","),
                typenames = typenames.Split(",")
            };

            return Success("获取成功", obj);
        }

        /// <summary>
        /// 添加
        /// </summary>
        [HttpPost("addtype")]
        public async Task<IActionResult> AddTypeAsync(string parentid, string code, string name, string remark, int sort)
        {
            if (string.IsNullOrEmpty(name))
            {
                return Error("名称不能为空");
            }

            Knowledge_Type clmodel = new Knowledge_Type();

            string optuser = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
            string optusername = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Name).Value;

            clmodel.parentid = parentid;
            clmodel.code = code;
            clmodel.name = name;
            clmodel.remark = remark;
            clmodel.sort = sort;

            clmodel.createuser = optuser;
            clmodel.createusername = optusername;
            clmodel.isdelete = 0;
            clmodel.createtime = DateTime.Now;

            bool bl = await _knowledge_typeRepository.Add(clmodel);

            if (bl)
            {
                return Success("保存成功");
            }
            else
                return Error("保存失败");

        }

        /// <summary>
        /// 修改
        /// </summary>
        [HttpPost("updatetype")]
        public async Task<IActionResult> UpdateTypeAsync(string id, string parentid, string code, string name, string remark, int sort)
        {
            if (string.IsNullOrEmpty(name))
            {
                return Error("名称不能为空");
            }

            string optuser = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
            string optusername = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Name).Value;

            var cls = await _knowledge_typeRepository.Get(p => p.id == id && p.isdelete == 0);
            var clmodel = cls.FirstOrDefault();

            clmodel.parentid = parentid;
            clmodel.code = code;
            clmodel.name = name;
            clmodel.remark = remark;
            clmodel.sort = sort;

            var res = await _knowledge_typeRepository.UpdateOne(clmodel);
            if (res)
            {
                return Success("保存成功");
            }
            else
                return Error("保存失败");
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        [HttpPost("deletetype")]
        public async Task<IActionResult> RemoveTypeAsync(string[] ids, int channel = 1)
        {
            string optuser = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
            string optusername = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Name).Value;

            //使用逻辑删除
            //物理删除的数据无法恢复
            var res = 0;
            if (ids != null && ids.Length > 0)
            {
                foreach (var id in ids)
                {
                    if (await DeleteTypeAsync(id, optuser))
                    {
                        res += 1;
                    }
                }
                if (res == ids.Length)
                    return Success("删除成功");
                else if (res > 0 && res < ids.Length)
                    return Error("部分删除失败");
                else
                    return Error("删除失败");
            }
            else
                return Error("请选择要删除的记录");
        }

        /// <summary>
        /// 循环删除分类
        /// </summary>
        /// <param name="typeid"></param>
        /// <returns></returns>
        public async Task<bool> DeleteTypeAsync(string typeid, string usercode)
        {
            bool bl = false;
            var typeinfo = await _knowledge_typeRepository.GetSingle(typeid);
            if (typeinfo != null)
            {
                //if (typeinfo.parentid != null)
                //{
                //    await DeleteTypeAsync(typeinfo.parentid, usercode);
                //}

                var zlist = await _knowledge_typeRepository.Get(p => p.parentid == typeinfo.id && p.isdelete == 0);
                foreach (var z in zlist)
                {
                    await DeleteTypeAsync(z.id, usercode);
                }

                typeinfo.isdelete = 1;
                typeinfo.deleteuser = usercode;
                typeinfo.deletetime = DateTime.Now;
                bl = await _knowledge_typeRepository.UpdateOne(typeinfo);
            }

            return bl;
        }

        #endregion

        #region 知识库
        /// <summary>
        /// 分页获取
        /// </summary>
        [HttpGet("getlistbypage")]
        public async Task<IActionResult> GetListsByPageAsync(string key, string typeid, string stime, string etime, int pageindex = 1, int pagesize = 10)
        {
           

            if (typeid != null)
            {
                //1级
                var listmodel = new List<Knowledge_Type>();
                var listmobase = new List<object>();
                int recordCount = 0;
                int count = 0;
                var list = await _knowledge_typeRepository.Get(p => p.id == typeid && p.isdelete == 0);

                foreach (var item in list)
                {
                    //2级
                    listmodel.Add(item);
                    var list1 = await _knowledge_typeRepository.Get(p => p.parentid == item.id && p.isdelete == 0);
                    foreach (var item1 in list1)
                    {
                        //3级
                        listmodel.Add(item1);
                        var list2 = await _knowledge_typeRepository.Get(p => p.parentid == item1.id && p.isdelete == 0);
                        foreach (var item2 in list2)
                        {
                            //4级
                            listmodel.Add(item2);
                            var list3 = await _knowledge_typeRepository.Get(p => p.parentid == item2.id && p.isdelete == 0);
                            foreach (var item3 in list3)
                            {
                                //5级
                                listmodel.Add(item3);
                                var list4 = await _knowledge_typeRepository.Get(p => p.parentid == item3.id && p.isdelete == 0);
                                foreach (var item4 in list4)
                                {
                                    listmodel.Add(item4);
                                    var list5 = await _knowledge_typeRepository.Get(p => p.parentid == item4.id && p.isdelete == 0);
                                    foreach (var item5 in list5)
                                    {
                                        listmodel.Add(item5);
                                    }
                                }
                            }
                        }
                    }
                }

                foreach (var item in listmodel)
                {
                    
                    var result =  _knowledge_baseRepository.GetListsByPage(key, item.id, stime, etime, pageindex, pagesize, out recordCount);

                    count += recordCount;

                    foreach (var item1 in result.ToList())
                    {
                         listmobase.Add(item1);
                    }

                }
                var obj = new
                {
                    rows = listmobase.ToList(),
                    total = count
                };
                return Success("获取成功", obj);
            }
            else {
                int recordCount = 0;
                var result = _knowledge_baseRepository.GetListsByPage(key, typeid, stime, etime, pageindex, pagesize, out recordCount);

                var obj = new
                {
                    rows = result.ToList(),
                    total = recordCount
                };
                return Success("获取成功", obj);
            }
           
        }

        /// <summary>
        /// 获取
        /// </summary>
        [HttpGet("getsingle")]
        public async Task<IActionResult> GetSingleAsync(string id)
        {
            //var model = _knowledge_baseRepository.GetDetails(id);
            var model = await _knowledge_baseRepository.GetSingle(id);
            var typenames = await GetTypeNameAsync(model.typeid);
            var typeids = await GetTypeIdAsync(model.typeid);
            var obj = new
            {
                model,
                typeids = typeids.Split(","),
                typenames = typenames.Split(",")
            };

            return Success("获取成功", obj);
        }

        /// <summary>
        /// 循环获取分类名称
        /// </summary>
        /// <param name="typeid"></param>
        /// <returns></returns>
        public async Task<string> GetTypeNameAsync(string typeid)
        {
            string type = string.Empty;
            var typeinfo = await _knowledge_typeRepository.GetSingle(typeid);
            if (typeinfo != null)
            {
                if (typeinfo.parentid != null)
                {
                    type = await GetTypeNameAsync(typeinfo.parentid);
                }
                if (string.IsNullOrEmpty(type))
                {
                    type = typeinfo.name;
                }
                else
                {
                    type += "," + typeinfo.name;
                }
            }

            return type;
        }

        /// <summary>
        /// 循环获取分类id
        /// </summary>
        /// <param name="typeid"></param>
        /// <returns></returns>
        public async Task<string> GetTypeIdAsync(string typeid)
        {
            string type = string.Empty;
            var typeinfo = await _knowledge_typeRepository.GetSingle(typeid);
            if (typeinfo != null)
            {
                if (typeinfo.parentid != null)
                {
                    type = await GetTypeIdAsync(typeinfo.parentid);
                }
                if (string.IsNullOrEmpty(type))
                {
                    type = typeinfo.id;
                }
                else
                {
                    type += "," + typeinfo.id;
                }
            }

            return type;
        }

        /// <summary>
        /// 添加
        /// </summary>
        [HttpPost("add")]
        public async Task<IActionResult> AddAsync(string typeid, string title, string content, string remark)
        {
            Knowledge_Base clmodel = new Knowledge_Base();

            string optuser = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
            string optusername = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Name).Value;

            clmodel.typeid = typeid;
            clmodel.title = title;
            clmodel.content = content;
            clmodel.remark = remark;

            clmodel.createuser = optuser;
            clmodel.createusername = optusername;
            clmodel.isdelete = 0;
            clmodel.createtime = DateTime.Now;

            bool bl = await _knowledge_baseRepository.Add(clmodel);

            if (bl)
            {
                return Success("保存成功");
            }
            else
                return Error("保存失败");

        }

        /// <summary>
        /// 修改
        /// </summary>
        [HttpPost("update")]
        public async Task<IActionResult> UpdateAsync(string id, string typeid, string title, string content, string remark)
        {
            string optuser = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
            string optusername = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Name).Value;

            var cls = await _knowledge_baseRepository.Get(p => p.id == id && p.isdelete == 0);
            var clmodel = cls.FirstOrDefault();

            clmodel.typeid = typeid;
            clmodel.title = title;
            clmodel.content = content;
            clmodel.remark = remark;

            var res = await _knowledge_baseRepository.UpdateOne(clmodel);
            if (res)
            {
                return Success("保存成功");
            }
            else
                return Error("保存失败");
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        [HttpPost("delete")]
        public async Task<IActionResult> RemoveAsync(string[] ids, int channel = 1)
        {
            string optuser = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
            string optusername = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Name).Value;

            //使用逻辑删除
            //物理删除的数据无法恢复
            var res = 0;
            if (ids != null && ids.Length > 0)
            {
                foreach (var id in ids)
                {
                    var ml = await _knowledge_baseRepository.GetSingle(id);
                    ml.isdelete = 1;
                    ml.deleteuser = optuser;
                    ml.deletetime = DateTime.Now;
                    if (await _knowledge_baseRepository.UpdateOne(ml))
                    {
                        res += 1;
                    }
                }
                if (res == ids.Length)
                    return Success("删除成功");
                else if (res > 0 && res < ids.Length)
                    return Error("部分删除失败");
                else
                    return Error("删除失败");
            }
            else
                return Error("请选择要删除的记录");
        } 
        #endregion
    }
}
