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

namespace Mall.WebApi.Controllers.MallBase
{
    [Route("api/[controller]/[action]")]
    [ApiExceptionFilter]
    [ApiController]
    [EnableCors("AllowCors")]
    public class PropertyController : BaseController
    {

        private readonly PropertyModule propertyModule = new PropertyModule();

        #region 商品采购

        /// <summary>
        /// 获取采购单分页列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetProcurementPageList()
        {
            var requestParm = RequestParm;
            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(requestParm.msg.ToString());
            RB_Procurement_Extend demodel = JsonConvert.DeserializeObject<RB_Procurement_Extend>(requestParm.msg.ToString());

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

            demodel.RB_Group_Id = requestParm.ERPGroupId;
            demodel.TenantId = requestParm.TenantId;
            demodel.MallBaseId = requestParm.MallBaseId;
            var list = propertyModule.GetProcurementPageList(pagelist.pageIndex, pagelist.pageSize, demodel, out long count);
            pagelist.count = Convert.ToInt32(count);
            pagelist.pageData = list.Select(x => new
            {
                x.Id,
                x.WareHouseId,
                x.WareHouseName,
                x.TotalCostMoney,
                x.TotalNumber,
                x.Remark,
                x.StockInStatus,
                DetailList = x.DetailList.Select(y => new
                {
                    y.Id,
                    y.MaterialId,
                    y.CostMoney,
                    y.Number,
                    y.StockInNum,
                    MaterialModel = new
                    {
                        y.MaterialModel.Name,
                        y.MaterialModel.SuppliesNum,
                        y.MaterialModel.Units,
                        y.MaterialModel.Money,
                        y.MaterialModel.GoodsSpecificationList,
                        y.MaterialModel.GoodsCategoryList,
                        y.MaterialModel.GoodsId,
                        y.MaterialModel.SpecificationKey,
                        y.MaterialModel.ImageList
                    }
                }),
                x.FinanceId,
                x.CreateByName,
                CreateDate = x.CreateDate.Value.ToString("yyyy-MM-dd")
            });
            return ApiResult.Success("", pagelist);
        }

        /// <summary>
        /// 获取采购单详情
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetProcurementInfo()
        {
            var requestParm = RequestParm;
            JObject parms = JObject.Parse(requestParm.msg.ToString());
            int ProcurementId = parms.GetInt("ProcurementId", 0);
            if (ProcurementId <= 0)
            {
                return ApiResult.ParamIsNull("请传递参数");
            }

            var model = propertyModule.GetProcurementInfo(ProcurementId, requestParm.TenantId, requestParm.MallBaseId, requestParm.ERPGroupId);
            return ApiResult.Success("", new
            {
                model.Id,
                model.WareHouseId,
                model.WareHouseName,
                model.TotalCostMoney,
                model.TotalNumber,
                model.Remark,
                model.StockInStatus,
                DetailList = model.DetailList.Select(y => new
                {
                    y.Id,
                    y.MaterialId,
                    y.CostMoney,
                    y.Number,
                    y.StockInNum,
                    MaterialModel = new
                    {
                        y.MaterialModel.Name,
                        y.MaterialModel.SuppliesNum,
                        y.MaterialModel.Units,
                        y.MaterialModel.Money,
                        y.MaterialModel.GoodsSpecificationList,
                        y.MaterialModel.GoodsCategoryList,
                        y.MaterialModel.GoodsId,
                        y.MaterialModel.SpecificationKey,
                        y.MaterialModel.ImageList,
                        y.MaterialModel.Barcode
                    }
                }),
                model.FinanceId
            });
        }

