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 ConfigurationApi.Models.Input;
using Microsoft.AspNetCore.Authorization;
using MadRunFabric.Model;

namespace ConfigurationApi.Controllers
{
    /// <summary>
    /// 字典，字典项管理
    /// </summary>
    [Authorize]
    [ApiVersion("6.0")]
    [Produces("application/json")]
    [Route("api/[controller]")]
    public class DictionaryController : BaseController
    {
        private readonly ILogger<DictionaryController> _logger;
        private readonly ISys_DictionaryBaseRepository _sys_dictionarybaserepository;
        private readonly ISys_DictionaryValueRepository _sys_dictionaryValuerepository;
        public DictionaryController(
            ILogger<DictionaryController> logger,
            ISys_DictionaryBaseRepository sys_dictionarybaserepository,
            ISys_DictionaryValueRepository sys_dictionaryValuerepository
            )
        {
            _logger = logger;
            _sys_dictionarybaserepository = sys_dictionarybaserepository;
            _sys_dictionaryValuerepository = sys_dictionaryValuerepository;
        }

        #region 字典
        /// <summary>
        /// 获取字典下拉列表
        /// </summary>
        /// <returns></returns>
        [HttpGet("getlistdrop")]
        public async Task<IActionResult> GetListDropAsync()
        {
            var list = await _sys_dictionarybaserepository.Get(x => x.statetype);
            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> GetListsByPageAsync(string keyword, int pageindex = 1, int pagesize = 10)
        {
            #region 条件信息
            ////排序字段
            var sort = Builders<Sys_DictionaryBase>.Sort.Descending("sort");
            var list = await _sys_dictionarybaserepository.GetByPage(null, pageindex, pagesize, sort);
            var redCount = await _sys_dictionarybaserepository.CountAsync(null); //获取总数
            //根据条件查询集合
            var listfilter = new List<FilterDefinition<Sys_DictionaryBase>>();
            listfilter.Add(Builders<Sys_DictionaryBase>.Filter.Eq("statetype", true));
            //模糊查询
            if (!string.IsNullOrEmpty(keyword))
                listfilter.Add(Builders<Sys_DictionaryBase>.Filter.Where(s => s.dictionarycode.Contains(keyword) || s.dictionaryname.Contains(keyword)));
            #endregion

            int recordCount = 0;
            if (listfilter.Count > 0)
            {
                var filter = Builders<Sys_DictionaryBase>.Filter.And(listfilter);
                list = await _sys_dictionarybaserepository.GetByPage(filter, pageindex, pagesize, sort);
                redCount = await _sys_dictionarybaserepository.CountAsync(filter);   //获取总数
            }
            recordCount = int.Parse(redCount.ToString());

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

        /// <summary>
        /// 获取字典详情 by id
        /// </summary>
        /// <param name="id">id</param>
        /// <returns></returns>
        [HttpGet("getdetailes")]
        public async Task<IActionResult> GetDetailsAsync(string id)
        {
            if (string.IsNullOrEmpty(id))
                return Error("参数错误");

            var model = await _sys_dictionarybaserepository.GetSingle(id);
            if (model == null)
                return Success("获取失败", null);
            var result = new
            {
                id = model.id,
                dictionarycode = model.dictionarycode,
                dictionaryname = model.dictionaryname,
                sort = model.sort,
                describe = model.describe,
                statetype = model.statetype,
            };
            return Success("获取成功！", result);
        }

        /// <summary>
        /// 添加字典信息
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("add")]
        public async Task<IActionResult> AddAsync(DictionaryBaseInput input)
        {
            if (string.IsNullOrEmpty(input.dictionarycode))
                return Error("字典标志不能为空");
            if (string.IsNullOrEmpty(input.dictionaryname))
                return Error("字典名称不能为空");
            long n = await _sys_dictionarybaserepository.Count(x => x.dictionarycode == input.dictionarycode&&x.statetype==true);
            if (n > 0)
                return Error("字典标志已存在");
            var model = new Sys_DictionaryBase();
            model.dictionarycode = input.dictionarycode;
            model.dictionaryname = input.dictionaryname;
            model.sort = input.sort;
            model.describe = input.describe;
            model.statetype = true;
            
            //var model = new Sys_DictionaryBase()
            //{
            //    dictionarycode = "BXJB",
            //    dictionaryname = "报修级别",
            //    sort = 1,
            //    describe = "",
            //    statetype = true,
            //};
            bool b = await _sys_dictionarybaserepository.Add(model);
            if (b)
                return Success("字典添加成功");
            return Error("字典添加失败");
        }

        /// <summary>
        /// 修改字典信息
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("update")]
        public async Task<IActionResult> UpdateAsync(DictionaryBaseInput input)
        {
            if (string.IsNullOrEmpty(input.dictionarycode))
                return Error("字典标志不能为空");
            if (string.IsNullOrEmpty(input.dictionaryname))
                return Error("字典名称不能为空");
            if (string.IsNullOrEmpty(input.id))
                return Error("参数错误");
            var model = new Sys_DictionaryBase();
            model = await _sys_dictionarybaserepository.GetSingle(input.id);
            if (model == null)
                return Error("操作失败");
            //model.dictionarycode = input.dictionarycode;
            model.dictionaryname = input.dictionaryname;
            model.sort = input.sort;
            model.describe = input.describe;
            //model.statetype = true;
            bool b = await _sys_dictionarybaserepository.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)
        {
            int num = 0;
            if (ids == null && ids.Length <= 0)
                return Error("请选择要删除的记录");
            foreach (var item in ids)
            {
                var model = await _sys_dictionarybaserepository.GetSingle(item);
                model.statetype = false;
                if (await _sys_dictionarybaserepository.Update(model))
                    num += 1;
            }
            if (num == ids.Length)
                return Success("删除成功");
            if (num > 0 && num < ids.Length)
                return Error("部分删除失败，请查看后重新操作");
            return Error("删除失败，请查看后重新操作");
        }
        #endregion

