using System;
using System.Collections.Generic;
using System.Common;
using System.IRepositories;
using System.Linq;
using System.Linq.Expressions;
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.Customer
{
    [Authorize]
    [Produces("application/json")]
    [Route("api/[controller]")]
    public class VipLabelInfoController : BaseController
    {
        private readonly ICus_VipLabelInfoRepository _cus_vip_labelinfoRepository;
        private readonly ISys_UserAccountRepository _sys_user_accountRepository;

        public VipLabelInfoController(ICus_VipLabelInfoRepository cus_vip_labelinfoRepository, ISys_UserAccountRepository sys_user_accountRepository)
        {
            _cus_vip_labelinfoRepository = cus_vip_labelinfoRepository;
            _sys_user_accountRepository = sys_user_accountRepository;
        }

        // GET: /<controller>/
        public IActionResult Index()
        {
            return Success("成功");
        }

        /// <summary>
        /// 获取会员标签列表分页
        /// </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 = 20)
        {
            List<IConditionalModel> conModels = new List<IConditionalModel>();
            #region 条件筛选
            conModels.Add(new ConditionalModel() { FieldName = "F_State", ConditionalType = ConditionalType.Equal, FieldValue = ((int)EnumDelState.Enabled).ToString() });

            
            if (!string.IsNullOrEmpty(keyword))
                conModels.Add(new ConditionalCollections()
                {
                    ConditionalList = new List<KeyValuePair<WhereType, ConditionalModel>>()
                    {
                        new  KeyValuePair<WhereType, ConditionalModel>(WhereType.And, new ConditionalModel() { FieldName = "F_Name", ConditionalType = ConditionalType.Like, FieldValue = keyword }),
                        new  KeyValuePair<WhereType, ConditionalModel>( WhereType.Or , new ConditionalModel() { FieldName = "F_Note", ConditionalType = ConditionalType.Like, FieldValue = keyword })

                    }
                });
            #endregion
            int recordCount = 0;
            var list = await _cus_vip_labelinfoRepository.GetListByPage(conModels, new MyPageModel() { PageIndex = pageindex, PageSize = pagesize, PageCount = recordCount });
            var obj = new
            {
                state = "success",
                message = "成功",
                rows = list,
                total = recordCount,
            };
            return Content(obj.ToJson());
        }

        /// <summary>
        /// 获取会员标签信息详情
        /// </summary>
        /// <param name="id">id</param>
        /// <returns></returns>
        [HttpGet("getdetails")]
        public async Task<IActionResult> GetDetailsAsync(int id)
        {
            if (id <= 0)
                return Error("参数错误");

            var model = await _cus_vip_labelinfoRepository.GetSingle(x => x.F_ID == id);
            if (model == null)
            {
                return Error("获取失败");
            }
            return Success("获取成功！", model);
        }

        /// <summary>
        /// 添加会员标签
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("add")]
        public async Task<IActionResult> AddAsync(VipLabelInfoInput input)
        {
            if (string.IsNullOrEmpty(input.name))
                return Error("请输入标签名称");
            
            var model = new T_Cus_VipLabelInfo();
            model.F_Name = input.name;
            //model.F_Type = input.type;
            //model.F_Kind = input.kind;
            model.F_LabelColor = input.labelcolor ;
            model.F_FontColor = input.fontcolor ;
            model.F_State = (int)EnumDelState.Enabled;
            model.F_Note = input.note;
            model.F_CreateBy = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
            model.F_CreateOn = DateTime.Now;

            if (await _cus_vip_labelinfoRepository.GetCount(x =>  x.F_Name == input.name&&x.F_State== (int)EnumDelState.Enabled) > 0)
            {
                return Error("添加失败，存在相同标签信息");
            }
            var res = await _cus_vip_labelinfoRepository.Add(model);
            if (res > 0)
            {
                return Success("添加成功");
            }
            else
            {
                return Error("添加失败");
            }
        }

        /// <summary>
        /// 修改会员标签信息
        /// </summary>
        [HttpPost("update")]
        public async Task<IActionResult> UpdateAsync(VipLabelInfoInput input)
        {
            if (string.IsNullOrEmpty(input.name))
                return Error("请输入名字");
            

            var model = await _cus_vip_labelinfoRepository.GetSingle(x => x.F_ID == input.id);
            if (model == null)
                return Error("操作失败");
            if (await _cus_vip_labelinfoRepository.GetCount(x => x.F_Name == input.name && x.F_State == (int)EnumDelState.Enabled
            && x.F_Name!= model .F_Name ) > 0)
            {
                return Error("修改失败，存在相同标签信息");
            }
            model.F_Name = input.name;
            //model.F_Type = input.type;
            //model.F_Kind = input.kind;
            model.F_LabelColor = input.labelcolor;
            model.F_FontColor = input.fontcolor;
            model.F_Note = input.note;
            bool b = await _cus_vip_labelinfoRepository.Update(model);
            if (b)
                return Success("修改成功");
            return Error("修改失败");
        }

        /// <summary>
        /// 删除会员标签信息 by ids
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        [HttpPost("delete")]
        public async Task<IActionResult> Remove(int[] ids)
        {
            var res = 0;
            if (ids != null && ids.Length > 0)
            {
                foreach (var item in ids)
                {
                    var ml = await _cus_vip_labelinfoRepository.GetSingle(x => x.F_ID == item);
                    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 (_cus_vip_labelinfoRepository.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("请选择要删除的记录");
        }

        /// <summary>
        /// 查询标签分类
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("getlist")]
        public async Task<IActionResult> GetList()
        {

            #region  拼接条件

            Expression<Func<T_Cus_VipLabelInfo, bool>> eq = a => a.F_State== (int)EnumDelState.Enabled;          
            #endregion
            List<T_Cus_VipLabelInfo> list = await _cus_vip_labelinfoRepository.GetListALL(eq);

            return Success("成功", list);

        }
    }
}
