using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using MadRunFabric.Common;
using Microsoft.Extensions.Logging;
using ConfigurationApi.IRepositories;
using MongoDB.Driver;
using MadRunFabric.Model;
using Microsoft.AspNetCore.Authorization;
using System.Security.Claims;
using Api.SignToken;
using Microsoft.Extensions.Configuration;

namespace ConfigurationApi.Controllers
{
    /// <summary>
    /// 部门科室
    /// </summary>
    [Authorize]
    [ApiVersion("6.0")]
    [Produces("application/json")]
    [Route("api/[controller]")]
    public class DepartmentController : BaseController
    {
        private readonly ILogger<DepartmentController> _logger;
        private readonly IConfiguration _configuration;
        private readonly ISys_User_AccountRepository _sys_user_accountRepository;
        private readonly ISignTokenService _signTokenService;
        private readonly ISys_DepartmentRepository _sys_departmentrepository;
        public DepartmentController(
            ILogger<DepartmentController> logger,
            IConfiguration configuration,
            ISys_User_AccountRepository sys_user_accountRepository,
            ISignTokenService signTokenService,
            ISys_DepartmentRepository sys_departmentrepository
            )
        {
            _logger = logger;
            _configuration = configuration;
            _sys_user_accountRepository = sys_user_accountRepository;
            _signTokenService = signTokenService;
            _sys_departmentrepository = sys_departmentrepository;
        }

        /// <summary>
        /// 获取科室列表 by page
        /// </summary>
        /// <param name="keyword"></param>
        /// <param name="stime"></param>
        /// <param name="etime"></param>
        /// <param name="pageindex"></param>
        /// <param name="pagesize"></param>
        /// <returns></returns>
        [HttpGet("getlistbypage")]
        public IActionResult GetListByPageAsync(string keyword, string projectid, string building, string floorid, int pageindex = 1, int pagesize = 10)
        {
            string usercode = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
            //var userstr = _signTokenService.GetUserInfoAsync(usercode).Result;
            //var userinfo = userstr.ToJObject()["data"].ToString().ToObject<UserInfoModel>();
            
            var userinfos = _sys_user_accountRepository.GetUserInfo(usercode);
            var userinfo = JsonHelper.JsonToEntity<UserAccountInfoModel>(userinfos.ToJson());

            //获取数据
            int recordCount = 0;
            var result = _sys_departmentrepository.GetListsByPage(keyword, projectid, building, floorid, userinfo, pageindex, pagesize, out recordCount);
            var obj = new
            {
                rows = result.ToList(),
                total = recordCount
            };
            return Success("获取成功", obj);
        }

        /// <summary>
        /// 获取科室列表 - 下拉
        /// </summary>
        /// <param name="keyword"></param>
        /// <param name="projectid"></param>
        /// <param name="building"></param>
        /// <param name="floorid"></param>
        /// <returns></returns>
        [HttpGet("getlist")]
        public IActionResult GetListAsync(string keyword, string projectid, string building, string floorid)
        {
            string usercode = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
            //var userstr = _signTokenService.GetUserInfoAsync(usercode).Result;
            //var userinfo = userstr.ToJObject()["data"].ToString().ToObject<UserInfoModel>();
            
            var userinfos = _sys_user_accountRepository.GetUserInfo(usercode);
            var userinfo = JsonHelper.JsonToEntity<UserAccountInfoModel>(userinfos.ToJson());

            //获取数据
            var list = _sys_departmentrepository.GetLists(keyword, projectid, building, floorid, userinfo).ToList();
            var treeList = new List<TreeGridModel>();

            foreach (var item in list)
            {
                TreeGridModel treeModel = new TreeGridModel();
                bool hasChildren = list.Count(t => t.parent_id == item.id.ToString()) == 0 ? false : true;
                treeModel.id = item.id.ToString();
                treeModel.isLeaf = hasChildren;
                treeModel.parentId = item.parent_id;
                treeModel.expanded = hasChildren;
                treeModel.entityJson = item.ToJson();
                treeList.Add(treeModel);
            }
            var treeListJson = treeList.TreeGridJsonByParentId(null);
            return Content(treeList.TreeGridJsonByParentId(null));
            //return Success("获取成功", list.ToList());
        }