        #region 字典项
        /// <summary>
        /// 获取字典下拉列表
        /// </summary>
        /// <returns></returns>
        [HttpGet("getdicvaluelistdrop")]
        public async Task<IActionResult> GetDicValueListDropAsync(string code,string projectname)
        {
            if (string.IsNullOrEmpty(code))
                return Success("获取全部数据成功", null);   //return Error("参数错误");
            var list = await _sys_dictionaryValuerepository.Get(x => x.statetype == true && x.dictionarycode == code);
            if (!string.IsNullOrEmpty(projectname))
                list = list.Where(x => x.projectname == projectname);
            return Success("获取全部数据成功", list);
        }

        /// <summary>
        /// 获取字典项列表 by page
        /// </summary>
        /// <param name="keyword"></param>
        /// <param name="pageindex"></param>
        /// <param name="pagesize"></param>
        /// <returns></returns>
        [HttpGet("getdicvaluelistbypage")]
        public async Task<IActionResult> GetDicValueListsByPageAsync(string keyword, string dictionarycode, int pageindex = 1, int pagesize = 10)
        {
            #region 条件信息
            ////排序字段
            var sort = Builders<Sys_DictionaryValue>.Sort.Ascending("sort");
            var list = await _sys_dictionaryValuerepository.GetByPage(null, pageindex, pagesize, sort);
            var redCount = await _sys_dictionaryValuerepository.CountAsync(null); //获取总数
            //根据条件查询集合
            var listfilter = new List<FilterDefinition<Sys_DictionaryValue>>();
            listfilter.Add(Builders<Sys_DictionaryValue>.Filter.Eq("statetype", true));
            //模糊查询
            if (!string.IsNullOrEmpty(dictionarycode))
            listfilter.Add(Builders<Sys_DictionaryValue>.Filter.Eq("dictionarycode", dictionarycode));
            if (!string.IsNullOrEmpty(keyword))
                listfilter.Add(Builders<Sys_DictionaryValue>.Filter.Where(s => s.dictionarycode.Contains(keyword) || s.name.Contains(keyword)));
            #endregion

            int recordCount = 0;
            if (listfilter.Count > 0)
            {
                var filter = Builders<Sys_DictionaryValue>.Filter.And(listfilter);
                list = await _sys_dictionaryValuerepository.GetByPage(filter, pageindex, pagesize, sort);
                redCount = await _sys_dictionaryValuerepository.CountAsync(filter);   //获取总数
            }
            recordCount = int.Parse(redCount.ToString());

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

        /// <summary>
        /// 获取字典详情 by id
        /// </summary>
        /// <param name="id">id</param>
        /// <returns></returns>
        [HttpGet("getdicvaluedetailes")]
        public async Task<IActionResult> GetDicValueDetailsAsync(string id)
        {
            if (string.IsNullOrEmpty(id))
                return Error("参数错误");

            var model = await _sys_dictionaryValuerepository.GetSingle(id);
            if (model == null)
                return Success("获取失败", null);
            var result = new
            {
                id = model.id,
                dictionarycode = model.dictionarycode,
                valuecode = model.valuecode,
                name = model.name,
                sort = model.sort,
                describe = model.describe,
                statetype = model.statetype,
                projectname=model .projectname,
                system_image=model.system_image
            };
            return Success("获取成功！", result);
        }

        /// <summary>
        /// 添加字典信息
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("adddicvalue")]
        public async Task<IActionResult> AddDicValueAsync(DictionaryValueInput input)
        {
            if (string.IsNullOrEmpty(input.dictionarycode))
                return Error("字典标志不能为空");
            if (string.IsNullOrEmpty(input.name))
                return Error("字典项名称不能为空");
            var model = new Sys_DictionaryValue();
            //model.id = input.id;
            model.dictionarycode = input.dictionarycode;
            model.valuecode = input.valuecode;
            model.name = input.name;
            model.sort = input.sort;
            model.describe = input.describe;
            model.statetype = true;
            model.projectname = input.projectname;
            if (input.system_image != null)
            {
                model.system_image = input.system_image;
            }
            else
            {
                model.system_image = new List<FileBaseModel>();
            }
            //var model = new Sys_DictionaryValue()
            //{
            //    dictionarycode = "BXJB",
            //    valuecode = "",
            //    name = "一般请求",
            //    sort = 1,
            //    describe = "",
            //    statetype = true,
            //};
            bool b = await _sys_dictionaryValuerepository.Add(model);
            if (b)
                return Success("字典添加成功");
            return Error("字典添加失败");
        }

