using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Mall.Common.API;
using Mall.Model.Extend.Product;
using Mall.Model.Extend.Property;
using Mall.Module.Product;
using Mall.Module.Property;
using Mall.WebApi.Filter;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;

namespace Mall.WebApi.Controllers.Property
{
    [Route("api/[controller]/[action]")]
    [ApiExceptionFilter]
    [ApiController]
    [EnableCors("AllowCors")]

    public class WarehouseOutController : BaseController
    {

        private readonly WarehouseOutModule warehouseOutModule = new WarehouseOutModule();
        private readonly OrderModule orderModule = new OrderModule();
        private readonly PropertyModule propertyModule = new PropertyModule();

        /// <summary>
        /// 获取出库申请列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetApplyPageList()
        {
            var parms = RequestParm;
            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(parms.msg.ToString());
            RB_WarehouseOut_Apply_Extend demodel = JsonConvert.DeserializeObject<RB_WarehouseOut_Apply_Extend>(parms.msg.ToString());

            demodel.TenantId = parms.TenantId;
            demodel.MallBaseId = parms.MallBaseId;
            var list = warehouseOutModule.GetApplyPageList(pagelist.pageIndex, pagelist.pageSize, out long count, demodel);
            pagelist.count = Convert.ToInt32(count);
            pagelist.pageData = list.Select(x => new
            {
                x.ApplyStatus,
                x.CreateBy,
                x.ExamineReason,
                x.ID,
                x.MallBaseId,
                x.MallBaseName,
                x.TenantId,
                x.TenantName,
                x.OutNo,
                x.Delivered,
                x.NotOutStock
            });
            return ApiResult.Success("", pagelist);
        }



        /// <summary>
        /// 根据商品id获取物料规格信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetSuppliesMaterialList()
        {
            var parms = RequestParm;
            //  var materialList = propertyModule.GetSuppliesMaterialList(new RB_Supplies_Material_Extend { GoodsIds = goodsIds, RB_Group_Id = requestParm.ERPGroupId, TenantId = requestParm.TenantId, MallBaseId = requestParm.MallBaseId });
            RB_Supplies_Material_Extend demodel = JsonConvert.DeserializeObject<RB_Supplies_Material_Extend>(parms.msg.ToString());
            demodel.TenantId = parms.TenantId;
            demodel.MallBaseId = parms.MallBaseId;
            demodel.RB_Group_Id = parms.ERPGroupId;
            var list = propertyModule.GetSuppliesMaterialList(demodel);
            return ApiResult.Success("", list);
        }