        /// <summary>
        /// 获取所有科室列表 - 树形下拉
        /// </summary>
        /// <returns></returns>
        [HttpGet("getlistdrop")]
        public async Task<IActionResult> GetListdrop(string projectid, string building, string floorid)
        {
            string usercode = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
            //var userstr = _signTokenService.GetUserInfoAsync(usercode).Result;
            //var userinfo = userstr.ToJObject()["data"].ToString().ToObject<UserInfoModel>();
            
            var userinfos = _sys_user_accountRepository.GetUserInfo(usercode);
            var userinfo = JsonHelper.JsonToEntity<UserAccountInfoModel>(userinfos.ToJson());

            var list = (await _sys_departmentrepository.Get(p => p.isdelete == 0)).ToList();

            if (!string.IsNullOrEmpty(projectid))
                list = list.Where(it => it.projectid == projectid).ToList();
            if (!string.IsNullOrEmpty(building))
                list = list.Where(it => it.building == building).ToList();
            if (!string.IsNullOrEmpty(floorid))
                list = list.Where(it => it.floorid == floorid).ToList();
            if (userinfo.isallproject == 0)
                list = list.Where(it => userinfo.projectlist.Contains(it.projectid)).ToList();
            return Success("获取成功", GetTreeList(list, null));
        }

        /// <summary>
        /// 循环获取树结构
        /// </summary>
        /// <param name="list"></param>
        /// <param name="pid"></param>
        /// <returns></returns>
        public object GetTreeList(List<Sys_Department> list, string depid)
        {
            var children = list.Where(p => p.parent_id == depid).Select(p => new
            {
                p.id,
                p.projectid,
                p.departmenname,
                p.sortnum,
                p.remark,
                children = GetTreeList(list, p.id)
            });

            return children;
        }

        /// <summary>
        /// 获取科室详情 by id
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet("getdetailes")]
        public async Task<IActionResult> GetDetailsAsync(string id)
        {
            if (string.IsNullOrEmpty(id))
                return Error("参数错误");
            var model = await _sys_departmentrepository.GetSingle(id);
            if (model != null)
            {
                var result = new
                {
                    id = model.id,
                    projectid = model.projectid,
                    building = model.building,
                    floorid = model.floorid,
                    departmenname = model.departmenname,
                    remark = model.remark,
                    telephone = model.telephone,
                    mobile = model.mobile,
                    email = model.email,
                    sortnum = model.sortnum,
                    createtime = model.createtime,
                };
                return Success("获取成功！", result);
            }
            return Error("获取失败");
        }

        #region 之前 - 不用部分
        ///// <summary>
        ///// 获取所有科室列表
        ///// </summary>
        ///// <returns></returns>
        //[HttpGet("getlistdrop")]
        //public async Task<IActionResult> GetListdrop(string projectid ,string floorid)
        //{
        //    //排序字段
        //    var sort = Builders<Sys_Department>.Sort.Descending("sortnum");
        //    var list = await _sys_departmentrepository.Get(null, null, sort);
        //    var redCount = await _sys_departmentrepository.CountAsync(null); //获取总数
        //    //根据条件查询集合
        //    var listfilter = new List<FilterDefinition<Sys_Department>>();
        //    listfilter.Add(Builders<Sys_Department>.Filter.Eq("isdelete", 0));
        //    //查询
        //    if (!string.IsNullOrEmpty(projectid))
        //        listfilter.Add(Builders<Sys_Department>.Filter.Where(s => s.projectid.Equals(projectid)));
        //    if (!string.IsNullOrEmpty(floorid))
        //        listfilter.Add(Builders<Sys_Department>.Filter.Where(s => s.floorid.Equals(floorid)));
        //    if (listfilter.Count > 0)
        //    {
        //        var filter = Builders<Sys_Department>.Filter.And(listfilter);
        //        list = await _sys_departmentrepository.Get(filter,null, sort);
        //    }
        //    //var list = await _sys_departmentrepository.Get(x => x.isdelete == 0);
        //    //var listmodel = new List<Sys_Department>();
        //    //foreach (var item in list)
        //    //{
        //    //    var model = new DropListDto();
        //    //    model.id = item.id;
        //    //    model.text = item.project_name;
        //    //    listmodel.Add(model);
        //    //}
        //    return Success("成功", list);
        //}