        /// <summary>
        /// 获取商品规格列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetGoodsToProcurementPageList()
        {
            var parms = RequestParm;
            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(parms.msg.ToString());
            RB_Goods_Extend demodel = JsonConvert.DeserializeObject<RB_Goods_Extend>(parms.msg.ToString());

            demodel.TenantId = parms.TenantId;
            demodel.MallBaseId = parms.MallBaseId;
            var list = propertyModule.GetGoodsToProcurementPageList(pagelist.pageIndex, pagelist.pageSize, out long count, demodel);
            pagelist.count = Convert.ToInt32(count);
            pagelist.pageData = list.Select(x => new
            {
                x.Id,
                x.Name,
                x.CoverImage,
                x.CostPrice,
                x.IsCustomSpecification,
                SpecificationList = x.SpecificationPriceList.Select(y => new
                {
                    y.Id,
                    y.GoodsId,
                    y.GoodsNumbers,
                    y.GoodsWeight,
                    y.InventoryNum,
                    y.SpecificationSort,
                    y.AttrList
                })
            });
            return ApiResult.Success("", pagelist);
        }

        /// <summary>
        /// 提交采购单
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetProcurementInfo()
        {
            var requestParm = RequestParm;
            RB_Procurement_Extend demodel = JsonConvert.DeserializeObject<RB_Procurement_Extend>(requestParm.msg.ToString());
            if (requestParm.ERPEmpId <= 0)
            {
                return ApiResult.ParamIsNull("请传递参数");
            }
            if (requestParm.ERPGroupId <= 0)
            {
                return ApiResult.ParamIsNull("请传递参数");
            }
            if (requestParm.EmpId <= 0)
            {
                return ApiResult.ParamIsNull("请传递参数");
            }
            if (demodel.IsPublic < 0)
            {
                return ApiResult.ParamIsNull("请选择账户类型");
            }
            if ((demodel.SupplierId ?? 0) <= 0)
            {
                return ApiResult.ParamIsNull("请传递供应商");
            }
            if ((demodel.WareHouseId ?? 0) <= 0)
            {
                return ApiResult.ParamIsNull("请传递仓库id");
            }

            if (demodel.DetailList == null || !demodel.DetailList.Any())
            {
                return ApiResult.ParamIsNull("请选择商品");
            }
            if (demodel.DetailList.Count() != demodel.DetailList.Select(x => x.GoodsId + "," + x.SpecificationKey).Distinct().Count())
            {
                return ApiResult.ParamIsNull("商品有重复数据");
            }
            foreach (var item in demodel.DetailList)
            {
                if (item.GoodsId <= 0)
                {
                    return ApiResult.ParamIsNull("商品id未传递");
                }
                if ((item.CostMoney ?? 0) <= 0)
                {
                    return ApiResult.ParamIsNull("请输入价格");
                }
                if ((item.Number ?? 0) <= 0)
                {
                    return ApiResult.ParamIsNull("请输入数量");
                }
            }

            string msg = propertyModule.SetProcurementInfo(demodel, requestParm.ERPEmpId, requestParm.ERPBranchId, requestParm.ERPGroupId, requestParm.TenantId, requestParm.MallBaseId, requestParm.EmpId);
            if (msg == "")
            {
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed(msg);
            }
        }

        #endregion

        #region 采购单入库

