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 MadRunFabric.Model;
using MongoDB.Driver;
using Microsoft.AspNetCore.Authorization;
using System.Security.Claims;
using Api.SignToken;
using Microsoft.Extensions.Configuration;

namespace ConfigurationApi.Controllers
{
    /// <summary>
    /// 楼层管理 - 例如：门诊楼10层
    /// </summary>
    //[Authorize]
    [ApiVersion("6.0")]
    [Produces("application/json")]
    [Route("api/[controller]")]
    public class FloorManageController : BaseController
    {
        private readonly ILogger<FloorManageController> _logger;
        private readonly IConfiguration _configuration;
        private readonly ISys_User_AccountRepository _sys_user_accountRepository;
        private readonly ISys_BuildingRepository _sys_buildingrepository;
        private readonly ISys_FloorRepository _sys_floorrepository;
        private readonly ISignTokenService _signTokenService;
        public FloorManageController(
            ILogger<FloorManageController> logger,
            IConfiguration configuration,
            ISys_User_AccountRepository sys_user_accountRepository,
            ISys_BuildingRepository sys_buildingrepository,
            ISys_FloorRepository sys_floorrepository,
            ISignTokenService signTokenService
            )
        {
            _logger = logger;
            _configuration = configuration;
            _sys_user_accountRepository = sys_user_accountRepository;
            _sys_buildingrepository = sys_buildingrepository;
            _sys_floorrepository = sys_floorrepository;
            _signTokenService = signTokenService;
        }