        ///// <summary>
        ///// 获取科室列表 by page
        ///// </summary>
        ///// <param name="keyword"></param>
        ///// <param name="stime"></param>
        ///// <param name="etime"></param>
        ///// <param name="pageindex"></param>
        ///// <param name="pagesize"></param>
        ///// <returns></returns>
        //[HttpGet("getlistbypage")]
        //public async Task<IActionResult> GetListByPageAsync(string keyword, int pageindex = 1, int pagesize = 10)
        //{
        //    #region 条件信息
        //    //排序字段
        //    var sort = Builders<Sys_Department>.Sort.Descending("sortnum");
        //    var list = await _sys_departmentrepository.GetByPage(null, pageindex, pagesize, sort);
        //    var redCount = await _sys_departmentrepository.CountAsync(null); //获取总数
        //    //根据条件查询集合
        //    var listfilter = new List<FilterDefinition<Sys_Department>>();
        //    //模糊查询
        //    if (!string.IsNullOrEmpty(keyword))
        //        listfilter.Add(Builders<Sys_Department>.Filter.Where(s => s.departmenname.Contains(keyword)));
        //    #endregion
        //    int recordCount = 0;
        //    if (listfilter.Count > 0)
        //    {
        //        var filter = Builders<Sys_Department>.Filter.And(listfilter);
        //        list = await _sys_departmentrepository.GetByPage(filter, pageindex, pagesize, sort);
        //        redCount = await _sys_departmentrepository.CountAsync(filter);   //获取总数
        //    }
        //    recordCount = int.Parse(redCount.ToString());

        //    var obj = new
        //    {
        //        rows = list,
        //        total = recordCount,
        //    };
        //    return Success("成功", obj);
        //    //return Content(obj.ToJson());
        //}

        ///// <summary>
        ///// 获取科室列表 by page - 关联查询
        ///// </summary>
        ///// <param name="keyword"></param>
        ///// <param name="stime"></param>
        ///// <param name="etime"></param>
        ///// <param name="pageindex"></param>
        ///// <param name="pagesize"></param>
        ///// <returns></returns>
        //[HttpGet("getlistsbypage")]
        //public IActionResult GetListsByPage(string keyword, string projectid, string floorid, int pageIndex = 1, int pageSize = 10)
        //{
        //    int recordCount = 0;
        //    var result = _sys_departmentrepository.GetListsByPage(keyword, projectid, floorid, pageIndex, pageSize, out recordCount);
        //    var obj = new
        //    {
        //        rows = result,
        //        total = recordCount,
        //    };
        //    return Success("获取成功", obj);
        //}

        ///// <summary>
        ///// 获取科室详情 by id
        ///// </summary>
        ///// <param name="id"></param>
        ///// <returns></returns>
        //[HttpGet("getdetailes")]
        //public async Task<IActionResult> GetDetailsAsync(string id)
        //{
        //    if (string.IsNullOrEmpty(id))
        //        return Error("参数错误");
        //    var model = await _sys_departmentrepository.GetSingle(id);
        //    if (model != null)
        //    {
        //        var result = new
        //        {
        //            id = model.id,
        //            projectid = model.projectid,
        //            floorid = model.floorid,
        //            departmenname = model.departmenname,
        //            sortnum = model.sortnum,
        //            remark = model.remark,
        //            telephone = model.telephone,
        //            mobile = model.mobile,
        //            elsephone = model.elsephone,
        //            email = model.email,
        //            createtime = model.createtime,
        //        };
        //        return Success("获取成功！", result);
        //    }
        //    return Error("获取失败");
        //}

