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

namespace TVShoppingCallCenter_ZLJ.Controllers.System
{
    [Authorize]
    [Produces("application/json")]
    [Route("api/[controller]")]
    public class DeptmentController : BaseController
    {
        private readonly ISys_DepartmentRepository _sys_departmentRepository;
        public DeptmentController(ISys_DepartmentRepository sys_departmentRepository)
        {
            _sys_departmentRepository = sys_departmentRepository;
        }

        /// <summary>
        /// 返回树形下拉框 部门数据 
        /// </summary>
        /// <returns></returns>
        [HttpGet("getall")]
        public async Task<IActionResult> GetALL()
        {
            var list_dept = await _sys_departmentRepository.GetListALL(x => x.F_State == (int)EnumDelState.Enabled, o => o.F_Sort, SqlSugar.OrderByType.Asc);
            var treeList = new List<TreeModel>();
            foreach (var item in list_dept)
            {
                TreeModel treeModel = new TreeModel();
                treeModel.id = item.F_DeptId;
                treeModel.code = item.F_Lock == 1 ? "" : "锁定";
                treeModel.iconcls = item.F_TargetMoney>0.1M? item.F_TargetMoney.ToString():"";
                treeModel.text = item.F_DeptName;
                treeModel.parentid = item.F_ParentId;
                treeList.Add(treeModel);
            }
            return Success("获取部门树成功", treeList.TreeRecursion(0));
        }

        /// <summary>
        /// 返回父子循环实体 
        /// </summary>
        /// <returns></returns>
        [HttpGet("getallloop")]
        public async Task<IActionResult> GetALLLoop()
        {
            List<T_Sys_Department> list_dept = await _sys_departmentRepository.GetListALL(x =>x.F_ParentId==0&& x.F_State == (int)EnumDelState.Enabled, o => o.F_Sort, SqlSugar.OrderByType.Asc);
            List<DepartmentDto> output= await ConvertAsync(list_dept);
            return Content(output.ToJson());
        }

        /// <summary>
        /// 递归获取部门
        /// </summary>
        /// <param name="modelList"></param>
        /// <returns></returns>
        private async Task<List<DepartmentDto>> ConvertAsync(List<T_Sys_Department> modelList)
        {
            List<DepartmentDto> output = new List<DepartmentDto>();
            if (modelList != null)
            {
                foreach (var model in modelList)
                {
                    DepartmentDto modelout = new DepartmentDto();

                    ModelConvertHelper<DepartmentDto, T_Sys_Department>.ModeToModelDefault(modelout, model);
                    List<T_Sys_Department> modelListChild = await _sys_departmentRepository.GetListALL(q => q.F_ParentId == model.F_DeptId&& q.F_State== (int)EnumDelState.Enabled);
                    if (modelListChild != null && modelListChild.Count > 0)
                    {
                        modelout.children =await ConvertAsync(modelListChild);
                    }
                    output.Add(modelout);
                }
            }
            return output;
        }

        /// <summary>
        /// 依据关键字获取相关部门数据
        /// </summary>
        /// <param name="keyword"></param>
        /// <returns></returns>
        [HttpGet("gettreegridjson")]
        public async Task<ActionResult> GetTreeGridJson(string keyword)
        {
            var list_dept = await _sys_departmentRepository.GetListALL(x => x.F_State < (int)EnumDelState.Delete);
            if (!string.IsNullOrEmpty(keyword))
            {
                list_dept = list_dept.ToList().TreeWhere(t => t.F_DeptName.Contains(keyword), "F_DeptId", "F_ParentId").ToList();
            }
            list_dept = list_dept.Where(x => x.F_State != (int)EnumDelState.Delete).OrderBy(x => x.F_Sort).ThenByDescending(x => x.F_LastModifyOn).ToList();//排序

            var treeList = new List<TreeGridModel>();
            foreach (var item in list_dept)
            {
                TreeGridModel treeModel = new TreeGridModel();
                bool hasChildren = list_dept.Count(t => t.F_ParentId == item.F_DeptId) == 0 ? false : true;
                treeModel.id = item.F_DeptId.ToString();
                treeModel.isLeaf = hasChildren;
                treeModel.parentId = item.F_ParentId.ToString();
                treeModel.expanded = hasChildren;
                treeModel.entityJson = item.ToJson();
                treeList.Add(treeModel);
            }
            return Content(treeList.TreeGridJson());
        }

