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.IndexCategory
{

    [Produces("application/json")]
    [Route("api/[controller]")]
    public class IndexCategoryController : BaseController
    {
        private readonly IQC_IndexCategoryReposytory _qc_indexcategoryreposytory;
        private readonly IQC_IndexBaseReposytory _qc_indexbasereposytory;
        public IndexCategoryController(IQC_IndexCategoryReposytory qc_indexcategoryreposytory, IQC_IndexBaseReposytory qc_indexbasereposytory)
        {
            _qc_indexcategoryreposytory = qc_indexcategoryreposytory;
            _qc_indexbasereposytory = qc_indexbasereposytory;
        }
        /// <summary>
        /// 获取树形分类
        /// </summary>
        /// <param name="id">id</param>
        /// <returns></returns>
        [HttpGet("getTreedetails")]
        public async Task<IActionResult> GetTreeAsync()
        {
            var list_ModuleInfo = _qc_indexcategoryreposytory.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="input"></param>
        /// <returns></returns>
        [HttpPost("add")]
        public async Task<IActionResult> AddAsync(T_QC_IndexCategory  input)
        {
            if (string .IsNullOrEmpty (input.F_CategoryName))
                return Error("请输入分类名称");

            if(input.F_CategoryName.Length>20)
            { return Error("分类名称长度不能超过20"); }
            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 _qc_indexcategoryreposytory.Add(input);
            if (res > 0)
            {
                var model = _qc_indexcategoryreposytory.GetSingle(x => x.F_CategoryId == res).Result;
                if (model!=null )
                {
                    model.F_Expand2 = "|" + res + "|";
                    if (input.F_ParentId > 0)
                    {
                        var parent = _qc_indexcategoryreposytory.GetSingle(x => x.F_CategoryId == input.F_ParentId).Result;
                        if (parent != null)
                            model.F_Expand2 = parent.F_Expand2 += res + "|";
                    }
                    var Expand = _qc_indexcategoryreposytory.Update(model);
                }
              
             
                return Success("添加成功");
            }
            else
            {
                return Error("添加失败");
            }
        }
        /// <summary>
        /// 修改指标
        /// </summary>
        [HttpPost("update")]
        public async Task<IActionResult> UpdateAsync(T_QC_IndexCategory input)
        {
            if (string.IsNullOrEmpty(input.F_CategoryName))
                return Error("请输入分类名称");
            string user = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
            var model = await _qc_indexcategoryreposytory.GetSingle(x => x.F_CategoryId == input.F_CategoryId);
            if (model == null)
                return Error("操作失败");
            input.F_DeleteFlag = 0;
            input.F_CreateBy = model.F_CreateBy;
            input.F_CreateOn = model.F_CreateOn;
            input.F_Expand2 = "|" + input.F_CategoryId + "|";
          

                if (input.F_ParentId > 0)
                {
                    var parent = _qc_indexcategoryreposytory.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_Expand2 = parent.F_Expand2 += input.F_CategoryId + "|";
                   }
                    
                }
           
            var b = await _qc_indexcategoryreposytory.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 =  _qc_indexcategoryreposytory.GetSingle(x => x.F_CategoryId == id).Result ;
            if (model == null)
                return Error("该指标不存在");
            var dt = _qc_indexbasereposytory.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 = _qc_indexcategoryreposytory.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 _qc_indexcategoryreposytory.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 _qc_indexcategoryreposytory.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("getdetails")]
        public async Task<IActionResult> GetDetailsAsync(int id)
        {
            if (id <= 0)
                return Error("参数错误");

            var model = await _qc_indexcategoryreposytory.GetSingle(x => x.F_CategoryId  == id);
            if (model == null)
            {
                return Error("获取失败");
            }
            List<string> ParentId = new List<string>();
            List<string> ParentName = new List<string>();
            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 = _qc_indexcategoryreposytory.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;
        }
       
    }
}