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

namespace TVShoppingCallCenter_ZLJ.Controllers.knowledge
{
    [Produces("application/json")]
    [Route("api/[controller]")]
    public class KnowledgeController : BaseController
    {
        private readonly IRepositoryCategoryRepository _repositorycategoryreposytory;
        private readonly IRepositoryInformationRepository _repositoryinformationrepository;
        private readonly ISys_AccessoriesRepository _sys_accessoriesrepository;
        private readonly ISys_SystemConfigRepository _sys_sysconfigRepository;
        public KnowledgeController(IRepositoryCategoryRepository repositorycategoryreposytory, IRepositoryInformationRepository repositoryinformationrepository, ISys_AccessoriesRepository sys_accessoriesrepository, ISys_SystemConfigRepository sys_sysconfigRepository)
        {
            _repositorycategoryreposytory = repositorycategoryreposytory;
            _repositoryinformationrepository = repositoryinformationrepository;
            _sys_accessoriesrepository = sys_accessoriesrepository;
            _sys_sysconfigRepository = sys_sysconfigRepository;
        }
        /// <summary>
        /// 添加知识库
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("add")]
        public async Task<IActionResult> AddAsync(T_RepositoryInformation input)
        {
            if (input.F_CategoryId <= 0)
            {
                return Error("请选择知识库分类");
            }
            input.F_Expand1 = _repositorycategoryreposytory.GetSingle(x => x.F_CategoryId == input.F_CategoryId)
                     .Result != null ? _repositorycategoryreposytory.GetSingle(x => x.F_CategoryId == input.F_CategoryId)
                     .Result.F_CategoryName : "";
       // string user = "8000";
          string user = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
            input.F_CreateOn = DateTime.Now;
            input.F_CreateBy = user;
            input.F_DeleteFlag = 0;
            var res = await _repositoryinformationrepository.Add(input);
            if (res > 0)
            {
                return Success("添加成功");
            }
            else
            {
                return Error("添加失败");
            }
        }
        /// <summary>
        /// 修改知识库
        /// </summary>
        [HttpPost("update")]
        public async Task<IActionResult> UpdateAsync(T_RepositoryInformation input)
        {
         
            if (input.F_CategoryId <= 0)
            {
                return Error("请选择知识库分类");
            }
            input.F_Expand1 = _repositorycategoryreposytory.GetSingle(x => x.F_CategoryId == input.F_CategoryId)
                     .Result != null ? _repositorycategoryreposytory.GetSingle(x => x.F_CategoryId == input.F_CategoryId)
                     .Result.F_CategoryName : "";
            string user = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
            var model = await _repositoryinformationrepository.GetSingle(x => x.F_RepositoryId  == input.F_RepositoryId);

            if (model == null)
                return Error("操作失败");
            input.F_DeleteFlag = 0;
            input.F_CreateBy = model.F_CreateBy;
            input.F_CreateOn = model.F_CreateOn;
            input.F_ModifyBy = user;
            input.F_ModifyOn = DateTime.Now;
            var b = await _repositoryinformationrepository.Update(input);
            if (b)
            {
                return Success("修改成功");
            }
            return Error("修改失败");
        }
        [HttpPost("delete")]
        public async Task<IActionResult> Remove(int [] ids )
        {

            var res = 0;
            if (ids != null && ids.Length > 0)
            {
                foreach (var item in ids)
                {
                    var model = await _repositoryinformationrepository.GetSingle(x => x.F_RepositoryId  == item);
                    model.F_DeleteFlag  = (int)EnumUserCountState.Delete;
                    if (_repositoryinformationrepository.Update(model).Result)
                        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="id">id</param>
        /// <returns></returns>
        [HttpGet("getdetails")]
        public async Task<IActionResult> GetDetailsAsync(int id)
        {
            if (id <= 0)
                return Error("参数错误");

            var model = await _repositoryinformationrepository.GetSingle(x => x.F_RepositoryId  == id);
            if (model == null)
            {
                return Error("获取失败");
            }
            var configfj = _sys_sysconfigRepository.GetSingle(x => x.F_ParamCode == "FileUrlPath").Result;
                
            List<T_Sys_Accessories> FileUrl = new List<T_Sys_Accessories>();
            FileUrl = GetFileData(model.F_Url , configfj.F_ParamValue);
            List<string> ParentId = new List<string>();
            List<string> ParentName = new List<string>();
            var obj = new
            {
                model.F_RepositoryId,
                model .F_Title ,
                model.F_Content,
                model.F_KeyWords,
                model.F_Description,
                model.F_Url,
                model.F_Expand1,
                ParentId = Category(model.F_CategoryId, 0, ParentId),
                ParentName = Category(model.F_CategoryId, 1, ParentName),
                FileUrl
            };

            return Success("获取成功！", obj);
        }
        public List<T_Sys_Accessories> GetFileData(string ids, string prefix)
        {
            List<T_Sys_Accessories> modellist = new List<T_Sys_Accessories>();
            List<IConditionalModel> conModels = new List<IConditionalModel>();
            conModels.Add(new ConditionalModel() { FieldName = "F_Id", ConditionalType = ConditionalType.In , FieldValue = ids });
            var model = _sys_accessoriesrepository.GetListALL(conModels, " F_CreateTime  desc").Result ;
            foreach (var it in model)
            {
                it.F_Url = prefix + it.F_Url;
                modellist.Add(it);
            }
            return modellist;
        }
        private string CategoryId(int  parentid)
        {
            string modelList = parentid+ "";
            var iv = _repositorycategoryreposytory.GetSingle (x => x.F_CategoryId == parentid && x.F_DeleteFlag == 0).Result;
               
            if (iv != null)
            {
                List<IConditionalModel> conModels = new List<IConditionalModel>();
                conModels.Add(new ConditionalModel() { FieldName = "F_DeleteFlag", ConditionalType = ConditionalType.Equal, FieldValue = "0" });
                conModels.Add(new ConditionalModel() { FieldName = "F_Expand2", ConditionalType = ConditionalType.Like, FieldValue = iv.F_Expand2 });
                var list = _repositorycategoryreposytory.GetListALL(conModels, " F_CreateOn  desc").Result;
                if (list!=null )
                {
                    foreach (var it in list)
                    {
                        modelList += "," + it.F_CategoryId;
                    }
                }
            }
            return modelList;
        }
        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;
        }
        /// <summary>
        /// 上传附件
        /// </summary>
        /// <returns></returns>
        [HttpPost("upload")]
        public async Task<IActionResult> UploadFiles(List<IFormFile> files)
        {
           
            List<T_Sys_Accessories> acs = new List<T_Sys_Accessories>();
            //string user = "8000";
           string user = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
              string path =  "\\Upload\\Files\\" + DateTime.Now.ToString("yyyy") + "\\" + DateTime.Now.ToString("MM") + "\\" + DateTime.Now.ToString("dd");
            string fliepath = Directory.GetCurrentDirectory() + path;
            //记录日志内容
            if (!Directory.Exists(fliepath))
            {
                Directory.CreateDirectory(fliepath);
            }
            if (files.Count > 0)
            {
                foreach (var item in files)     //上传选定的文件列表
                {
                    if (item.Length > 0)        //文件大小 0 才上传
                    {
                        if (item.FileName.IndexOf ('#') != -1)
                        {
                            return Error ("附件名称不能包含#");
                        }
                        var thispath = fliepath + "\\" + item.FileName;
                        //当前上传文件应存放的位置
                        //上传文件
                        using (var stream = new FileStream(thispath, FileMode.Create))      //创建特定名称的文件流
                        {
                            try
                            {
                                 await  item.CopyToAsync(stream);     //上传文件
                                T_Sys_Accessories model_T_Sys_Accessories = new T_Sys_Accessories();
                                model_T_Sys_Accessories.F_CreateTime  = DateTime.Now;//上传时间
                                model_T_Sys_Accessories.F_Name  = item.FileName;//附件名称
                                model_T_Sys_Accessories.F_Type  = item.FileName.Split ('.')[1];//附件类型
                                model_T_Sys_Accessories.F_Url  = path + "\\" + item.FileName;//附件地址
                                model_T_Sys_Accessories.F_Size = item.Length;
                                model_T_Sys_Accessories.F_CreateUser  = user;//上传人  
                                var id = await _sys_accessoriesrepository.Add(model_T_Sys_Accessories);
                                model_T_Sys_Accessories.F_Id = id;
                                acs.Add(model_T_Sys_Accessories);

                            }
                            catch (Exception ex)        //上传异常处理
                            {
                               
                            }
                        }
                    }
                }
                return Success("成功",  acs);
            }
            {
                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 keyword,int pid=-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" });
            if (!string.IsNullOrEmpty(keyword))
            {
                conModels.Add(new ConditionalCollections()
                {
                    ConditionalList = new List<KeyValuePair<WhereType, ConditionalModel>>()
                    {
                        new  KeyValuePair<WhereType, ConditionalModel>(WhereType.And, new ConditionalModel() { FieldName = "F_Title", ConditionalType = ConditionalType.Like, FieldValue = keyword }),
                        new  KeyValuePair<WhereType, ConditionalModel>( WhereType.Or , new ConditionalModel() { FieldName = "F_Content", ConditionalType = ConditionalType.Like, FieldValue = keyword }),
                         new  KeyValuePair<WhereType, ConditionalModel>( WhereType.Or , new ConditionalModel() { FieldName = "F_KeyWords", ConditionalType = ConditionalType.Like, FieldValue = keyword })
                    }
                });
            }
            if (pid>-1)
            {
                conModels.Add(new ConditionalModel() { FieldName = "F_CategoryId", ConditionalType = ConditionalType.In , FieldValue = CategoryId(pid) });
            }
            #endregion
            int recordCount = 0;
            if (pageindex > 0 && pagesize > 0)
            {
                var list = await _repositoryinformationrepository.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 _repositoryinformationrepository.GetListALL(conModels, " F_CreateOn  desc");
                var obj = new
                {
                    state = "success",
                    message = "成功",
                    rows = list,
                    total = list.Count(),
                };
                return Content(obj.ToJson());
            }
        }
    }
}