using System;
using System.Collections.Generic;
using System.Linq;
using Siger.Middlelayer.Common;
using Siger.Middlelayer.Common.ModuleEnum;
using Siger.Middlelayer.WmsRepository.Entities;
using Siger.Middlelayer.WmsRepository.Repositories.Interface;
using Siger.Middlelayer.WmsRepository.Request;

namespace Siger.Middlelayer.WmsRepository.Repositories
{
    internal class siger_wms_stocktake_order_detailRepository : WMSRepositoryBase<siger_wms_stocktake_order_detail>, Isiger_wms_stocktake_order_detailRepository
    {
        private readonly ApiWmsDbContext dbContext;
        public siger_wms_stocktake_order_detailRepository(ApiWmsDbContext context) : base(context)
        {
            dbContext = context;
        }

        public void UpdateCheck(int id, List<node> nodes, int projectId, int userId)
        {
            var order = dbContext.siger_wms_stocktake_order.FirstOrDefault(f => f.status == (int)RowState.Valid && f.projectid == projectId && f.id == id);
            var detailsId = nodes.Select(f => f.id);
            //check
            var detailData = GetList(f => detailsId.Contains(f.id) && f.projectid == projectId && f.status == (int)RowState.Valid).ToList();
            if (detailData.Count() != detailsId.Count())
            {
                return;
            }
            var nodeDic = nodes.ToDictionary(f => f.id, f => f.num);

            //update
            foreach (var item in detailData)
            {
                if (nodeDic.Any(f => f.Key == item.id))
                {
                    item.stocktaked_quantity = nodeDic[item.id];
                    item.update_time = DateTime.Now;
                    item.updator = userId;
                    item.stocktake_person = userId;
                    item.stocktake_time = DateTime.Now;
                    item.stocktake_status = (int)CheckStatu.Finish;
                    Update(item);
                }
                //获取储位信息
                var stock = dbContext.siger_wms_stock.FirstOrDefault(f => f.status == (int)RowState.Valid && f.projectid == projectId && f.id == item.stockid);
                if (stock == null)
                {
                    throw new BadRequestException(RequestEnum.StockNotExist);
                }
                //如果是序号管理，只能出现一个
                if (stock.manage_model==((int)managemodel.No).ToString())
                {
                    if(item.stocktaked_quantity>1)
                    {
                        throw new BadRequestException(RequestEnum.SNManageCountError);
                    }
                }
                var locationdata = dbContext.siger_wms_storage_location.FirstOrDefault(f => f.status == (int)RowState.Valid && f.projectid == projectId && f.id == stock.storage_location_id);
                if (locationdata == null)
                {
                    throw new BadRequestException(RequestEnum.LocationNull);
                }
                //添加trace
                var tracedata = new siger_wms_stock_detail();
                tracedata.type = (int)traceType.Check;
                tracedata.billID = item.order_number;
                tracedata.inventory = item.material_id;
                tracedata.inventorySN = item.material_pn;
                tracedata.inventoryName = item.material_name;
                tracedata.allqty = item.stocktaked_quantity;
                tracedata.qty = item.stocktaked_quantity;
                tracedata.userid = userId;
                tracedata.username = GetUserName(userId);
                tracedata.updatetime = DateTime.Now;
                tracedata.state = (int)RowState.Valid;
                tracedata.locationid = order.storageid;
                tracedata.locationname = locationdata.name;
                tracedata.inventorySpec = item.material_spec;
                tracedata.state = (int)RowState.Valid;
                tracedata.projectid = projectId;
                tracedata.no = stock.serial_number;
                tracedata.batch = stock.batch_number;
                //将供应商信息存入详情中
                if (stock.category != WaveHousingType.Production.ToString() &&
                    stock.category != WaveHousingType.ProductionOut.ToString()&&
                    stock.category != WaveHousingType.OtherOut.ToString())
                {
                    //供应商信息
                    var businessName = GetBusinessName(stock.businessid, projectId);
                    tracedata.businessid = stock.businessid;
                    tracedata.businessName = businessName;
                }
                dbContext.siger_wms_stock_detail.Add(tracedata);

                //更新库存
                if (stock == null)
                {
                    throw new BadRequestException(RequestEnum.StockNotExist);
                }

                //当前数量小于待修改的数量
                //即当前库存大于实际库存
                //需要将现有库存改小
                if (stock.quantity > item.stocktaked_quantity)
                {
                    SubtractStockChange(order.storageid, stock.material_id, (stock.quantity - item.stocktaked_quantity), projectId);
                }
                if (stock.quantity < item.stocktaked_quantity)
                {
                    AddStockChange(order.storageid, stock.material_id, (item.stocktaked_quantity - stock.quantity), projectId);
                }
                stock.quantity = item.stocktaked_quantity;
                dbContext.siger_wms_stock.Update(stock);
            }
            order.update_time = DateTime.Now;
            order.updator = userId;
            dbContext.siger_wms_stocktake_order.Update(order);

            if (dbContext.SaveChanges() <= 0)
                throw new BadRequestException(CommonEnum.Fail);
            //更新单据状态
            //所有数据均已盘点(此订单的所有数据均不为审核通过状态,即所有状态都是盘点完成)
            if (!IsExist(f =>f.orderid==id&& f.stocktake_status == (int)CheckStatu.Checked && f.status == (int)RowState.Valid && f.projectid == projectId))
            {
                //更新单据信息
                order.order_status = (int)CheckStatu.Finish;
            }
            else
            {
                order.order_status = (int)CheckStatu.Checking;
            }
            dbContext.siger_wms_stocktake_order.Update(order);
            if (dbContext.SaveChanges() <= 0)
                throw new BadRequestException(CommonEnum.Fail);
        }
    }
}