        /// <summary>
        /// 保存采购单入库
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetProcurementStockIn()
        {
            var requestParm = RequestParm;
            RB_Procurement_Extend demodel = JsonConvert.DeserializeObject<RB_Procurement_Extend>(requestParm.msg.ToString());

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

            if (demodel.Id <= 0)
            {
                return ApiResult.ParamIsNull("请传递采购单id");
            }
            if (demodel.WareHouseId <= 0)
            {
                return ApiResult.ParamIsNull("请传递仓库id");
            }
            if (demodel.DetailList == null || !demodel.DetailList.Any())
            {
                return ApiResult.ParamIsNull("请选择商品");
            }
            demodel.DetailList = demodel.DetailList.Where(x => x.InStockNum > 0).ToList();
            if (!demodel.DetailList.Any())
            {
                return ApiResult.ParamIsNull("请输入商品入库数量");
            }
            foreach (var item in demodel.DetailList)
            {
                if (item.GoodsId <= 0)
                {
                    return ApiResult.ParamIsNull("商品id未传递");
                }
                if (item.InStockNum <= 0)
                {
                    return ApiResult.ParamIsNull("请输入入库数量");
                }
                if (item.ValidityList != null && item.ValidityList.Count() > 0)
                {
                    if (item.ValidityList.Count() != item.InStockNum)
                    {
                        return ApiResult.ParamIsNull("有效期数量与入库数量不匹配");
                    }
                }
            }

            //判断当前仓库是否在盘点中2020-07-28 Add By:W
            var suppliesCheckList = propertyModule.GetSuppliesCheckList(new RB_Supplies_Check_Extend { RB_Group_Id = requestParm.ERPGroupId, StartDate = System.DateTime.Now, EndDate = System.DateTime.Now, WarehouseId = demodel.WareHouseId ?? 0, CheckState = Common.Enum.Property.SuppliesCheckStatusEnum.InTheInventory });
            if (suppliesCheckList != null && suppliesCheckList.Any())
            {
                return ApiResult.ParamIsNull("仓库盘点中，不能入库");
            }
            string msg = propertyModule.SetProcurementStockIn(demodel, requestParm.ERPEmpId, requestParm.ERPBranchId, requestParm.ERPGroupId, requestParm.TenantId, requestParm.MallBaseId, requestParm.EmpId);
            if (msg == "")
            {
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed(msg);
            }
        }

        /// <summary>
        /// 获取采购单 入库批次
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetProcurementSotckInBatchList()
        {
            var requestParm = RequestParm;
            if (requestParm.ERPEmpId <= 0)
            {
                return ApiResult.ParamIsNull("请传递参数");
            }
            if (requestParm.ERPGroupId <= 0)
            {
                return ApiResult.ParamIsNull("请传递参数");
            }
            if (requestParm.EmpId <= 0)
            {
                return ApiResult.ParamIsNull("请传递参数");
            }
            JObject parms = JObject.Parse(requestParm.msg.ToString());
            int ProcurementId = parms.GetInt("ProcurementId", 0);
            if (ProcurementId <= 0)
            {
                return ApiResult.ParamIsNull("请传递参数");
            }

            var list = propertyModule.GetProcurementSotckInBatchList(ProcurementId, requestParm.ERPEmpId, requestParm.ERPGroupId, requestParm.EmpId);
            return ApiResult.Success("", list);
        }

        /// <summary>
        /// 获取采购入库 的标签
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetProcurementStockInLableList()
        {
            var requestParm = RequestParm;
            if (requestParm.ERPEmpId <= 0)
            {
                return ApiResult.ParamIsNull("请传递参数");
            }
            if (requestParm.ERPGroupId <= 0)
            {
                return ApiResult.ParamIsNull("请传递参数");
            }
            if (requestParm.EmpId <= 0)
            {
                return ApiResult.ParamIsNull("请传递参数");
            }
            JObject parms = JObject.Parse(requestParm.msg.ToString());
            int ProcurementId = parms.GetInt("ProcurementId", 0);
            int StockInId = parms.GetInt("StockInId", 0);
            if (ProcurementId <= 0)
            {
                return ApiResult.ParamIsNull("请传递参数");
            }

            var list = propertyModule.GetProcurementStockInLableList(ProcurementId, StockInId, requestParm.ERPEmpId, requestParm.ERPGroupId, requestParm.EmpId);
            return ApiResult.Success("", list);

        }
        #endregion

        #region 重新入库