        /// <summary>
        /// 修改字典信息
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("updatedicvalue")]
        public async Task<IActionResult> UpdateDicValueAsync(DictionaryValueInput input)
        {
            if (string.IsNullOrEmpty(input.dictionarycode))
                return Error("字典标志不能为空");
            if (string.IsNullOrEmpty(input.name))
                return Error("字典项名称不能为空");
            if (string.IsNullOrEmpty(input.id))
                return Error("参数错误");
            var model = new Sys_DictionaryValue();
            model = await _sys_dictionaryValuerepository.GetSingle(input.id);
            if (model == null)
                return Error("操作失败");
            //model.dictionarycode = input.dictionarycode;
            model.name = input.name;
            model.sort = input.sort;
            model.describe = input.describe;
            model.projectname = input.projectname;
            if (input.system_image != null)
            {
                model.system_image = input.system_image;
            }
            else
            {
                model.system_image = new List<FileBaseModel>();
            }
            //model.statetype = true;
            bool b = await _sys_dictionaryValuerepository.Update(model);
            if (b)
                return Success("字典添加成功");
            return Error("字典添加失败");
        }

        /// <summary>
        /// 删除字典项信息 by ids
        /// </summary>
        /// <param name="ids">string[] id</param>
        /// <returns></returns>
        [HttpPost("deletedicvalue")]
        public async Task<IActionResult> DeleteDicValueAsync(string[] ids)
        {
            int num = 0;
            if (ids == null && ids.Length <= 0)
                return Error("请选择要删除的记录");
            foreach (var item in ids)
            {
                var model = await _sys_dictionaryValuerepository.GetSingle(item);
                model.statetype = false;
                if (await _sys_dictionaryValuerepository.Update(model))
                    num += 1;
            }
            if (num == ids.Length)
                return Success("删除成功");
            if (num > 0 && num < ids.Length)
                return Error("部分删除失败，请查看后重新操作");
            return Error("删除失败，请查看后重新操作");
        }


        /// <summary>
        /// 获取字典详情 by id
        /// </summary>
        /// <param name="id">id</param>
        /// <returns></returns>
        [HttpGet("getdetailesbyname")]
        public async Task<IActionResult> GetDetailsByNameAsync(string name)
        {
            if (string.IsNullOrEmpty(name))
                return Error("参数错误");

            var model = await _sys_dictionaryValuerepository.GetSingle(x => x.name == name);
            if (model == null)
                return Success("获取失败", null);
            var result = new
            {
                id = model.id,
                dictionarycode = model.dictionarycode,
                valuecode = model.valuecode,
                name = model.name,
                sort = model.sort,
                describe = model.describe,
                statetype = model.statetype,
                projectname = model.projectname,
                system_image = model.system_image
            };
            return Success("获取成功！", result);
        }
        #endregion

    }
}