/* =============================================
-- Author:		<Author,,zhangkun>
-- Create date: <Create Date,,20200616>
-- Description:	<Description,,商品标签相关操作）>
-- ============================================*/
using System;
using System.Collections.Generic;
using System.Common;
using System.Common.Helpers;
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.Http;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;
using TVShoppingCallCenter_ZLJ.Models.Dtos;
using TVShoppingCallCenter_ZLJ.Models.Inputs;

namespace TVShoppingCallCenter_ZLJ.Controllers.Product
{
    [Route("api/[controller]")]
    public class TagController : BaseController
    {


        private readonly IBus_TagRepository _tagRepository;
        private readonly ISys_MarketingRepository bus_MarketingRepository;
        public TagController(IBus_TagRepository tagRepository, ISys_MarketingRepository _bus_MarketingRepository)
        {

            _tagRepository = tagRepository;
            bus_MarketingRepository = _bus_MarketingRepository;
        }
       
             [HttpPost("/api/test")]
          public async Task<IActionResult> TEST(TagInput input)
        {
            return Success(UserLogin.UserName);
        }
        #region 标签操作

        /// <summary>
        /// 新增标签
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("addtag")]
        public async Task<IActionResult> AddTag(TagInput input)
        {

            #region 验证 参数


            if (string.IsNullOrEmpty(input.TagName))
                return Error("请输入分类名称");
            if(input.TagName.Length>15)
                return Error("标签长度不能超过15");
            if (input.CLass < 1)
                return Error("请输入标签分类");
            if (input.Type < 0)
                input.Type = 1;
            if (input.CLass == 3 && !input.TagName.StartsWith("."))
            {
                input.TagName = "." + input.TagName;
            }
            else if(input.CLass != 3)
            {
                input.TagName = input.TagName.Replace(".","");
            }
            #endregion
            Expression<Func<T_Bus_Tag, bool>> eq = a => a.F_TagName == input.TagName;

            if (await _tagRepository.GetCount(eq.And(b => b.F_Type == input.Type)) > 0)
            {
                return Error("标签名称重复");
            }
            T_Bus_Tag T_Bus_TagModel = new T_Bus_Tag();

            T_Bus_TagModel.F_Type = input.Type;
            T_Bus_TagModel.F_TagName = input.TagName;
            T_Bus_TagModel.F_Sort = 100;
            T_Bus_TagModel.F_CLass = input.CLass;
            T_Bus_TagModel.F_UserName = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Name).Value;
            T_Bus_TagModel.F_UserId = int.Parse(User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.PrimarySid).Value, 0);
            T_Bus_TagModel.F_UpdateTime = DateTime.Now;

            if (await _tagRepository.AddReturnCount(T_Bus_TagModel))
            {
                return Success("新增标签成功");
            }
            else
            {
                return Success("新增标签失败");//这个方法返回的不是影响记录行数
            }
        }


        /// <summary>
        /// 更新标签
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("updatetag")]
        public async Task<IActionResult> UpdateTag(TagInput input)
        {

            #region 验证 参数


            if (string.IsNullOrEmpty(input.TagName))
                return Error("请输入原标签名称");
            if (string.IsNullOrEmpty(input.NewTagName))
                return Error("请输入标签名称");
            if (input.Type < 0)
                input.Type = 1;
            if (input.Sort < 1)
                return Error("请输入标签排序序号");
            if (input.CLass == 3 && !input.NewTagName.StartsWith("."))
            {
                input.NewTagName = "." + input.NewTagName;
            }
            else if (input.CLass != 3)
            {
                input.NewTagName = input.NewTagName.Replace(".", "");
            }
            #endregion
            if (await _tagRepository.GetCount(x => x.F_TagName == input.NewTagName 
                   && x.F_Type == input.Type && x.F_TagName!= input.TagName) > 0)
            {
                return Error("标签名称重复");
            }
            Expression<Func<T_Bus_Tag, bool>> eq = a =>( a.F_TagName == input.TagName);

            T_Bus_Tag T_Bus_TagModel = await _tagRepository.GetSingle(eq.And(b => b.F_Type == input.Type));
            //除非某固定权限 定之后再加
            if (T_Bus_TagModel.F_CLass == 1)
            {
                return Error("系统标签不能更改");
            }

           
            T_Bus_TagModel.F_TagName = input.NewTagName;
            T_Bus_TagModel.F_Sort = input.Sort;


            T_Bus_TagModel.F_UserName = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Name).Value;
            T_Bus_TagModel.F_UserId = int.Parse(User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.PrimarySid).Value, 0);
            T_Bus_TagModel.F_UpdateTime = DateTime.Now;

            
            if (await _tagRepository.Update(q => new T_Bus_Tag() { F_TagName = input.NewTagName },q=>q.F_TagName== input.TagName&& q.F_Type==1))
            {
                    return Success("更新标签成功。");
            }
            return Error("更新标签失败");

        }

        /// <summary>
        /// 删除标签
        /// </summary>
        /// <param name="tagName"></param>
        /// <returns></returns>
        [HttpPost("deletetag")]
        public async Task<IActionResult> DeleteTag(TagInput input)
        {


            if (string.IsNullOrEmpty(input.TagName))
                return Error("请选择标签");
            if (input.CLass < 2)
                return Error("系统标签不能删除");


            Expression<Func<T_Bus_Tag, bool>> eq = a => a.F_TagName == input.TagName;
            //非系统标签可以随意删除，与商品没有关联
            if (await _tagRepository.Delete(eq.And(b => b.F_Type == input.Type)))
            {
                return Success("删除标签成功");
            }
            else
            {
                return Error("删除标签失败,请重试！");
            }
        }

        /// <summary>
        /// 查询符合条件所有标签
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("gettagall")]
        public async Task<IActionResult> GetTagAll(TagInput input)
        {

            #region  拼接条件

            Expression<Func<T_Bus_Tag, bool>> eq = a => a.F_Type == 1;

            //if (input.Type > 0)
            //    eq = eq.And(a => a.F_Type == input.Type);
            if (input.CLass > 0)
            {
                eq = eq.And(a => a.F_CLass == input.CLass);
            }
            if (!string.IsNullOrEmpty(input.TagName))
            {
                eq = eq.And(a => a.F_TagName.Contains(input.TagName));
            }


            #endregion


            List<T_Bus_Tag> list = await _tagRepository.GetListALL(eq, c => c.F_Sort, OrderByType.Asc);

            return Success("成功", list);

        }

        /// <summary>
        /// 获取没有参加活动的 商品活动标签
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("getacttag")]
        public async Task<IActionResult> GetActTag(TagInput input)
        {

            #region  拼接条件

            Expression<Func<T_Bus_Tag, bool>> eq = a => a.F_Type == 1;

            eq = eq.And(a => a.F_CLass == 3);

            if (!string.IsNullOrEmpty(input.TagName))
            {
                eq = eq.And(a => a.F_TagName.Contains(input.TagName));
            }


            #endregion


            List<T_Bus_Tag> list = await _tagRepository.GetListALL(eq, c => c.F_Sort, OrderByType.Asc);
            List<T_Bus_Tag> listres = new List<T_Bus_Tag>();
            if (list != null && list.Count > 0)
            {
                foreach (T_Bus_Tag t in list)
                {
                    int count = await bus_MarketingRepository.GetCount(q =>q.F_IsDelete==0&& (","+ q.F_Commodity + ",")==("," + t.F_TagName + ",") );
                    if (count == 0)
                    {
                        listres.Add(t);
                    }
                }
                
            }
            return Success("成功", listres);

        }

        #endregion

    }
}