        /// <summary>
        /// 提交出库申请
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetWarehouseOutApply()
        {
            var requestParm = RequestParm;
            RB_WarehouseOut_Apply_Extend demodel = JsonConvert.DeserializeObject<RB_WarehouseOut_Apply_Extend>(requestParm.msg.ToString());

            if (requestParm.EmpId <= 0)
            {
                return ApiResult.ParamIsNull("请传递参数");
            }
            if (requestParm.ERPEmpId <= 0)
            {
                return ApiResult.ParamIsNull("请传递参数");
            }

            if (demodel.WarehouseOutGoodsList == null || !demodel.WarehouseOutGoodsList.Any())
            {
                return ApiResult.ParamIsNull("请选择商品");
            }
            foreach (var item in demodel.WarehouseOutGoodsList)
            {
                if (item.OrderGoodsId <= 0)
                {
                    return ApiResult.ParamIsNull("订单商品id未传递");
                }
            }

            //根据订单商品id查询商品信息
            var orderGoodsIds = string.Join(",", demodel.WarehouseOutGoodsList.Select(x => x.OrderGoodsId));

            var orderGoodsList = orderModule.GetOrderGoodsList(new Model.Extend.Product.RB_Goods_OrderDetail_Extend { IsOut = demodel.IsOut, TenantId = requestParm.TenantId, MallBaseId = requestParm.MallBaseId, IdList = demodel.WarehouseOutGoodsList.Select(x => x.OrderGoodsId).ToList() });
            if (demodel.WarehouseOutGoodsList.GroupBy(x => x.OrderGoodsId).Count() != orderGoodsList.Count)
            {
                List<int> chajiList = demodel.WarehouseOutGoodsList.Select(x => x.OrderGoodsId).Except(orderGoodsList.Select(x => x.Id)).ToList();
                string msg = "";
                foreach (var item in chajiList)
                {
                    msg += orderGoodsList.Where(x => x.Id == item).FirstOrDefault()?.OrderNo + ",";
                }
                if (!string.IsNullOrWhiteSpace(msg))
                {
                    msg = msg.TrimEnd(',');
                }
                return ApiResult.Failed("订单号：" + msg + "的商品已出库/已取消");
            }
            if (demodel.IsOut == 0)
            {
                //判断商品是否出库中
                var oldOutGoods = warehouseOutModule.GetWarehouseOutListByIds(new RB_WarehouseOut_Goods_Extend { OrderGoodsIds = String.Join(",", demodel.WarehouseOutGoodsList.Select(x => x.OrderGoodsId)), TenantId = requestParm.TenantId, MallBaseId = requestParm.MallBaseId });
                if (oldOutGoods != null && oldOutGoods.Any())
                {

                    string msg = "";
                    foreach (var item in oldOutGoods)
                    {
                        msg += orderGoodsList.Where(x => x.Id == item.OrderGoodsId).FirstOrDefault()?.OrderNo + ",";
                    }
                    if (!string.IsNullOrWhiteSpace(msg))
                    {
                        msg = msg.TrimEnd(',');
                    }
                    return ApiResult.Failed("订单号：" + msg + "的商品已申请出库,请勿重复申请");
                }
            }


            //获取商品的出库规格物料信息
            var goodsIds = string.Join(",", demodel.WarehouseOutGoodsList.Select(x => x.NewGoodsId));
            // var materialList = propertyModule.GetSuppliesMaterialList(new RB_Supplies_Material_Extend { GoodsIds = goodsIds, RB_Group_Id = requestParm.ERPGroupId, TenantId = requestParm.TenantId, MallBaseId = requestParm.MallBaseId });
            var materialList = propertyModule.GetHaveInventory(new RB_Supplies_Material_Extend { GoodsIds = goodsIds, RB_Group_Id = requestParm.ERPGroupId, TenantId = requestParm.TenantId, MallBaseId = requestParm.MallBaseId });
            foreach (var item in demodel.WarehouseOutGoodsList)
            {
                if (item.NewNumber <= 0)
                {
                    return ApiResult.Failed("出库商品数量不能小于0");
                }
                var orderGoodsDetailModel = orderGoodsList.Where(x => x.Id == item.OrderGoodsId).FirstOrDefault();
                if (item.NewSpecificationSort != item.SpecificationSort)//修改了规格的判断新规格是否在物料中存在
                {
                    var oldmaterialList = materialList.Where(x => x.GoodsId == item.NewGoodsId && x.SpecificationKey == item.NewSpecificationSort);

                    var materialModel = oldmaterialList.FirstOrDefault();

                    var orderGoodsDetail = orderGoodsList.Where(x => x.Id == item.OrderGoodsId).FirstOrDefault();
                    if (oldmaterialList == null || !oldmaterialList.Any() || materialModel== null )
                    {
                        return ApiResult.Failed("订单号：" + orderGoodsDetail?.OrderNo + "的商品：" + orderGoodsDetail?.GoodsName + "不存在物料请先同步");
                    }

                    if (oldmaterialList != null && (oldmaterialList.Sum(x => x.InventoryNum ?? 0)) <= 0)
                    {
                        return ApiResult.Failed("订单号：" + orderGoodsDetail?.OrderNo + "的商品：" + orderGoodsDetail?.GoodsName + "库存不足");
                    }
                    item.NewSpecificationSort = materialModel.SpecificationKey;
                    item.NewSpecification = materialModel.SpecificationName;
                }
                else//没有就直接等于订单的规格和数量
                {
                    item.NewSpecificationSort = orderGoodsDetailModel.SpecificationSort;
                    item.NewNumber = orderGoodsDetailModel.Number.Value;
                    item.NewSpecification = orderGoodsDetailModel.Specification;
                }
                if (orderGoodsDetailModel != null)
                {
                    item.TenantId = orderGoodsDetailModel.TenantId;
                    item.MallBaseId = orderGoodsDetailModel.MallBaseId;
                    item.SpecificationSort = orderGoodsDetailModel.SpecificationSort;
                    item.OrderId = orderGoodsDetailModel.OrderId.Value;
                    item.OrderNo = orderGoodsDetailModel.OrderNo;
                    item.GoodsName = orderGoodsDetailModel.GoodsName;
                    item.Specification = orderGoodsDetailModel.Specification;
                    item.Number = orderGoodsDetailModel.Number;
                    item.CostMoney = orderGoodsDetailModel.CostMoney;
                    item.ProductCode = orderGoodsDetailModel.ProductCode;
                    item.GoodsId = orderGoodsDetailModel.GoodsId.Value;
                    item.Status = 0;
                    item.IsOut = 0;
                }
            }
            if (demodel.ID == 0)
            {
                demodel.CreateDate = System.DateTime.Now;
                demodel.CreateBy = requestParm.ERPEmpId;
                demodel.MallUserId = requestParm.EmpId;
                demodel.TenantId = requestParm.TenantId;
                demodel.MallBaseId = requestParm.MallBaseId;
                demodel.RB_Branch_Id = requestParm.ERPBranchId;
                demodel.RB_Group_Id = requestParm.ERPGroupId;
                Random R = new Random();
                int Rstr = R.Next(111, 999);
                demodel.OutNo = DateTime.Now.ToString("yyyyMMddHHmmssfff") + Rstr;
            }
            demodel.ApplyStatus = 1;
            demodel.Status = 0;
            demodel.UpdateDate = System.DateTime.Now;
            demodel.UpdateBy = requestParm.ERPEmpId;

            bool result = warehouseOutModule.AddWarehouseOut(demodel);
            if (result)
            {
                return ApiResult.Success("出库单申请成功");
            }
            else
            {
                return ApiResult.Failed("出库单申请失败");
            }
        }



        /// <summary>
        /// 获取出库申请列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetNoOutOrderGoodsList()
        {
            var parms = RequestParm;
            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(parms.msg.ToString());
            RB_Goods_OrderDetail_Extend demodel = JsonConvert.DeserializeObject<RB_Goods_OrderDetail_Extend>(parms.msg.ToString());
            demodel.TenantId = parms.TenantId;
            demodel.MallBaseId = parms.MallBaseId;
            var list = orderModule.GetNoOutOrderGoodsList(pagelist.pageIndex, pagelist.pageSize, out long count, demodel);
            list.ForEach(x => x.NewSpecificationSort = x.SpecificationSort);
            list.ForEach(x => x.NewSpecification = x.Specification);
            list.ForEach(x => x.NewNumber = (x.Number ?? 0));
            list.ForEach(x => x.NewGoodsId = x.GoodsId ?? 0);
            list.ForEach(x => x.NewGoodsName = x.GoodsName);
            pagelist.count = Convert.ToInt32(count);
            pagelist.pageData = list;
            return ApiResult.Success("", pagelist);
        }


    }
}