        ///// <summary>
        ///// 获取项目管理详情 by id - 关联查询
        ///// </summary>
        ///// <param name="id"></param>
        ///// <returns></returns>
        //[HttpGet("getdetails")]
        //public IActionResult GetDetails(string id)
        //{
        //    if (string.IsNullOrEmpty(id))
        //        return Error("参数错误");
        //    var model = _sys_departmentrepository.GetDetails(id);
        //    if (model != null)
        //    {
        //        return Success("获取成功！", model);
        //    }
        //    return Error("获取失败");
        //}

        #endregion


        /// <summary>
        /// 添加科室
        /// </summary>
        /// <returns></returns>
        [HttpPost("add")]
        public async Task<IActionResult> AddAsync(string parentid, string projectid, string building, string floorid, string departmenname, int sortnum,string remark,string telephone,string mobile,string elsephone,string email)
        {
            string usercode = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
            if (string.IsNullOrEmpty(departmenname))
                return Error("科室名称不能为空");
            var model = new Sys_Department();
            model.parent_id = parentid;
            model.projectid = projectid;
            model.floorid = floorid;
            model.building = building;
            model.departmenname = departmenname;
            model.sortnum = sortnum;
            model.remark = remark;
            model.telephone = telephone;
            model.mobile = mobile;
            model.email = email;
            model.createtby = usercode;
            model.createtime = DateTime.Now.ToLocalTime();
            bool b = await _sys_departmentrepository.Add(model);
            if (b)
                return Success("添加成功");
            return Error("添加失败");
        }

        /// <summary>
        /// 修改科室信息
        /// </summary>
        /// <param name="id"></param>
        /// <param name="provincecode"></param>
        /// <param name="provincename"></param>
        /// <returns></returns>
        [HttpPost("update")]
        public async Task<IActionResult> UpdateAsync(string id, string parentid, string projectid, string building, string floorid, string departmenname,int sortnum, string remark, string telephone, string mobile, string elsephone, string email)
        {
            if (string.IsNullOrEmpty(id))
                return Error("参数错误");
            if (string.IsNullOrEmpty(departmenname))
                return Error("科室名称不能为空");

            var model = new Sys_Department();
            model = await _sys_departmentrepository.GetSingle(id);
            if (model == null)
                return Error("操作失败");
            model.parent_id = parentid;
            model.projectid = projectid;
            model.building = building;
            model.floorid = floorid;
            model.departmenname = departmenname;
            model.sortnum = sortnum;
            model.remark = remark;
            model.telephone = telephone;
            model.mobile = mobile;
            model.email = email;
            bool b = await _sys_departmentrepository.Update(model);
            if (b)
                return Success("保存成功");
            return Error("保存失败");
        }

        /// <summary>
        /// 删除科室信息 by ids
        /// </summary>
        /// <param name="ids">string[] id</param>
        /// <returns></returns>
        [HttpPost("delete")]
        public async Task<IActionResult> DeleteAsync(string[] ids)
        {
            string usercode = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
            var res = 0;
            if (ids != null && ids.Length > 0)
            {
                foreach (var item in ids)
                {
                    var modelSun = await _sys_departmentrepository.GetSingle(x=>x.parent_id == item);
                    if (modelSun != null)
                        return Error("删除失败，此栏目下有子级信息");
                    var ml = await _sys_departmentrepository.GetSingle(item);
                    ml.isdelete = -1;
                    ml.deleteby = usercode;
                    ml.deletetime = DateTime.Now.ToLocalTime();
                    if (_sys_departmentrepository.Update(ml).Result)
                        res += 1;
                }
                if (res == ids.Length)
                    return Success("删除成功");
                else if (res > 0 && res < ids.Length)
                    return Error("部分删除失败，请查看后重新操作");
                else
                    return Error("删除失败，请查看后重新操作");
            }
            else
                return Error("请选择要删除的记录");
        }
    }
}