//————————————
//des：产品管理类
//author:zhangkun
//addtime:2020-06-10
//————————————
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.Http;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;
using TVShoppingCallCenter_ZLJ.Models.Inputs;

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

        private readonly IBus_ProductRepository _productRepository;
        private readonly IBus_ProductClassRepository _productClassRepository;
        public ProductController(IBus_ProductRepository productRepository, IBus_ProductClassRepository productClassRepository)
        {
            _productRepository = productRepository;
            _productClassRepository = productClassRepository;
        }
        [AllowAnonymous]
        [HttpGet("/api/test")]
        public IActionResult Test()
        {
            return new JsonResult(new
            {
                Status = false,
                Message = "访问信息"
            });
        }
        #region 产品分类

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

            #region 验证 参数


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

            #endregion
            Expression<Func<T_Bus_ProductClass, bool>> eq = a => a.F_ClassName == input.ClassName;
            if (await _productClassRepository.GetCount(eq.Or(b => b.F_ClassShortName == input.ClassShortName)) > 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 = 10000;
            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("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
            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_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.Update(T_Bus_ProductClassModel))
            {
                return Success("保存商品分类成功");
            }
            else
            {
                return Error("保存分类失败,请重试！");
            }
        }

        /// <summary>
        /// 删除商品分类
        /// </summary>
        /// <param name="ids">格式   ,1,2,3,4,</param>
        /// <returns></returns>
        [HttpPost("deleteproductclass")]
        public async Task<IActionResult> DeleteProductClass(string ids)
        {


            if (string.IsNullOrEmpty(ids))
                return Error("请输入删除id");
            if (ids.Replace(",", "") == "")
                return Error("请输入删除id");

            //删除的时候  分类下有商品怎么处理  暂未处理  后续根据需求处理  可以指定规则，分类下没有产品才可以删除
            if (await _productClassRepository.Delete(a => ids.Contains("," + a.F_ClassId.ToString() + ",")))
            {
                return Success("删除商品分类成功");
            }
            else
            {
                return Error("删除分类失败,请重试！");
            }
        }

        /// <summary>
        /// 查询商品分类
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("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> list = await _productClassRepository.GetListALL(eq);

            return Success("成功", list);

        }


        #endregion

        #region 产品操作
        /// <summary>
        /// 新增商品 库存只通过两种方式变动 1 （我们下订单后，对方库存发别的地儿）对方库存变动回调我们，我们更新相关产品库存  2  我们定时去拿库存统一更新
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("addproduct")]
        public async Task<IActionResult> AddProduct(ProductInput input)
        {

            #region 验证 参数

            if (input.ClassId == 0)
                return Error("请选择分类名称");
            if (string.IsNullOrEmpty(input.ProductName))
                return Error("请输入产品名称");
            if (string.IsNullOrEmpty(input.ProductShortName))
                return Error("请输入产品简写");
            if (string.IsNullOrEmpty(input.ProductNumber))
                return Error("请输入产品条形码");
            if (string.IsNullOrEmpty(input.ClassName))
                return Error("请选择分类名称");
            if (input.MarketPrice <= 0)
                return Error("请输入正确市场价");
            if (input.MemberPrice <= 0)
                return Error("请输入正确会员价");
            if (input.SpecialPrice <= 0)
                return Error("请输入正确特惠价");
            if (input.ProductId <= 0)
                return Error("请输入正确产品编码");
            if (string.IsNullOrEmpty(input.PinyinShort))
                return Error("请输入正确拼音简码");
            #endregion
            Expression<Func<T_Bus_Product, bool>> eq = a => a.F_ProductName == input.ProductName;
            eq = eq.Or(b => b.F_PinyinShort == input.PinyinShort);
            eq = eq.Or(b => b.F_ProductId == input.ProductId);
            eq = eq.Or(b => b.F_ProductShortName == input.ProductShortName);
            if (await _productRepository.GetCount(eq) > 0)
            {
                return Error("名称/条形码/简称 有重复");
            }

            T_Bus_Product T_Bus_ProductModel = new T_Bus_Product();


            T_Bus_ProductModel.F_ProductId = input.ProductId;
            T_Bus_ProductModel.F_ProductName = input.ProductName;
            T_Bus_ProductModel.F_ProductShortName = input.ProductShortName;
            T_Bus_ProductModel.F_ProductNumber = input.ProductNumber;
            T_Bus_ProductModel.F_PinyinShort = input.PinyinShort;

            T_Bus_ProductModel.F_ClassId = input.ClassId;
            T_Bus_ProductModel.F_ClassName = input.ClassName;


            T_Bus_ProductModel.F_MarketPrice = input.MarketPrice;
            T_Bus_ProductModel.F_MemberPrice = input.MemberPrice;
            T_Bus_ProductModel.F_SpecialPrice = input.SpecialPrice;
            T_Bus_ProductModel.F_Integral = input.Integral;

            T_Bus_ProductModel.F_Address = input.Address;
            T_Bus_ProductModel.F_Des = input.Des;
            T_Bus_ProductModel.F_Factory = input.Factory;
            T_Bus_ProductModel.F_Supplier = input.Supplier;
            T_Bus_ProductModel.F_IsDelete = 1;

            T_Bus_ProductModel.F_IsSale = input.IsSale = input.OnSaleBegin < DateTime.Now;
            T_Bus_ProductModel.F_Weight = input.Weight;
            if (input.OnSaleBegin != null)
            { T_Bus_ProductModel.F_OnSaleBegin = input.OnSaleBegin.GetValueOrDefault().ToString("yyyy-MM-dd 00:00:01").ObjToDate(); }
            if (input.OnSaleEnd != null)
            { T_Bus_ProductModel.F_OnSaleEnd = input.OnSaleEnd.GetValueOrDefault().ToString("yyyy-MM-dd 23:59:59").ObjToDate(); }



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


            if (await _productRepository.AddStrong(T_Bus_ProductModel, true) == 0)
            {
                return Success("新增商品成功");
            }
            else
            {
                return Error("新增商品失败,请重试！");
            }
        }

        /// <summary>
        /// 修改商品 库存只通过两种方式变动 1 （我们下订单后，对方库存发别的地儿）对方库存变动回调我们，我们更新相关产品库存  2  我们定时去拿库存统一更新
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("updateproduct")]
        public async Task<IActionResult> UpdateProduct(ProductInput input)
        {

            #region 验证 参数

            if (input.ClassId == 0)
                return Error("请选择分类名称");
            if (string.IsNullOrEmpty(input.ProductName))
                return Error("请输入产品名称");
            if (string.IsNullOrEmpty(input.ProductShortName))
                return Error("请输入产品简写");
            if (string.IsNullOrEmpty(input.ProductNumber))
                return Error("请输入产品条形码");
            if (string.IsNullOrEmpty(input.ClassName))
                return Error("请选择分类名称");
            if (input.MarketPrice <= 0)
                return Error("请输入正确市场价");
            if (input.MemberPrice <= 0)
                return Error("请输入正确会员价");
            if (input.SpecialPrice <= 0)
                return Error("请输入正确特惠价");
            if (input.ProductId <= 0)
                return Error("产品ID不能修改");
            if (string.IsNullOrEmpty(input.PinyinShort))
                return Error("请输入正确拼音简码");
            #endregion

            T_Bus_Product T_Bus_ProductModel = await _productRepository.GetSingle(a => a.F_ProductId == input.ProductId);

            if (T_Bus_ProductModel == null)
                return Error("如需新添加，请点击新增按钮，此记录不存在");

            T_Bus_ProductModel.F_ProductName = input.ProductName;
            T_Bus_ProductModel.F_ProductShortName = input.ProductShortName;
            T_Bus_ProductModel.F_ProductNumber = input.ProductNumber;
            T_Bus_ProductModel.F_PinyinShort = input.PinyinShort;

            T_Bus_ProductModel.F_ClassId = input.ClassId;
            T_Bus_ProductModel.F_ClassName = input.ClassName;


            T_Bus_ProductModel.F_MarketPrice = input.MarketPrice;
            T_Bus_ProductModel.F_MemberPrice = input.MemberPrice;
            T_Bus_ProductModel.F_SpecialPrice = input.SpecialPrice;
            T_Bus_ProductModel.F_Integral = input.Integral;

            T_Bus_ProductModel.F_Address = input.Address;
            T_Bus_ProductModel.F_Des = input.Des;
            T_Bus_ProductModel.F_Factory = input.Factory;
            T_Bus_ProductModel.F_Supplier = input.Supplier;

            T_Bus_ProductModel.F_IsSale = input.IsSale = input.OnSaleBegin < DateTime.Now;//此状态暂不启用 以时间判断
            T_Bus_ProductModel.F_Weight = input.Weight;
            T_Bus_ProductModel.F_OnSaleBegin = input.OnSaleBegin ?? input.OnSaleBegin.GetValueOrDefault().ToString("yyyy-MM-dd 00:00:01").ObjToDate();
            T_Bus_ProductModel.F_OnSaleEnd = input.OnSaleEnd ?? input.OnSaleEnd.GetValueOrDefault().ToString("yyyy-MM-dd 23:59:59").ObjToDate();



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


            if (await _productRepository.Update(T_Bus_ProductModel))
            {
                return Success("保存商品成功");
            }
            else
            {
                return Error("保存商品失败,请重试！");
            }
        }

        /// <summary>
        /// 删除商品 硬删除
        /// </summary>
        /// <param name="ids">格式 ,1,2,3,</param>
        /// <returns></returns>
        [HttpPost("deleteproductbyids")]
        public async Task<IActionResult> DeleteProductByIds(string ids)
        {

            #region 验证 参数

            if (string.IsNullOrEmpty(ids))
                return Error("请输入删除id");
            if (ids.Replace(",", "") == "")
                return Error("请输入删除id");
            #endregion

            if (await _productRepository.Delete(a => ids.Contains("," + a.F_ProductId.ToString() + ",")))
            {
                return Success("删除商品成功");
            }
            else
            {
                return Error("删除商品失败,请重试！");
            }
        }
        /// <summary>
        /// 删除商品 软删除
        /// </summary>
        /// <param name="ids">格式 ,1,2,3,</param>
        /// <returns></returns>
        [HttpPost("delproductbyids")]
        public async Task<IActionResult> DelProduct(string ids)
        {

            #region 验证 参数

            if (string.IsNullOrEmpty(ids))
                return Error("请输入删除id");
            if (ids.Replace(",", "") == "")
                return Error("请输入删除id");
            #endregion
            List<T_Bus_Product> listmodel = await _productRepository.GetListALL(a => ids.Contains("," + a.F_ProductId.ToString() + ","));


            //此处如果不是批量删除，最好事务
            for (int i = 0; i < listmodel.Count; i++)
            {
                listmodel[i].F_IsDelete = 1;
            }

            if (await _productRepository.UpdateList(listmodel))
                return Success("删除商品成功");
            else
                return Success("删除商品失败");
        }


        /// <summary>
        /// 查询商品
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("getproduct")]
        public async Task<IActionResult> ProductList(ProductInput input)
        {

            #region  拼接条件
            if (input.Limit <= 0)
            {
                input.Limit = 100000;
            }
            Expression<Func<T_Bus_Product, bool>> eq = a => a.F_IsDelete == 1;

            if (input.ClassId > 0)
                eq = eq.And(a => a.F_ProductId == input.ProductId);
            if (!string.IsNullOrEmpty(input.ClassName))
            {
                eq = eq.And(a => a.F_ClassName.Contains(input.ClassName));
                // eq.Or(a => a.F_ClassShortName.Contains(input.F_ClassName));
            }
            //产品名/标题
            if (!string.IsNullOrEmpty(input.ProductName))
            {
                eq = eq.And(a => a.F_ProductName.Contains(input.ProductName));
            }
            //指定分类
            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.PinyinShort))
            {
                eq = eq.And(a => a.F_PinyinShort == input.PinyinShort);
            }

            //条形码
            if (!string.IsNullOrEmpty(input.ProductNumber))
            {
                eq = eq.And(a => a.F_ProductNumber == input.ProductNumber);
            }
            //简称/编码/副标题
            if (!string.IsNullOrEmpty(input.ProductShortName))
            {
                eq = eq.And(a => a.F_ProductShortName == input.ProductShortName);
            }
            //标签
            if (!string.IsNullOrEmpty(input.Tag))
            {
                eq.And(a => a.F_Tag.Contains(input.Tag));
            }

            #endregion

            RefAsync<int> count = 0;
            var list = await _productRepository.GetListByPage(eq, new MyPageModel() { PageIndex = 1, PageSize = input.Limit, PageCount = count });

            return Success("成功", list);

        }
        /// <summary>
        /// 分页获取产品列表
        /// </summary>
        /// <param name="input">筛选字段</param>
        /// <param name="pagesize"></param>
        /// <param name="pageindex"></param>
        /// <returns></returns>
        [HttpPost("getlistbypage")]
        public async Task<IActionResult> GetListByPage([FromBody]ProductInput input, int pagesize, int pageindex)
        {
            List<IConditionalModel> conModels = new List<IConditionalModel>();
            #region 条件筛选


            conModels.Add(new ConditionalModel() { FieldName = "F_IsDelete", ConditionalType = ConditionalType.Equal, FieldValue = ((int)EnumDelState.Enabled).ToString() });

            if (input.ProductId > 0)
            {
                conModels.Add(new ConditionalModel() { FieldName = "F_ProductId", ConditionalType = ConditionalType.Equal, FieldValue = input.ProductId.ToString() });
            }
            //指定分类
            if (input.ClassId > 0)
            {
                conModels.Add(new ConditionalModel() { FieldName = "F_ClassId", ConditionalType = ConditionalType.Equal, FieldValue = input.ClassId.ToString() });
            }

            if (!string.IsNullOrEmpty(input.ClassName))
            {
                conModels.Add(new ConditionalModel() { FieldName = "F_ClassName", ConditionalType = ConditionalType.Like, FieldValue = input.ClassName });

            }
            //产品名/标题
            if (!string.IsNullOrEmpty(input.ProductName))
            {
                conModels.Add(new ConditionalModel() { FieldName = "F_ProductName", ConditionalType = ConditionalType.Like, FieldValue = input.ProductName });
            }
            //分类名称
            if (!string.IsNullOrEmpty(input.ClassName))
            {
                conModels.Add(new ConditionalModel() { FieldName = "F_ClassName", ConditionalType = ConditionalType.Like, FieldValue = input.ClassName });
            }
            //拼音简码
            if (!string.IsNullOrEmpty(input.PinyinShort))
            {
                conModels.Add(new ConditionalModel() { FieldName = "F_PinyinShort", ConditionalType = ConditionalType.Equal, FieldValue = input.PinyinShort });
            }

            //条形码
            if (!string.IsNullOrEmpty(input.ProductNumber))
            {
                conModels.Add(new ConditionalModel() { FieldName = "F_ProductNumber", ConditionalType = ConditionalType.Equal, FieldValue = input.ProductNumber });
            }
            //简称/编码/副标题
            if (!string.IsNullOrEmpty(input.ProductShortName))
            {
                conModels.Add(new ConditionalModel() { FieldName = "F_ProductShortName", ConditionalType = ConditionalType.Like, FieldValue = input.ProductShortName });
            }
            //标签
            if (!string.IsNullOrEmpty(input.Tag))
            {
                conModels.Add(new ConditionalModel() { FieldName = "F_Tag", ConditionalType = ConditionalType.Equal, FieldValue = input.Tag });
            }


            #endregion
            int recordCount =0;
            var list = await _productRepository.GetListByPage(conModels, new MyPageModel() { PageIndex = pageindex, PageSize = pagesize, PageCount = recordCount });

             return Success("成功", list);
        }


        #endregion

        #region 库存对接

        /// <summary>
        /// 更新库存（对方库存变化  入库 出库 时做更新）  订单发货时，对面库存 出库要对应订单，以便跟踪
        /// </summary>
        /// <param name="input">目前暂定Id唯一标识更新如果不方便可以以F_ProductName，如果那边更好操作，顺序上这边先有产品的话可以以id操作，或者以条形码操作</param>
        /// 基类BaseController继承的不是[ApiController]，也没有加[ApiController]头标  所以用到json序列化传值 和测试工具raw传值必须加[FromBody]
        /// <returns></returns>
        [HttpPost("updatestock")]
        public async Task<IActionResult> UpdateStock([FromBody]List<ProductInput> input)
        {

            #region 验证 参数
            if (input.Count <= 0)
                return Error("参数缺失，没有数据");
            List<T_Bus_Product> listmodel = new List<T_Bus_Product>();

            foreach (ProductInput m in input)
            {
                // return Success(m.F_ProductId.ToString() + ":" + m.F_Stock.ToString());
                //if (!string.IsNullOrEmpty(m.ProductName))
                //    return Error("参数缺失产品名称");
                if (m.ProductId <= 0)
                    return Error("参数缺失产品id");
                if (m.Stock < 0)
                    return Error("参数缺失库存");
                T_Bus_Product model = await _productRepository.GetSingle(a => a.F_ProductId == m.ProductId);
                if (model != null)
                {
                    model.F_Stock = m.Stock;
                    listmodel.Add(model);
                }
            }

            #endregion
            //此字段更新单独字段
            if (await _productRepository.UpdateListToColumns(listmodel, it => new { it.F_Stock }))
                return Success("更新库存成功");
            else
                return Success("更新库存失败");
        }


        #endregion
    }
}