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.Authorization;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;
using TVShoppingCallCenter_ZLJ.Models.Inputs;

namespace TVShoppingCallCenter_ZLJ.Controllers.System
{
    [Authorize]
    [Produces("application/json")]
    [Route("api/[controller]")]
    public class DictionaryController : BaseController
    {
        private readonly ISys_DictionaryValueRepository _sys_dictionaryRepository;
        public DictionaryController(ISys_DictionaryValueRepository sys_dictionaryRepository)
        {
            _sys_dictionaryRepository = sys_dictionaryRepository;
        }

        
        /// <summary>
        /// 获取字典下拉列表
        /// </summary>
        /// <returns></returns>
        [HttpGet("getlistdrop")]
        public async Task<IActionResult> GetListDropAsync(string code, bool isleaf = false)
        {
            List<IConditionalModel> conModels = new List<IConditionalModel>();
            #region 条件筛选
            conModels.Add(new ConditionalModel() { FieldName = "F_State", ConditionalType = ConditionalType.Equal, FieldValue = ((int)EnumDelState.Enabled).ToString() });
            conModels.Add(new ConditionalModel() { FieldName = "F_IsLeaf", ConditionalType = ConditionalType.Equal, FieldValue = isleaf.ToString() });
            if (!string.IsNullOrEmpty(code))
                conModels.Add(new ConditionalModel() { FieldName = "F_ValueCode", ConditionalType = ConditionalType.Equal, FieldValue = code });
            #endregion

            var list = await _sys_dictionaryRepository.GetListALL(conModels, "F_Sort Asc");
            var result = list.Select(x => new {
                x.F_ValueId,
                x.F_ValueCode,
                x.F_Value,
                x.F_Sort
            });
            return Success("获取下拉数据成功", result);
        }

        /// <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,string code, bool isleaf = false, int pageindex = 1, int pagesize = 20)
        {
            List<IConditionalModel> conModels = new List<IConditionalModel>();
            #region 条件筛选
            conModels.Add(new ConditionalModel() { FieldName = "F_State", ConditionalType = ConditionalType.Equal, FieldValue = ((int)EnumDelState.Enabled).ToString() });
            conModels.Add(new ConditionalModel() { FieldName = "F_IsLeaf", ConditionalType = ConditionalType.Equal, FieldValue = isleaf==true?"1":"0" });
            if(!string.IsNullOrEmpty(code))
                conModels.Add(new ConditionalModel() { FieldName = "F_ValueCode", ConditionalType = ConditionalType.Equal, FieldValue = code });
            if (!string.IsNullOrEmpty(keyword))
            {
                conModels.Add(new ConditionalCollections()
                {
                    ConditionalList = new List<KeyValuePair<WhereType, ConditionalModel>>()
                    {
                        new  KeyValuePair<WhereType, ConditionalModel>(WhereType.And, new ConditionalModel() { FieldName = "F_ValueCode", ConditionalType = ConditionalType.Like, FieldValue = keyword }),
                        new  KeyValuePair<WhereType, ConditionalModel>( WhereType.Or , new ConditionalModel() { FieldName = "F_Value", ConditionalType = ConditionalType.Like, FieldValue = keyword })
                    }
                });
            }
            #endregion

            int recordCount = 0;
            var list = await _sys_dictionaryRepository.GetListByPage(conModels, new MyPageModel() { PageIndex = pageindex, PageSize = pagesize, PageCount = recordCount }, "F_Sort desc");

            return Success("获取列表成功", list);
        }

        /// <summary>
        /// 获取字典详情 by id
        /// </summary>
        /// <param name="id">id</param>
        /// <returns></returns>
        [HttpGet("getdetails")]
        public async Task<IActionResult> GetDetailsAsync(int id,bool isleaf = false)
        {
            if (id <= 0)
                return Error("参数错误");
            var model = await _sys_dictionaryRepository.GetSingle(x => x.F_ValueId == id && x.F_State == (int)EnumDelState.Enabled && x.F_IsLeaf == isleaf);
            if (model == null)
                return Success("获取失败", null);
            var result = new
            {
                id=model.F_ValueId,
                code=model.F_ValueCode,
                name=model.F_Value,
                des=model.F_Remark,
                sort=model.F_Sort,
                pid=model.F_ParentId,
                isleaf=model.F_IsLeaf
            };
            return Success("获取成功！", result);
        }
        /// <summary>
        /// 获取字段详情 by name
        /// </summary>
        /// <param name="name"></param>
        /// <param name="isleaf"></param>
        /// <returns></returns>
        [HttpGet("getdetailsbyname")]
        public async Task<IActionResult> GetDetailsByNameAsync(string name, bool isleaf = false)
        {
            if (string.IsNullOrEmpty(name))
                return Error("参数错误");

            var model = await _sys_dictionaryRepository.GetSingle(x => x.F_Value == name && x.F_State == (int)EnumDelState.Enabled && x.F_IsLeaf == isleaf);
            if (model == null)
                return Success("获取失败", null);
            var result = new
            {
                id = model.F_ValueId,
                code = model.F_ValueCode,
                name = model.F_Value,
                des = model.F_Remark,
                sort = model.F_Sort,
                pid = model.F_ParentId,
                isleaf = model.F_IsLeaf
            };
            return Success("获取成功！", result);
        }

