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
                    }
                }),
                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.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("请输入入库数量");
                }
            }

            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 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;
            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,
                //UpdateBy = CacheManager.User.UserReidsCache.GetEmployee(x.UpdateBy)?.EmName ?? "",
                UpdateDate = x.UpdateDate.Value.ToString("yyyy-MM-dd")
            });
            return ApiResult.Success("", pagelist);
        }

        /// <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
    }
}