/* =============================================
-- Author:		<Author,,zhangkun>
-- Create date: <Create Date,,20200609>
-- Description:	<Description,,商品 库存 商品类别相关操作）>
-- ============================================*/
using System;
using System.Collections.Generic;
using System.Common;
using System.Common.Helpers;
using System.Data;
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 Microsoft.Extensions.Configuration;
using SqlSugar;
using TVShoppingCallCenter_ZLJ.Controllers.Order;
using TVShoppingCallCenter_ZLJ.Models.Dtos;
using TVShoppingCallCenter_ZLJ.Models.Inputs;

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

        private readonly IBus_ProductRepository _productRepository;
        private readonly IBus_ProductClassRepository _productClassRepository;
        private readonly IBus_TagRepository _tagRepository;
        private readonly OrderFunctionController busOrderFunctionController;
        private readonly IConfiguration config;
        public ProductClassController(IConfiguration _config, OrderFunctionController _busOrderFunctionController, IBus_ProductRepository productRepository, IBus_ProductClassRepository productClassRepository, IBus_TagRepository tagRepository)
        {
            _productRepository = productRepository;
            _productClassRepository = productClassRepository;
            _tagRepository = tagRepository;
            busOrderFunctionController = _busOrderFunctionController;
            config = _config;
        }
        [AllowAnonymous]
        [HttpGet("/api/test")]
        public IActionResult Test()
        {
            return new JsonResult(new
            {
                Status = false,
                Message = "访问信息"
            });
        }
        #region 商品分类

        /// <summary>
        /// 新增商品分类
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("/api/product/addproductclass")]
        public async Task<IActionResult> AddProductClass(ProductClassInput input)
        {

            #region 验证 参数


            if (string.IsNullOrEmpty(input.ClassName))
                return Error("请输入分类名称");
            if (string.IsNullOrEmpty(input.ClassShortName))
                return Error("请输入分类简写");

            if (input.ClassName.Length>25)
                return Error("分类名称不宜超过25");
            if (input.ClassShortName.Length > 10)
                return Error("分类简写不宜超过10");
            #endregion

            if (await _productClassRepository.GetCount(a => a.F_ClassName == input.ClassName) > 0)
            {
                return Error("分类名称重复");
            }
            if (await _productClassRepository.GetCount(b => b.F_ClassShortName == input.ClassShortName) > 0)
            {
                return Error("分类简写重复");
            }
            if (input .ParentId>0)
            {
                if (await _productClassRepository.GetCount(b => b.F_ParentId == input.ParentId && b.F_Lock == 1) > 0)
                {
                    return Error("系统锁定分类不允许设置子类");
                }
            }
           


            T_Bus_ProductClass T_Bus_ProductClassModel = new T_Bus_ProductClass();
            if (input.ClassId != 0)
                T_Bus_ProductClassModel.F_ClassId = input.ClassId;

            T_Bus_ProductClassModel.F_ClassShortName = input.ClassShortName;
            T_Bus_ProductClassModel.F_ParentId = input.ParentId;
            T_Bus_ProductClassModel.F_Sort = input.Sort;
            T_Bus_ProductClassModel.F_ClassName = input.ClassName;
            T_Bus_ProductClassModel.F_UserName = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Name).Value;
            T_Bus_ProductClassModel.F_UserId = int.Parse(User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.PrimarySid).Value, 0);

            if (await _productClassRepository.Add(T_Bus_ProductClassModel) > 0)
            {
                return Success("新增商品分类成功");
            }
            else
            {
                return Error("新增分类失败,请重试！");
            }
        }


        /// <summary>
        /// 更新商品分类名称
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("/api/product/updateproductclass")]
        public async Task<IActionResult> UpdateProductClass(ProductClassInput input)
        {

            #region 验证 参数


            if (string.IsNullOrEmpty(input.ClassName))
                return Error("请输入分类名称");
            if (string.IsNullOrEmpty(input.ClassShortName))
                return Error("请输入分类简写");
            if (input.ClassId <= 0)
                return Error("缺少参数");

            #endregion

            if (await _productClassRepository.GetCount(q => q.F_ClassName == input.ClassName && q.F_ClassId != input.ClassId) > 0)
            {
                return Error("分类名称重复");
            }
            if (await _productClassRepository.GetCount(q => q.F_ClassShortName == input.ClassShortName && q.F_ClassId != input.ClassId) > 0)
            {
                return Error("分类简写重复");
            }
            if (input.ParentId>0)
            {
                if (await _productClassRepository.GetCount(b => b.F_ParentId == input.ParentId && b.F_Lock == 1
             ) > 0)
                {
                    return Error("系统锁定分类不允许设置子类");
                }
            }

            T_Bus_ProductClass T_Bus_ProductClassModel = await _productClassRepository.GetSingle(a => a.F_ClassId == input.ClassId);

            T_Bus_ProductClassModel.F_ClassName = input.ClassName;
            T_Bus_ProductClassModel.F_ClassShortName = input.ClassShortName;
            T_Bus_ProductClassModel.F_Sort = input.Sort;

            T_Bus_ProductClassModel.F_UserName =UserLogin.UserName;
            T_Bus_ProductClassModel.F_UserId = UserLogin.UserId.ObjToInt();

            if (T_Bus_ProductClassModel.F_Lock == 1)
            {
                return Error("系统锁定分类不能自己修改");
            }
            if (await _productClassRepository.Update(T_Bus_ProductClassModel))
            {
                return Success("保存商品分类成功");
            }
            else
            {
                return Error("保存分类失败,请重试！");
            }
        }

        /// <summary>
        /// 删除商品分类
        /// </summary>
        /// <param name="ids">格式   ,1,2,3,4,</param>
        /// <returns></returns>
        [HttpPost("/api/product/deleteproductclass")]
        public async Task<IActionResult> DeleteProductClass(string ids)
        {
            if (string.IsNullOrEmpty(ids))
                return Error("请输入删除id");
            ids = ids.Trim(',');
            if (string.IsNullOrEmpty(ids))
                return Error("请输入删除id");
            string[] idsarry = ids.Split(',');

            if (await _productRepository.GetCount(q => idsarry.Contains(q.F_ClassId.ToString())) > 0)
            {
                return Error("请先删除分类下商品");
            }
            if (await _productClassRepository.Delete(q => idsarry.Contains(q.F_ClassId.ToString())&&q.F_Lock==0))
            {
                return Success("删除商品分类成功");
            }
            else
            {
                return Error("删除分类失败,请重试！");
            }
        }

        /// <summary>
        /// 查询商品分类
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("/api/product/getproductclass")]
        public async Task<IActionResult> ProductClassList(ProductClassInput input)
        {

            #region  拼接条件

            Expression<Func<T_Bus_ProductClass, bool>> eq = a => a.F_ClassId > 0;

            if (input.ClassId > 0)
                eq = eq.And(a => a.F_ClassId == input.ClassId);
            if (!string.IsNullOrEmpty(input.ClassName))
            {
                eq = eq.And(a => a.F_ClassName.Contains(input.ClassName));
            }
            if (!string.IsNullOrEmpty(input.ClassShortName))
            {
                eq = eq.And(a => a.F_ClassShortName.Contains(input.ClassShortName));
            }
            if (input.ParentId >= 0)
            {
                eq = eq.And(a => a.F_ParentId == input.ParentId);
            }

            #endregion

            List<T_Bus_ProductClass> productClasselist = await _productClassRepository.GetListALL(eq, o => o.F_Sort, OrderByType.Asc);
            var treeList = new List<TreeModel>();
            foreach (T_Bus_ProductClass item in productClasselist)
            {
                TreeModel treeModel = new TreeModel();
                treeModel.id = item.F_ClassId;
                treeModel.iconcls = item.F_Sort.ToString();
                treeModel.text = item.F_ClassName;
                treeModel.parentid = item.F_ParentId;
                treeModel.code = item.F_ClassShortName;
                treeList.Add(treeModel);
            }
            return Success("获取商品分类树成功", treeList.TreeRecursion(0));
        }


        #endregion

        



        
    }
}