        #region 楼
        /// <summary>
        /// 获取所有楼列表
        /// </summary>
        /// <returns></returns>
        [HttpGet("getbuildlistdrop")]
        public async Task<IActionResult> GetBuildListdrop(string keyword, string projectid)
        {
            //排序字段
            var sort = Builders<Sys_Building>.Sort.Descending("sortnum");
            var list = await _sys_buildingrepository.Get(null, null, sort);
            //根据条件查询集合
            var listfilter = new List<FilterDefinition<Sys_Building>>();
            listfilter.Add(Builders<Sys_Building>.Filter.Eq("isdelete", 0));
            //查询
            if (!string.IsNullOrEmpty(projectid))
                listfilter.Add(Builders<Sys_Building>.Filter.Eq("projectid", projectid));
            if (!string.IsNullOrEmpty(keyword))
                listfilter.Add(Builders<Sys_Building>.Filter.Where(s => s.buildname.Contains(keyword)));
            var filter = Builders<Sys_Building>.Filter.And(listfilter);
            list = await _sys_buildingrepository.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>
        /// 获取楼列表 - 关联查询
        /// </summary>
        /// <returns></returns>
        [HttpGet("getbuildlistsbypage")]
        public IActionResult GetBuildListsByPage(string keyword, string projectid, int pageindex = 1, int pagesize = 10)
        {
            string rolecode = User.Claims.FirstOrDefault(c => c.Type == "RoleCode").Value;
            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_buildingrepository.GetBuildListsByPage(keyword, projectid, userinfo, 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("getbuilddetails")]
        public IActionResult GetBuildDetails(string id)
        {
            if (string.IsNullOrEmpty(id))
                return Error("参数错误");
            var model = _sys_buildingrepository.GetBuildDetails(id);
            if (model != null)
            {
                return Success("获取成功！", model);
            }
            return Error("获取失败");
        }
        /// <summary>
        /// 添加楼层
        /// </summary>
        /// <param name="floorname"></param>
        /// <param name="sortnum"></param>
        /// <param name="remark"></param>
        /// <returns></returns>
        [HttpPost("addbuild")]
        public async Task<IActionResult> AddBuildAsync(string projectid, string buildname, int sortnum, string remark)
        {
            string usercode = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
            if (string.IsNullOrEmpty(projectid))
                return Error("项目信息不能为空");
            if (string.IsNullOrEmpty(buildname))
                return Error("楼名称不能为空");
            var model = new Sys_Building();
            model.projectid = projectid;
            model.buildname = buildname;
            model.sortnum = sortnum;
            model.remark = remark;
            model.createtby = usercode;
            model.createtime = DateTime.Now.ToLocalTime();
            //model.projectid = "5aab6f580d26390eac2bdc82";
            //model.buildname = "1号楼";
            //model.sortnum = 1;
            //model.remark = "1号楼";
            //model.createtby = "8000";
            //model.createtime = DateTime.Now.ToLocalTime();
            bool b = await _sys_buildingrepository.Add(model);
            if (b)
                return Success("添加成功");
            return Error("添加失败");
        }

        /// <summary>
        /// 修改楼层信息
        /// </summary>
        /// <param name="id"></param>
        /// <param name="floorname"></param>
        /// <param name="sortnum"></param>
        /// <param name="remark"></param>
        /// <returns></returns>
        [HttpPost("updatebuild")]
        public async Task<IActionResult> UpdateBuildAsync(string id, string projectid, string buildname, int sortnum, string remark)
        {
            if (string.IsNullOrEmpty(id))
                return Error("参数错误");
            if (string.IsNullOrEmpty(projectid))
                return Error("项目信息不能为空");
            if (string.IsNullOrEmpty(buildname))
                return Error("楼名称不能为空");

            var model = new Sys_Building();
            model = await _sys_buildingrepository.GetSingle(id);
            if (model == null)
                return Error("操作失败");
            model.projectid = projectid;
            model.buildname = buildname;
            model.sortnum = sortnum;
            model.remark = remark;
            bool b = await _sys_buildingrepository.Update(model);
            if (b)
                return Success("保存成功");
            return Error("保存失败");
        }

        /// <summary>
        /// 删除楼层信息 by ids
        /// </summary>
        /// <param name="ids">string[] id</param>
        /// <returns></returns>
        [HttpPost("deletebuild")]
        public async Task<IActionResult> DeleteBuildAsync(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 ml = await _sys_buildingrepository.GetSingle(item);
                    ml.isdelete = -1;
                    ml.deleteby = usercode;
                    ml.deletetime = DateTime.Now.ToLocalTime();
                    if (_sys_buildingrepository.Update(ml).Result)
                    {
                        res += 1;
                        #region 批量删除 - 删对应的楼层信息信息
                        var imodel = new Sys_Floor();
                        Dictionary<string, string> dic = new Dictionary<string, string>();
                        dic.Add("isdelete", "1");
                        dic.Add("deleteby", usercode);
                        dic.Add("deletetime", DateTime.Now.ToLocalTime().ToLongDateString());
                        var list = new List<FilterDefinition<Sys_Floor>>();
                        var filterBuilder = Builders<Sys_Floor>.Filter;
                        list.Add(filterBuilder.Eq("projectid", item));
                        var filter = Builders<Sys_Floor>.Filter.And(list);
                        await _sys_floorrepository.UpdateManay(imodel, dic, filter);
                        #endregion
                    }
                }
                if (res == ids.Length)
                    return Success("删除成功");
                else if (res > 0 && res < ids.Length)
                    return Error("部分删除失败，请查看后重新操作");
                else
                    return Error("删除失败，请查看后重新操作");
            }
            else
                return Error("请选择要删除的记录");
        }
        #endregion

