using System;
using System.Collections.Generic;
using System.Common;
using System.IRepositories;
using System.Linq;
using System.Model;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;


namespace TVShoppingCallCenter_ZLJ.Controllers.knowledge
{
    [Produces("application/json")]
    [Route("api/[controller]")]
    public class KnowledgeClassController : BaseController
    {
        private readonly IRepositoryCategoryRepository _repositorycategoryreposytory;
        private readonly IRepositoryInformationRepository _repositoryinformationrepository;
        public KnowledgeClassController(IRepositoryCategoryRepository repositorycategoryreposytory, IRepositoryInformationRepository repositoryinformationrepository)
        {
            _repositorycategoryreposytory = repositorycategoryreposytory;
            _repositoryinformationrepository = repositoryinformationrepository;
        }
        /// <summary>
        /// 添加知识库分类
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("add")]
        public async Task<IActionResult> AddAsync(T_RepositoryCategory  input)
        {
            if (string.IsNullOrEmpty(input.F_CategoryName))
                return Error("请输入分类名称");
            if (input.F_Sort > 100000)
                return Error("排序过大，请重新输入");
            string user = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
            if (input .F_ParentId >0)
            {
                input.F_Expand1 = _repositorycategoryreposytory.GetSingle(x => x.F_CategoryId == input.F_ParentId)
                    .Result != null ? _repositorycategoryreposytory.GetSingle(x => x.F_CategoryId == input.F_ParentId)
                    .Result.F_CategoryName :"";
            }
            input.F_CreateOn = DateTime.Now;
            input.F_CreateBy = user;
            input.F_DeleteFlag = 0;
            var res = await _repositorycategoryreposytory.Add(input);
            if (res > 0)
            {
                var model = _repositorycategoryreposytory.GetSingle(x => x.F_CategoryId == res).Result;
                if (model != null)
                {
                    model.F_Expand2 = "|" + res + "|";
                    if (input.F_ParentId > 0)
                    {
                        var parent = _repositorycategoryreposytory.GetSingle(x => x.F_CategoryId == input.F_ParentId).Result;
                        if (parent != null)
                            model.F_Expand2 += parent.F_Expand2 + res + "|";
                    }
                    var Expand = _repositorycategoryreposytory.Update(model);

                }
                return Success("添加成功");
            }
            else
            {
                return Error("添加失败");
            }
        }
        /// <summary>
        /// 修改知识库分类
        /// </summary>
        [HttpPost("update")]
        public async Task<IActionResult> UpdateAsync(T_RepositoryCategory input)
        {
            if (string.IsNullOrEmpty(input.F_CategoryName))
                return Error("请输入分类名称");
            string user = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
            var model = await _repositorycategoryreposytory.GetSingle(x => x.F_CategoryId == input.F_CategoryId);
            if (model == null)
                return Error("操作失败");
            input.F_Expand2 = "|" + input.F_CategoryId + "|";
            if (input.F_ParentId > 0)
            {
                var parent = _repositorycategoryreposytory.GetSingle(x => x.F_CategoryId == input.F_ParentId)
                    .Result;
                if (parent != null)
                {
                    string[] Expand = parent.F_Expand2.Split('|');
                    if (Expand.Contains(input.F_CategoryId.ToString()))
                    {
                        return Error("不能选择该分类的下级分类");
                    }
                    else
                    {
                        input.F_Expand1 = parent.F_CategoryName;
                        input.F_Expand2 = parent.F_Expand2 += input.F_CategoryId + "|";
                    }
                       
                }
               
            }
            input.F_DeleteFlag = 0;
            input.F_CreateBy = model.F_CreateBy;
            input.F_CreateOn = model.F_CreateOn;
            var b = await _repositorycategoryreposytory.Update(input);
            if (b)
            {
                return Success("修改成功");
            }
            return Error("修改失败");
        }
        /// <summary>
        /// 删除知识库分类
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        [HttpPost("delete")]
        public async Task<IActionResult> Remove(int id = 0)
        {

            var model = _repositorycategoryreposytory.GetSingle(x => x.F_CategoryId == id).Result;
            if (model == null)
                return Error("该分类不存在");
            var dt = _repositoryinformationrepository.GetListALL(x => x.F_CategoryId == model.F_CategoryId&&x.F_DeleteFlag ==0).Result;
            if (dt != null)
            {
                if (dt.Count > 0)
                    return Error("请先删除此分类知识库信息");
            }
            model.F_DeleteFlag = (int)EnumUserCountState.Delete;
            bool n = _repositorycategoryreposytory.Update(model).Result;
            if (n)
                return Success("删除成功");
            else
                return Error("删除失败");
        }
        /// <summary>
        /// 获取知识库分类
        /// </summary>
        /// <param name="keyword"></param>
        /// <param name="pageindex"></param>
        /// <param name="pagesize"></param>
        /// <returns></returns>
        [HttpGet("getlist")]
        public async Task<IActionResult> GetListMark(string name, int parentid = -1, int pageindex = 0, int pagesize = 0)
        {
            // string user = "8000";

            List<IConditionalModel> conModels = new List<IConditionalModel>();
            #region 条件筛选
            conModels.Add(new ConditionalModel() { FieldName = "F_DeleteFlag", ConditionalType = ConditionalType.Equal, FieldValue = "0" });
            conModels.Add(new ConditionalModel() { FieldName = "F_CategoryName", ConditionalType = ConditionalType.Like, FieldValue = name });
            if (parentid > -1)
                conModels.Add(new ConditionalModel() { FieldName = "F_ParentId", ConditionalType = ConditionalType.Equal, FieldValue = parentid.ToString() });
            #endregion
            int recordCount = 0;
            if (pageindex > 0 && pagesize > 0)
            {
                var list = await _repositorycategoryreposytory.GetListByPage(conModels, new MyPageModel() { PageIndex = pageindex, PageSize = pagesize, PageCount = recordCount }, "  F_CreateOn  desc");
                var obj = new
                {
                    state = "success",
                    message = "成功",
                    rows = list,
                    total = list.Totals,
                };
                return Content(obj.ToJson());
            }
            else
            {
                var list = await _repositorycategoryreposytory.GetListALL(conModels, " F_CreateOn  desc");
                var obj = new
                {
                    state = "success",
                    message = "成功",
                    rows = list,
                    total = list.Count(),
                };
                return Content(obj.ToJson());
            }
        }
        /// <summary>
        /// 获取树形知识库分类
        /// </summary>
        /// <param name="id">id</param>
        /// <returns></returns>
        [HttpGet("getTreedetails")]
        public async Task<IActionResult> GetTreeAsync()
        {
            var list_ModuleInfo =  _repositorycategoryreposytory.GetListALL (x => x.F_DeleteFlag == 0
            ).Result ;
            var treeList = new List<TreeModel>();
            foreach (var item in list_ModuleInfo)
            {
                TreeModel treeModel = new TreeModel();
                treeModel.id = item.F_CategoryId ;
                treeModel.code ="";
                treeModel.iconcls = "";
                treeModel.text = item.F_CategoryName ;
                try
                {
                    treeModel.parentid = (int)item.F_ParentId;
                }
                catch
                {
                    treeModel.parentid = 0;
                }
                treeList.Add(treeModel);
            }
            return Success("获取地区树成功", treeList.TreeRecursion(0));
         
        }
        /// <summary>
        /// 获取详情
        /// </summary>
        /// <param name="id">id</param>
        /// <returns></returns>
        [HttpGet("getdetails")]
        public async Task<IActionResult> GetDetailsAsync(int id)
        {
            if (id <= 0)
                return Error("参数错误");

            var model = await _repositorycategoryreposytory.GetSingle(x => x.F_CategoryId == id);
            List<string> ParentId = new List<string>();
            List<string> ParentName = new List<string>();
            if (model == null)
            {
                return Error("获取失败");
            }
            var obj = new
            {
                model.F_CategoryId,
                model.F_CategoryName ,
                model.F_Expand1,
                model.F_ParentId ,
                model.F_Sort ,
                ParentId = Category(model.F_ParentId, 0, ParentId),
                ParentName = Category(model.F_ParentId, 1, ParentName),
            };
            
            return Success("获取成功！", obj);
        }
        public List<string> Category(int? CategoryId, int type, List<string> key)
        {
            var model = _repositorycategoryreposytory.GetSingle(x => x.F_CategoryId == CategoryId).Result;
            if (model != null)
            {
                if (type == 0)
                {
                    key.Add("" + CategoryId);
                    if (model.F_ParentId > 0)
                    {
                        key = Category((int)model.F_ParentId, 0, key);
                    }
                }
                else
                {
                    key.Add(model.F_CategoryName);
                    if (model.F_ParentId > 0)
                    {
                        key = Category((int)model.F_ParentId, 1, key);
                    }
                }
            }

            return key;
        }

    }
}