        /// <summary>
        /// 添加字典信息
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("add")]
        public async Task<IActionResult> AddAsync(DictionaryInput input)
        {
            if (string.IsNullOrEmpty(input.code))
                return Error("字典标识不能为空");
            if (string.IsNullOrEmpty(input.name))
                return Error("字典名称不能为空");
            if (input.isleaf)
            {
                long n = await _sys_dictionaryRepository.GetCount(x => x.F_State == (int)EnumDelState.Enabled && x.F_ValueCode == input.code && x.F_Value==input.name && x.F_IsLeaf == input.isleaf);
                if (n > 0)
                    return Error("字典名称已存在");
            }
            else
            {
                long n = await _sys_dictionaryRepository.GetCount(x => x.F_State == (int)EnumDelState.Enabled && x.F_ValueCode == input.code && x.F_IsLeaf == input.isleaf);
                if (n > 0)
                    return Error("字典标识已存在");
            }
            var model = new T_Sys_DictionaryValue();
            model.F_ValueCode = input.code;
            model.F_Value = input.name;
            model.F_IsLeaf = input.isleaf;
            if(input.isleaf)
            {
                model.F_ParentCode = input.code;
            }
            model.F_ParentId = input.pid;
            model.F_Remark = input.describe;
            model.F_Sort = input.sort;
            model.F_State = (int)EnumDelState.Enabled;
            model.F_CreateOn = DateTime.Now;
            model.F_CreateBy = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
            int b = await _sys_dictionaryRepository.Add(model);
            if (b > 0)
                return Success("字典添加成功");
            else
                return Error("字典添加失败");
        }

        /// <summary>
        /// 修改字典信息
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("update")]
        public async Task<IActionResult> UpdateAsync(DictionaryInput input)
        {
            if (string.IsNullOrEmpty(input.code))
                return Error("字典标识不能为空");
            if (string.IsNullOrEmpty(input.name))
                return Error("字典名称不能为空");
            if (input.id <= 0)
                return Error("参数错误");
            var model = new T_Sys_DictionaryValue();
            model = await _sys_dictionaryRepository.GetSingle(x => x.F_ValueId == input.id && x.F_State == (int)EnumDelState.Enabled);
            if (model == null)
                return Error("操作失败");
            model.F_Value = input.name;
            model.F_Sort = input.sort;
            model.F_Remark = input.describe;

            model.F_LastModifyOn = DateTime.Now;
            model.F_LastModifyBy = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
            bool b = await _sys_dictionaryRepository.Update(model);
            if (b)
                return Success("字典修改成功");
            else
                return Error("字典修改失败");
        }

        /// <summary>
        /// 删除字典信息 by ids
        /// </summary>
        /// <param name="ids">string[] id</param>
        /// <returns></returns>
        [HttpPost("delete")]
        public async Task<IActionResult> DeleteAsync(int[] ids)
        {
            int num = 0;
            if (ids == null && ids.Length <= 0)
                return Error("请选择要删除的记录");
            var leafcount = await _sys_dictionaryRepository.GetCount(x => x.F_State == (int)EnumDelState.Enabled && ids.Contains(x.F_ParentId.Value));
            if (leafcount > 0)
                return Error("请先清理子节点");
            foreach (var item in ids)
            {
                var model = await _sys_dictionaryRepository.GetSingle(x => x.F_ValueId == item);
                model.F_State = (int)EnumDelState.Delete;
                model.F_DeleteOn = DateTime.Now;
                model.F_DeleteBy = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
                if (await _sys_dictionaryRepository.Update(model))
                    num += 1;
            }
            if (num == ids.Length)
                return Success("删除成功");
            if (num > 0 && num < ids.Length)
                return Error("部分删除失败，请查看后重新操作");
            return Error("删除失败，请查看后重新操作");
        }
    }
}