        #region 楼层
        /// <summary>
        /// 获取所有楼层列表
        /// </summary>
        /// <returns></returns>
        [HttpGet("getlistdrop")]
        public async Task<IActionResult> GetListdrop(string keyword, string buildid)
        {
            //排序字段
            var sort = Builders<Sys_Floor>.Sort.Descending("sortnum");
            var list = await _sys_floorrepository.Get(null, null, sort);
            var redCount = await _sys_floorrepository.CountAsync(null); //获取总数
            //根据条件查询集合
            var listfilter = new List<FilterDefinition<Sys_Floor>>();
            listfilter.Add(Builders<Sys_Floor>.Filter.Eq("isdelete", 0));
            //查询
            if (!string.IsNullOrEmpty(buildid))
                listfilter.Add(Builders<Sys_Floor>.Filter.Eq("buildid", buildid));
            if (!string.IsNullOrEmpty(keyword))
                listfilter.Add(Builders<Sys_Floor>.Filter.Where(s => s.floorname.Contains(keyword)));
            if (listfilter.Count > 0)
            {
                var filter = Builders<Sys_Floor>.Filter.And(listfilter);
                list = await _sys_floorrepository.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="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_Floor>.Sort.Descending("sortnum");
            var list = await _sys_floorrepository.GetByPage(null, pageindex, pagesize, sort);
            var redCount = await _sys_floorrepository.CountAsync(null); //获取总数
            //根据条件查询集合
            var listfilter = new List<FilterDefinition<Sys_Floor>>();
            //模糊查询
            if (!string.IsNullOrEmpty(keyword))
                listfilter.Add(Builders<Sys_Floor>.Filter.Where(s => s.floorname.Contains(keyword)));
            #endregion
            int recordCount = 0;
            if (listfilter.Count > 0)
            {
                var filter = Builders<Sys_Floor>.Filter.And(listfilter);
                list = await _sys_floorrepository.GetByPage(filter, pageindex, pagesize, sort);
                redCount = await _sys_floorrepository.CountAsync(filter);   //获取总数
            }
            recordCount = int.Parse(redCount.ToString());

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

        /// <summary>
        /// 获取楼层列表 - 关联查询
        /// </summary>
        /// <returns></returns>
        [HttpGet("getlistsbypage")]
        public IActionResult GetListsByPage(string keyword,string buildid, int pageindex = 1, int pagesize = 10)
        {
            int recordCount = 0;
            var result = _sys_floorrepository.GetListsByPage(keyword, buildid, 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_floorrepository.GetSingle(id);
            if (model != null)
            {
                var result = new
                {
                    id = model.id,
                    buildid = model.buildid,
                    sortnum = model.sortnum,
                    remark = model.remark,
                    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_floorrepository.GetDetails(id);
            if (model != null)
            {
                return Success("获取成功！", model);
            }
            return Error("获取失败");
        }
        
        /// <summary>
        /// 添加楼层
        /// </summary>
        /// <param name="floorname"></param>
        /// <param name="sortnum"></param>
        /// <param name="remark"></param>
        /// <returns></returns>
        [HttpPost("add")]
        public async Task<IActionResult> AddAsync(string buildid, string floorname, int sortnum, string remark)
        {
            string usercode = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
            if (string.IsNullOrEmpty(buildid))
                return Error("楼信息不能为空");
            if (string.IsNullOrEmpty(floorname))
                return Error("楼层名称不能为空");
            var model = new Sys_Floor();
            model.buildid = buildid;
            model.floorname = floorname;
            model.sortnum = sortnum;
            model.remark = remark;
            model.createtby = usercode;
            model.createtime = DateTime.Now.ToLocalTime();
            //model.buildid = "5ad04d0c13d2380c3c0d6637";
            //model.floorname = "10层";
            //model.sortnum = 1;
            //model.remark = "门诊楼10层";
            //model.createtby = "8000";
            //model.createtime = DateTime.Now.ToLocalTime();
            bool b = await _sys_floorrepository.Add(model);
            if (b)
                return Success("添加成功");
            return Error("添加失败");
        }

        /// <summary>
        /// 修改楼层信息
        /// </summary>
        /// <param name="id"></param>
        /// <param name="floorname"></param>
        /// <param name="sortnum"></param>
        /// <param name="remark"></param>
        /// <returns></returns>
        [HttpPost("update")]
        public async Task<IActionResult> UpdateAsync(string id, string buildid, string floorname, int sortnum, string remark)
        {
            if (string.IsNullOrEmpty(id))
                return Error("参数错误");
            if (string.IsNullOrEmpty(buildid))
                return Error("楼信息不能为空");
            if (string.IsNullOrEmpty(floorname))
                return Error("楼层名称不能为空");

            var model = new Sys_Floor();
            model = await _sys_floorrepository.GetSingle(id);
            if (model == null)
                return Error("操作失败");
            model.buildid = buildid;
            model.floorname = floorname;
            model.sortnum = sortnum;
            model.remark = remark;
            bool b = await _sys_floorrepository.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 ml = await _sys_floorrepository.GetSingle(item);

                    ml.isdelete = -1;
                    ml.deleteby = usercode;
                    ml.deletetime = DateTime.Now.ToLocalTime();
                    if (_sys_floorrepository.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("请选择要删除的记录");
        }
        #endregion


        /// <summary>
        /// 获取五级联动
        /// </summary>
        /// <param name="keyword"></param>
        /// <param name="buildid"></param>
        /// <returns></returns>
        [HttpGet("gettree")]
        public IActionResult GetTree()
        {
            var result = _sys_floorrepository.GetTree();
            return Success("成功", result);
        }
    }
}