        /// <summary>
        /// 获取部门实体
        /// </summary>
        /// <param name="mid"></param>
        /// <returns></returns>
        [HttpGet("getdept")]
        public async Task<IActionResult> GetDept(int deptid)
        {
            var entity_dept = await _sys_departmentRepository.GetSingle(x => x.F_DeptId == deptid && x.F_State == (int)EnumDelState.Enabled);
            if (entity_dept != null)
            {
                return Success("加载部门成功", entity_dept);
            }
            else
            {
                return Error("加载部门失败");
            }
        }
        [HttpGet("getdeptsingle")]
        public async Task<IActionResult> GetDeptsingle(int deptid)
        {
            var entity_dept = await _sys_departmentRepository.GetSingle(x => x.F_DeptId == deptid && x.F_State == (int)EnumDelState.Enabled);
            if(entity_dept==null)
                return Error("加载失败");

            var obj = new
            {
                model= entity_dept,
                levelid = await GetTypeAsync(entity_dept.F_DeptCode, 0),
                levelname = await GetTypeAsync(entity_dept.F_DeptCode, 1)
            };

            return Success("加载成功", obj);
        }


        /// <summary>
        /// 添加部门
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("adddept")]
        public async Task<IActionResult> AddDept(string deptname,int islock, int parentid=0,int sort=1,decimal targetmoney=0.00M)
        {
            if (string.IsNullOrEmpty(deptname))
                return Error("请输入部门名称");
            var parentcode = "|0|";
            if(parentid>0)
            {
                var parentdept= await _sys_departmentRepository.GetSingle(x => x.F_DeptId == parentid && x.F_State == (int)EnumDelState.Enabled);
                if (parentdept != null)
                    parentcode = parentdept.F_DeptCode;
            }
            var entity_dept = new T_Sys_Department();
            entity_dept.F_DeptName = deptname;
            entity_dept.F_State = (int)EnumDelState.Enabled;
            entity_dept.F_ParentId = parentid;
            entity_dept.F_ParentCode = parentcode;
            entity_dept.F_Sort = sort;
            entity_dept.F_CreateOn = DateTime.Now.ToLocalTime();
            entity_dept.F_CreateBy = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
             entity_dept.F_Lock = islock;
            entity_dept.F_TargetMoney = targetmoney;
            var res = await _sys_departmentRepository.Add(entity_dept);
            if (res > 0)
            {
                entity_dept.F_DeptId = res;
                entity_dept.F_DeptCode = parentcode + res.ToString() + "|";
                await _sys_departmentRepository.Update(entity_dept);
                return Success("部门添加成功");
            }
            else
            {
                return Error("部门添加失败,请重试！");
            }

        }
        /// <summary>
        /// 删除部门
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        [HttpPost("deldept")]
        public async Task<IActionResult> DelDept(int[] ids)
        {
            if (ids != null && ids.Length > 0)
            {
                var res = 0;
                //获取选中的部门下所有级联部门id
                List<int> _ids = await GetTreeDeptId(new List<int>(ids));
                ids = _ids.ToArray();
                //foreach (var item in _ids)
                //{
                //        //var ml = await _sys_departmentRepository.GetSingle(x => x.F_DeptId == item&&x.F_Lock==0);
                //        //ml.F_State = (int)EnumDelState.Delete;
                //        //ml.F_DeleteOn = DateTime.Now.ToLocalTime();
                //        //ml.F_DeleteBy = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
                //        //if (_sys_departmentRepository.Update(ml).Result)
                //        //    res += 1;

                //}
                if (await _sys_departmentRepository.Delete(x => ids.Contains(x.F_DeptId) && x.F_Lock == 0))
                    return Success("删除部门成功/已锁定未删除");
                //else if (res > 0 && res < ids.Length)
                //    return Error("部分删除失败，请查看后重新操作");
                else
                    return Error("删除失败，请查看后重新操作");
            }
            else
            {
                return Error("获取参数失败");
            }
        }