        /// <summary>
        /// 获取出库记录表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetGoodsOutDetailPageList()
        {
            var parms = RequestParm;
            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(parms.msg.ToString());
            RB_WarehouseOut_GoodsDetail_Extend demodel = JsonConvert.DeserializeObject<RB_WarehouseOut_GoodsDetail_Extend>(parms.msg.ToString());

            demodel.TenantId = parms.TenantId;
            demodel.MallBaseId = parms.MallBaseId;
            var list = propertyModule.GetGoodsOutDetailPageList(pagelist.pageIndex, pagelist.pageSize, out long count, demodel);
            pagelist.count = Convert.ToInt32(count);
            int Num = 1;
            pagelist.pageData = list.Select(x => new
            {
                Id = Num++,
                x.OrderId,
                x.OrderGoodsId,
                x.GoodsId,
                x.StockOutId,
                x.MaterialId,
                x.GoodsName,
                x.Specification,
                x.OrderNo,
                x.CostMoney,
                x.ProductCode,
                x.WarehouseId,
                x.WarehouseName,
                x.Number,
                x.ValidityIds,
                StockOutDate = x.StockOutDate.HasValue ? x.StockOutDate.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                StockInDate = x.StockInDate.HasValue ? x.StockInDate.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                x.InventoryNum
            });
            return ApiResult.Success("", pagelist);
        }

        /// <summary>
        /// 重新入库
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetGoodsAgainInventory()
        {
            var requestParm = RequestParm;
            List<RB_WarehouseOut_GoodsDetail_Extend> demodel = JsonConvert.DeserializeObject<List<RB_WarehouseOut_GoodsDetail_Extend>>(requestParm.msg.ToString());
            if (requestParm.ERPEmpId <= 0)
            {
                return ApiResult.ParamIsNull("非资产绑定账户，无法操作");
            }
            if (demodel == null || demodel.Count() == 0) {
                return ApiResult.ParamIsNull("请传递数据");
            }
            foreach (var item in demodel)
            {
                if (item.OrderId <= 0){
                    return ApiResult.ParamIsNull("请传递订单id");
                }
                if (item.OrderGoodsId <= 0) {
                    return ApiResult.ParamIsNull("请传递订单明细id");
                }
                if (item.StockOutId <= 0) {
                    return ApiResult.ParamIsNull("请传递出库单id");
                }
                if (item.MaterialId <= 0) {
                    return ApiResult.ParamIsNull("请传递物料id");
                }
                if (item.WarehouseId <= 0) {
                    return ApiResult.ParamIsNull("请传递仓库id");
                }
                if (item.Number <= 0){
                    return ApiResult.ParamIsNull("请传递出库数量");
                }
                if (item.InventoryNum <= 0) {
                    return ApiResult.ParamIsNull("请传递重新入库数量");
                }
                if (string.IsNullOrEmpty(item.GoodsName))
                {
                    return ApiResult.ParamIsNull("请传递商品名称");
                }
                if (string.IsNullOrEmpty(item.Specification))
                {
                    return ApiResult.ParamIsNull("请传递商品规格");
                }
                if (string.IsNullOrEmpty(item.OrderNo))
                {
                    return ApiResult.ParamIsNull("请传递订单号");
                }

            }

            string msg = propertyModule.SetGoodsAgainInventory(demodel, requestParm.ERPEmpId, requestParm.ERPBranchId, requestParm.ERPGroupId, requestParm.TenantId, requestParm.MallBaseId, requestParm.EmpId);
            if (msg == "")
            {
                return ApiResult.Success();
            }
            else {
                return ApiResult.Failed(msg);
            }
        }

        /// <summary>
        /// 重新入库获取物料信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetStockOutGoodsInfo()
        {
            var requestParm = RequestParm;
            if (requestParm.ERPEmpId <= 0)
            {
                return ApiResult.ParamIsNull("非资产绑定账户，无法操作");
            }
            JObject parms = JObject.Parse(requestParm.msg.ToString());
            string Code = parms.GetStringValue("Code");
            if (string.IsNullOrEmpty(Code))
            {
                return ApiResult.ParamIsNull("请传递参数");
            }

            var obj = propertyModule.GetStockOutGoodsInfo(Code);
            return ApiResult.Success("", obj);
        }