        /// <summary>
        /// 编辑部门
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("editdept")]
        public async Task<IActionResult> EditDept(int deptid,string deptname, int parentid = 0, int sort = 1, decimal targetmoney = 0.00M)
        {
            if (string.IsNullOrEmpty(deptname))
                return Error("请输入部门名称");
            if (deptname.Length>30)
                return Error("部门名称过长");
            var entity_dept = await _sys_departmentRepository.GetSingle(x => x.F_DeptId == deptid && x.F_State == (int)EnumDelState.Enabled);
            if (entity_dept != null)
            {
                if (entity_dept.F_Lock == 1)
                {
                    return Error("锁定部门不能编辑");
                }
                var parentcode = "|0|";
                if (parentid > 0)
                {
                    var parentdept = await _sys_departmentRepository.GetSingle(x => x.F_DeptId == parentid && x.F_State == (int)EnumDelState.Enabled);
                    if (parentdept != null)
                        parentcode = parentdept.F_DeptCode;
                }

                entity_dept.F_DeptName = deptname;
                entity_dept.F_State = (int)EnumDelState.Enabled;
                entity_dept.F_ParentId = parentid;
                entity_dept.F_ParentCode = parentcode;
                entity_dept.F_Sort = sort;

                entity_dept.F_LastModifyOn = DateTime.Now;
                entity_dept.F_LastModifyBy = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;


                entity_dept.F_TargetMoney = targetmoney;
                if (await _sys_departmentRepository.Update(entity_dept))
                {
                    return Success("部门修改成功!");
                }
                else
                {
                    return Error("部门修改失败,请重试！");
                }
            }
            else
            {
                return Error("部门对象获取失败");
            }
        }

        #region 私有方法
        /// <summary>
        /// 获取所有子节点的Id
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        private async Task<List<int>> GetTreeDeptId(List<int> ids)
        {
            List<int> _moduleIdlist = null;
            List<int> _list = new List<int>(ids);
            var list_dept = await _sys_departmentRepository.GetListALL(x=>x.F_State == (int)EnumDelState.Enabled);//DataSet  不在此处添加搜素条件，是因为计划改为缓存
            for (int i = 0; i < ids.Count; i++)
            {
                _moduleIdlist = list_dept.Where(x => x.F_ParentId == ids[i]).Select(x => x.F_DeptId).ToList();
                if (_moduleIdlist.Count > 0)
                {
                    _list.AddRange(_moduleIdlist);
                    _list.AddRange(await GetTreeDeptId(_moduleIdlist));
                    _list = _list.Distinct().ToList();
                }
            }
            return _list;
        }

        /// <summary>
        /// 获取分类
        /// </summary>
        /// <param name="typeid"></param>
        /// <returns></returns>
        public async Task<object> GetTypeAsync(string code,int type)
        {
            List<int> ids = new List<int>();
            List<string> names = new List<string>();
            string[] codes = code.Trim('|').Split('|');

            var typelists = await _sys_departmentRepository.GetListALL(x => x.F_State == (int)EnumDelState.Enabled && codes.Contains(x.F_DeptId.ToString()),o=>o.F_DeptId,OrderByType.Asc);

            foreach (var item in typelists)
            {
                ids.Add(item.F_DeptId);
                names.Add(item.F_DeptName);
            }
            if (type == 0)
                return ids.ToArray();
            else
                return names.ToArray();
        }
        #endregion
    }
}