        #endregion


        #region 同步商品
        /// <summary>
        /// 获取物料档案分页列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetMaterialPageList()
        {
            var requestParm = RequestParm;
            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(requestParm.msg.ToString());
            RB_Supplies_Material_Extend demodel = JsonConvert.DeserializeObject<RB_Supplies_Material_Extend>(requestParm.msg.ToString());

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

            demodel.RB_Group_Id = requestParm.ERPGroupId;
            demodel.TenantId = requestParm.TenantId;
            demodel.MallBaseId = requestParm.MallBaseId;
            var list = propertyModule.GetMaterialPageList(pagelist.pageIndex, pagelist.pageSize, demodel, out long count);
            pagelist.count = Convert.ToInt32(count);
            pagelist.pageData = list.Select(x => new
            {
                x.Id,
                x.Name,
                x.Money,
                x.Units,
                x.ImageList,
                x.Remark,
                x.SupplierName,
                x.SuppliesNum,
                x.InventoryNum,
                x.GoodsSpecificationList,
                x.GoodsCategoryList,
                x.Barcode,
                UpdateDate = x.UpdateDate.Value.ToString("yyyy-MM-dd")
            });
            return ApiResult.Success("", pagelist);
        }

        /// <summary>
        /// 设置物料条形码
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetMaterialBarcode() {
            var requestParm = RequestParm;
            if (requestParm.ERPEmpId <= 0)
            {
                return ApiResult.ParamIsNull("请传递参数");
            }
            JObject parms = JObject.Parse(requestParm.msg.ToString());
            int MaterialId = parms.GetInt("MaterialId", 0);
            string Barcode = parms.GetStringValue("Barcode");
            if (MaterialId <= 0) {
                return ApiResult.ParamIsNull();
            }

            bool flag = propertyModule.SetMaterialBarcode(MaterialId, Barcode);
            if (flag)
            {
                return ApiResult.Success();
            }
            else {
                return ApiResult.Failed();
            }
        }

        /// <summary>
        /// 同步商品信息至资产耗材
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetSyncGoodsToMaterial()
        {
            var requestParm = RequestParm;
            JObject parms = JObject.Parse(requestParm.msg.ToString());
            //int WareHouseId = parms.GetInt("WareHouseId", 0);//仓库id
            string CategoryIds = parms.GetStringValue("CategoryIds");//同步的商品分类

            if (string.IsNullOrEmpty(CategoryIds) || CategoryIds == "[]")
            {
                return ApiResult.ParamIsNull("请传递分类");
            }
            List<int> categoryIdList = new List<int>();
            try
            {
                categoryIdList = JsonConvert.DeserializeObject<List<int>>(CategoryIds);
            }
            catch (Exception)
            {
                return ApiResult.ParamIsNull("分类格式有误");
            }
            if (requestParm.ERPEmpId <= 0)
            {
                return ApiResult.ParamIsNull("请传递关联ERP用户id");
            }

            bool flag = propertyModule.SetSyncGoodsToMaterial(0, categoryIdList, requestParm.ERPEmpId, requestParm.ERPBranchId, requestParm.ERPGroupId, requestParm.TenantId, requestParm.MallBaseId, requestParm.EmpId);
            if (flag)
            {
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed();
            }
        }

        #endregion

        #region 获取盘点中的仓库

        public ApiResult GetSuppliesCheckList()
        {
            var requestParm = RequestParm;
            //判断当前仓库是否在盘点中2020-07-28 Add By:W
            var suppliesCheckList = propertyModule.GetSuppliesCheckList(new RB_Supplies_Check_Extend { RB_Group_Id = requestParm.ERPGroupId, StartDate = System.DateTime.Now, EndDate = System.DateTime.Now, CheckState = Common.Enum.Property.SuppliesCheckStatusEnum.InTheInventory });
            return ApiResult.Success("", suppliesCheckList);
        }

        #endregion
    }
}