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

namespace Siger.Middlelayer.WmsRepository.Repositories
{
    internal class siger_wms_stock_access_orderRepository : WMSRepositoryBase<siger_wms_stock_access_order>, Isiger_wms_stock_access_orderRepository
    {
        private readonly ApiWmsDbContext dbContext;
        public siger_wms_stock_access_orderRepository(ApiWmsDbContext context) : base(context)
        {
            dbContext = context;
        }
        public IEnumerable<ResponseWaveHousing> GetWaveHousingBills(int pid, WaveHouseType type, WaveHousingState orderstatus, int page, int pageSize, out int totalCount)
        {
            var start = DateTime.Now.AddDays(-DateTime.Now.Day + 1);
            var data = GetList(f => f.projectid == pid && f.order_status == (int)orderstatus && f.access_type == (int)type && f.status == (int)RowState.Valid && f.update_time >= start.Date && f.update_time <= DateTime.Now);
            totalCount = data.Count();
            data = data.Skip((page - 1) * pageSize).Take(pageSize);
            var result = from d in data
                         join u in dbContext.siger_user on d.updator equals u.id into tmp1
                         from t1 in tmp1.DefaultIfEmpty()
                         join storage in dbContext.siger_wms_storage on d.storageid equals storage.id
                         select new ResponseWaveHousing
                         {
                             id = d.id,
                             order_number = d.order_number,
                             name = t1.nickname,
                             time = d.update_time,
                             storageName = storage.name
                         };
            foreach (var item in result)
            {
                var count = dbContext.siger_wms_stock_access_order_detail.Where(f => f.orderid == item.id && f.projectid == pid).Count();
                item.count = count;
            }
            return result;
        }

        public IEnumerable<ResponseBill> GeList(int pid, WaveHouseType bill, WaveHousingType waveHouseType, int waveHouseID,
                            WaveHousingState state, string billCode, string originBillCode, DateTime start, DateTime end,
                            out int totalCount, int page = 1, int pageSize = 10)
        {
            IQueryable<siger_wms_stock_access_order> data = GetList(f => f.status == (int)RowState.Valid && f.projectid == pid);
            switch (bill)
            {
                case WaveHouseType.In:
                case WaveHouseType.Out:
                    data = data.Where(f => f.access_type == (int)bill);
                    break;
                default:
                    throw new BadRequestException(RequestEnum.ErrorWaveHouseType);
            }
            switch (waveHouseType)
            {
                case WaveHousingType.RawMaterial:
                case WaveHousingType.Production:
                case WaveHousingType.Other:
                case WaveHousingType.ProductionOut:
                case WaveHousingType.SalesOut:
                case WaveHousingType.WholeToolIn:
                case WaveHousingType.Purchase:
                case WaveHousingType.Recycling:
                case WaveHousingType.UseOut:
                case WaveHousingType.OtherOut:
                    data = data.Where(f => f.category_code == (int)waveHouseType);
                    break;
            }
            switch (state)
            {
                case WaveHousingState.Waiting:
                case WaveHousingState.Checked:
                case WaveHousingState.Failed:
                case WaveHousingState.WaveHousing:
                case WaveHousingState.Finish:
                case WaveHousingState.WaveHousingOut:
                case WaveHousingState.WaveHousingOutFinish:
                case WaveHousingState.Deleted:
                    data = data.Where(f => f.order_status == (int)state);
                    break;
            }
            if (!string.IsNullOrEmpty(originBillCode))
            {
                data = data.Where(f => f.origin_order_number == originBillCode);
            }
            if (!string.IsNullOrEmpty(billCode))
            {
                data = data.Where(f => f.order_number == billCode);
            }
            if (waveHouseID != 0)
            {
                data = data.Where(f => f.storageid == waveHouseID);
            }
            if (start != null && start != DateTime.MinValue)
                data = data.Where(f => f.create_time > start);
            if (end != null && end != DateTime.MinValue)
                data = data.Where(f => f.create_time < end);
            data = data.OrderByDescending(f => f.update_time);
            totalCount = data.Count();
            data = data.Skip((page - 1) * pageSize).Take(pageSize);

            var Result = (from list in data
                          join wavehouse in dbContext.siger_wms_storage on list.storageid equals wavehouse.id
                          into wavehouseData//关联仓库信息
                                            //from waveHouseInfo in wavehouseData.DefaultIfEmpty()
                                            //join business in dbContext.siger_wms_bussinese_contacts on list.contactid equals business.id
                                            //into businessData//关联来源方
                                            //from businessInfo in businessData.DefaultIfEmpty()
                          from waveHouseInfo in wavehouseData.DefaultIfEmpty()
                          join creater in dbContext.siger_project_user on list.creator equals creater.mid
                          into createrData//关联创建人
                          from createrInfo in createrData.DefaultIfEmpty()
                          join checkuser in dbContext.siger_project_user on list.auditor equals checkuser.mid
                          into result//关联审核人
                          from r in result.DefaultIfEmpty()
                          join pickuser in dbContext.siger_project_user on list.picker equals pickuser.mid
                          into result1//关联审核人
                          from p in result1.DefaultIfEmpty()
                          join depart in dbContext.siger_project_section on list.departid equals depart.id
                              into d//关联部门
                          from depart in d.DefaultIfEmpty()
                          select new ResponseBill
                          {//类型id、仓库iD、原始单号
                              id = list.id,
                              category = list.category,
                              category_id = list.category_code,
                              storageID = list.storageid,
                              wavehouseName = waveHouseInfo.name,
                              order_number = list.order_number,
                              businessName = "",
                              createrName = createrInfo.name,
                              createTime = list.create_time,
                              checkUser = r.name,
                              checkTime = list.audit_time == DateTime.MinValue ? "" : list.audit_time.ToString(UnixTimeHelper.DateTimeFormat),
                              auditdesc = list.audit_desc,
                              state = list.order_status.ToString(),
                              stateid = list.order_status,
                              businessID = list.contactid,
                              origin_order_number = list.origin_order_number,
                              picker = list.picker,
                              picker_name = p.name,
                              access_type = list.access_type,
                              departid = list.departid,
                              department = depart.title ?? ""
                          }).ToList();
            foreach (var item in Result)
            {
                if (item.state == ((int)WaveHousingType.Production).ToString())
                {
                    //显示生产部门
                    var contract = dbContext.siger_project_section.Where(f => f.id == item.businessID && f.projectid == pid).FirstOrDefault();
                    if (contract != null)
                    {
                        item.businessName = contract.title;
                    }
                }
                else
                {
                    if (item.state == ((int)WaveHousingType.SalesOut).ToString())
                    {
                        var contract = dbContext.siger_wms_bussinese_contacts.Where(f => f.id == item.businessID && f.projectid == pid).FirstOrDefault();
                        if (contract != null)
                        {
                            item.businessName = contract.name;
                        }
                    }

                }
                if (Enum.TryParse<WaveHousingState>(item.state, out WaveHousingState result))
                {
                    item.state = EnumHelper.GetEnumDesc((WaveHousingState)result);
                }
            }
            return Result;
        }

        public IEnumerable<ResponseDepartment> GetDepartmentList(int pid)
        {
            var result = dbContext.siger_project_section.Where(f => f.status == (int)RowState.Valid && f.projectid == pid).Select(f =>
            new ResponseDepartment
            {
                id = f.id,
                title = f.title,
                des = f.description
            });
            return result;
        }

        public ResponseInventoryInfo GetInventoryInfo(string pn, int pid, int storage, int businessid)
        {
            if (string.IsNullOrEmpty(pn))
            {
                throw new BadRequestException(RequestEnum.ParameterMiss);
            }
            var entity = dbContext.siger_tr_materials.Where(f => f.status == (int)RowState.Valid && f.pn.Trim() == pn.Trim() && f.projectId == pid).FirstOrDefault();
            if (entity == null)
            {
                throw new BadRequestException(CommonEnum.RecordNotFound);
            }
            if (businessid != 0)
            {
                //check if material has the supplier
                if (!dbContext.siger_tr_material_supplier.Any(f => f.status == (int)RowState.Valid && f.projectId == pid && f.material_id == entity.id && f.supplier_id == businessid))
                {
                    throw new BadRequestException(CommonEnum.NoData);
                }
            }
            int count = 0;
            if (storage == 0)
            {
                var data = dbContext.siger_wms_stock.Where(f => f.status == (int)RowState.Valid && f.stock_state == (int)StockEnum.InWavehouse && f.projectid == pid);
                if(businessid!=0)
                {
                    data = data.Where(f => f.businessid == businessid);
                }
                count=data.Sum(f => f.quantity);
            }
            else
            {
                var locationids = dbContext.siger_wms_storage_location.Where(f => f.status == (int)RowState.Valid && f.projectid == pid && f.storageid == storage).Select(f => f.id).ToList();
                var data = dbContext.siger_wms_stock.Where(f => f.material_id == entity.id && f.status == (int)RowState.Valid && f.stock_state == (int)StockEnum.InWavehouse && f.projectid == pid && locationids.Contains(f.storage_location_id));
                if(businessid!=0)
                {
                    data = data.Where(f => f.businessid == businessid);
                }
                count = data.Sum(f => f.quantity);
            }
            var result = new ResponseInventoryInfo
            {
                id = entity.id,
                inventoryid = entity.pn,
                name = entity.name,
                spec = entity.spec,
                count = count
            };
            return result;
        }

        public void AddBill(int pid,int userid, RequestAddBill req)
        {
            if (IsExist(f => f.order_number == req.billID.Trim() && f.projectid == pid && f.status == (int)RowState.Valid))
            {
                throw new BadRequestException(CommonEnum.RecordExits);
            }
            //供应商、部门检测
            if (req.wavehousingtype == WaveHousingType.ProductionOut)
            {
                if (dbContext.siger_project_section.Count(f => f.id == req.departid && f.projectid == pid) <= 0)
                {
                    throw new BadRequestException(RequestEnum.SectionIDNotNull);
                }
            }
            if (req.wavehousingtype == WaveHousingType.Production)
            {
                if (dbContext.siger_project_section.Count(f => f.id == req.businessid && f.projectid == pid) <= 0)
                {
                    throw new BadRequestException(RequestEnum.BusinessIDNotExist);
                }
            }
           
            if (dbContext.siger_wms_storage.Count(f => f.id == req.waveHouseID && f.projectid == pid) <= 0)
            {
                throw new BadRequestException(RequestEnum.WaveHouseIDNotExist);
            }
            var picker = req.picker.ToInt() > 0 ? req.picker.ToInt() : userid;

            var entity = new siger_wms_stock_access_order
            {
                contactid = req.businessid,
                category = EnumHelper.GetEnumDesc(req.wavehousingtype),
                storageid = req.waveHouseID,
                access_type = (int)req.billType,
                order_number = req.rowBillID,
                origin_order_number = req.rowBillID,
                order_status = (int)WaveHousingState.Waiting,
                creator = userid,
                create_time = DateTime.Now,
                update_time = DateTime.Now,
                updator = userid,
                projectid = pid,
                status = (int)RowState.Valid,
                picker = picker,
                category_code = (int)req.wavehousingtype,
                departid = req.departid
            };
            Insert(entity);
            if (dbContext.SaveChanges() <= 0)
            {
                throw new BadRequestException(CommonEnum.Fail);
            }
            //添加物料信息
            //entity.id
            foreach (var item in req.inventories)
            {
                var material = dbContext.siger_tr_materials.Where(f => f.id == item.InventoryID && f.projectId == pid).FirstOrDefault();
                if (material == null)
                {
                    throw new BadRequestException(RequestEnum.MaterialNotExist);
                }
                var detail = new siger_wms_stock_access_order_detail
                {
                    orderid = entity.id,
                    material_id = item.InventoryID,
                    material_name = material.name,
                    material_pn = material.pn,
                    material_spec = material.spec,
                    manage_mode = material.manage_mode,
                    unit = GetUnitName(material.unit),
                    quantity = item.Count,
                    creator = userid,
                    create_time = DateTime.Now,
                    update_time = DateTime.Now,
                    updator = userid,
                    projectid = pid,
                    status = (int)RowState.Valid,
                    //access_quantity=item.Count,
                    storage_location_id=item.storage_location_id,
                };
                detail.businessid = dbContext.siger_tr_materials.FirstOrDefault(f => f.id == item.InventoryID)?.supplier.ToInt() ?? 0;
                dbContext.siger_wms_stock_access_order_detail.Add(detail);
            }
            if (dbContext.SaveChanges() <= 0)
            {
                throw new BadRequestException(CommonEnum.Fail);
            }
        }
        public void AddBill(int pid, WaveHouseType billType, string billCode, WaveHousingType wavehousingtype, int businessid, int waveHouseID, string rowBillID, List<Inventory> inventories, int PID, int UID, int picker, int departid)
        {
            //check
            switch (billType)
            {
                case WaveHouseType.In:
                    break;
                case WaveHouseType.Out:
                    break;
                default:
                    throw new BadRequestException(RequestEnum.ErrorWaveHouseType);
            }
            switch (wavehousingtype)
            {
                case WaveHousingType.RawMaterial:
                    break;
                case WaveHousingType.Production:
                    break;
                case WaveHousingType.Other:
                    break;
                case WaveHousingType.ProductionOut:
                    break;
                case WaveHousingType.SalesOut:
                    break;
                case WaveHousingType.OtherOut:
                    break;
                case WaveHousingType.WholeToolIn:
                    break;
                case WaveHousingType.Purchase:
                    break;
                case WaveHousingType.Recycling:
                    break;
                case WaveHousingType.UseOut:
                    break;
                default:
                    throw new BadRequestException(RequestEnum.ErrorWaveHouseType);
            }
            if (IsExist(f => f.order_number == billCode.Trim() && f.projectid == pid && f.status == (int)RowState.Valid))
            {
                throw new BadRequestException(CommonEnum.RecordExits);
            }
            //供应商、部门检测
            if (wavehousingtype == WaveHousingType.ProductionOut)
            {
                if (dbContext.siger_project_section.Count(f => f.id == departid && f.projectid == pid) <= 0)
                {
                    throw new BadRequestException(RequestEnum.SectionIDNotNull);
                }
            }
            if (wavehousingtype == WaveHousingType.Production)
            {
                if (dbContext.siger_project_section.Count(f => f.id == businessid && f.projectid == pid) <= 0)
                {
                    throw new BadRequestException(RequestEnum.BusinessIDNotExist);
                }
            }
            else
            {
                if (wavehousingtype != WaveHousingType.ProductionOut &&
                    wavehousingtype != WaveHousingType.OtherOut &&
                    wavehousingtype != WaveHousingType.Production &&
                    wavehousingtype != WaveHousingType.SalesOut)
                {
                    //防止误传
                    businessid = 0;

                    foreach (var item in inventories)
                    {
                        if (!dbContext.siger_wms_bussinese_contacts.Any(f => f.id == item.businessID && f.projectid == pid && f.status == (int)RowState.Valid))
                        {
                            throw new BadRequestException(RequestEnum.BusinessIDNotExist);
                        }
                    }
                }

            }
            if (dbContext.siger_wms_storage.Count(f => f.id == waveHouseID && f.projectid == pid) <= 0)
            {
                throw new BadRequestException(RequestEnum.WaveHouseIDNotExist);
            }

            var entity = new siger_wms_stock_access_order
            {
                contactid = businessid,
                category = EnumHelper.GetEnumDesc(wavehousingtype),
                storageid = waveHouseID,
                access_type = (int)billType,
                order_number = billCode,
                origin_order_number = rowBillID,
                order_status = (int)WaveHousingState.Waiting,
                creator = UID,
                create_time = DateTime.Now,
                update_time = DateTime.Now,
                updator = UID,
                projectid = PID,
                status = (int)RowState.Valid,
                picker = picker,
                category_code = (int)wavehousingtype,
                departid = departid
            };
            Insert(entity);
            if (dbContext.SaveChanges() <= 0)
            {
                throw new BadRequestException(CommonEnum.Fail);
            }
            //添加物料信息
            //entity.id
            foreach (var item in inventories)
            {
                var material = dbContext.siger_tr_materials.Where(f => f.id == item.InventoryID && f.projectId == pid).FirstOrDefault();
                if (material == null)
                {
                    throw new BadRequestException(RequestEnum.MaterialNotExist);
                }
                var detail = new siger_wms_stock_access_order_detail
                {
                    orderid = entity.id,
                    material_id = item.InventoryID,
                    material_name = material.name,
                    material_pn = material.pn,
                    material_spec = material.spec,
                    manage_mode = material.manage_mode,
                    unit = GetUnitName(material.unit),
                    quantity = item.Count,
                    creator = UID,
                    create_time = DateTime.Now,
                    update_time = DateTime.Now,
                    updator = UID,
                    projectid = PID,
                    status = (int)RowState.Valid
                };
                detail.businessid = item.businessID;

                dbContext.siger_wms_stock_access_order_detail.Add(detail);
            }
            if (dbContext.SaveChanges() <= 0)
            {
                throw new BadRequestException(CommonEnum.Fail);
            }
        }

        public void AddBillForChangling(int pid, WaveHouseType billType, string billCode, WaveHousingType wavehousingtype, int businessid, string waveHouseID, string rowBillID, List<InventoryForChangling> inventories, int PID, int UID, int picker)
        {
            //check
            switch (billType)
            {
                case WaveHouseType.In:
                    break;
                case WaveHouseType.Out:
                    break;
                default:
                    throw new BadRequestException(RequestEnum.ErrorWaveHouseType);
            }
            switch (wavehousingtype)
            {
                case WaveHousingType.RawMaterial:
                    break;
                case WaveHousingType.Production:
                    break;
                case WaveHousingType.Other:
                    break;
                case WaveHousingType.ProductionOut:
                    break;
                case WaveHousingType.SalesOut:
                    break;
                case WaveHousingType.OtherOut:
                    break;
                case WaveHousingType.WholeToolIn:
                    break;
                case WaveHousingType.Purchase:
                    break;
                case WaveHousingType.Recycling:
                    break;
                case WaveHousingType.UseOut:
                    break;
                default:
                    throw new BadRequestException(RequestEnum.ErrorWaveHouseType);
            }
            if (IsExist(f => f.order_number == billCode.Trim() && f.projectid == pid && f.status == (int)RowState.Valid))
            {
                throw new BadRequestException(CommonEnum.RecordExits);
            }
            //供应商、部门检测
            if (wavehousingtype == WaveHousingType.Production)
            {
                if (dbContext.siger_project_section.Count(f => f.id == businessid && f.projectid == pid) <= 0)
                {
                    throw new BadRequestException(RequestEnum.BusinessIDNotExist);
                }
            }
            else
            {
                if (wavehousingtype != WaveHousingType.ProductionOut &&
                    wavehousingtype != WaveHousingType.OtherOut &&
                    wavehousingtype != WaveHousingType.Production &&
                    wavehousingtype != WaveHousingType.SalesOut)
                {
                    //防止误传
                    businessid = 0;

                    foreach (var item in inventories)
                    {
                        if (!dbContext.siger_wms_bussinese_contacts.Any(f => f.serial_number == item.businessID && f.projectid == pid && f.status == (int)RowState.Valid))
                        {
                            throw new BadRequestException(RequestEnum.BusinessIDNotExist);
                        }
                    }
                }

            }
            if (dbContext.siger_wms_storage.Count(f => f.serial_number == waveHouseID && f.projectid == pid) <= 0)
            {
                throw new BadRequestException(RequestEnum.WaveHouseIDNotExist);
            }

            var storage = dbContext.siger_wms_storage.FirstOrDefault(f =>
                f.serial_number == waveHouseID && f.projectid == pid && f.status == (int) RowState.Valid);
            var entity = new siger_wms_stock_access_order
            {
                contactid = businessid,
                category = EnumHelper.GetEnumDesc(wavehousingtype),
                storageid = storage?.id??0,
                access_type = (int)billType,
                order_number = billCode,
                origin_order_number = rowBillID,
                order_status = (int)WaveHousingState.Waiting,
                creator = UID,
                create_time = DateTime.Now,
                update_time = DateTime.Now,
                updator = UID,
                projectid = PID,
                status = (int)RowState.Valid,
                picker = picker,
                category_code = (int)wavehousingtype
            };
            Insert(entity);
            if (dbContext.SaveChanges() <= 0)
            {
                throw new BadRequestException(CommonEnum.Fail);
            }
            //添加物料信息
            //entity.id
            foreach (var item in inventories)
            {
                var material = dbContext.siger_tr_materials.FirstOrDefault(f => f.pn == item.InventoryID && f.projectId == pid);
                if (material == null)
                {
                    throw new BadRequestException(RequestEnum.MaterialNotExist);
                }
                var detail = new siger_wms_stock_access_order_detail
                {
                    orderid = entity.id,
                    material_id = material.id,
                    material_name = material.name,
                    material_pn = material.pn,
                    material_spec = material.spec,
                    manage_mode = material.manage_mode,
                    unit = GetUnitName(material.unit),
                    quantity = item.Count,
                    creator = UID,
                    create_time = DateTime.Now,
                    update_time = DateTime.Now,
                    updator = UID,
                    projectid = PID,
                    status = (int)RowState.Valid
                };
                var bussiness = dbContext.siger_wms_bussinese_contacts.FirstOrDefault(t =>
                    t.serial_number == item.businessID && t.status == (int) RowState.Valid && t.projectid == PID);
                detail.businessid = bussiness?.id ?? 0;

                dbContext.siger_wms_stock_access_order_detail.Add(detail);
            }
            if (dbContext.SaveChanges() <= 0)
            {
                throw new BadRequestException(CommonEnum.Fail);
            }
        }
        /// <summary>
        /// 获取字典表中单位名称
        /// </summary>
        /// <param name="unit"></param>
        /// <returns></returns>
        private string GetUnitName(string unit)
        {
            var entity = dbContext.siger_tr_dict.FirstOrDefault(f => f.status == (int)RowState.Valid && f.cat == DictUnitType.meterunits.ToString() && f.dkey == unit);
            if (entity == null)
                throw new BadRequestException(RequestEnum.UnitNotFound);

            return entity.dval;
        }

        /// <summary>
        /// 检测物料是否存在
        /// </summary>
        /// <param name="ids"></param>
        /// <param name="pid"></param>
        public void CheckInventory(IEnumerable<int> ids, int pid)
        {
            foreach (var item in ids)
            {
                if (dbContext.siger_tr_materials.Count(f => f.id == item && f.projectId == pid && f.projectId == pid && f.status == (int)RowState.Valid) <= 0)
                    throw new BadRequestException(RequestEnum.MaterialNotExist);
            }
        }

        public string getDepartmentName(int contactid, int projectId)
        {
            var data = dbContext.siger_project_section.FirstOrDefault(f => f.id == contactid && f.projectid == projectId);
            if (data == null)
            {
                throw new BadRequestException(RequestEnum.DepartmentNull);
            }
            return data.title;
        }

        public IEnumerable<ResponseIdName> GetBillCodes(WaveHouseType type, int projectId, int storageid)
        {
            switch (type)
            {
                case WaveHouseType.In:
                    break;
                case WaveHouseType.Out:
                    break;
                default:
                    throw new BadRequestException(RequestEnum.ErrorWaveHouseType);
            }
            var data = GetList(f => f.status == (int)RowState.Valid && f.projectid == projectId && f.access_type == (int)type);
            if (storageid != 0)
            {
                data = data.Where(f => f.storageid == storageid);
            }
            var result = (data.Select(f =>
                      new ResponseIdName
                      {
                          id = f.id,
                          name = f.order_number
                      }
                )).ToList();
            return result;
        }

        public void UpdateBill(int billID, List<Inventory> inventories, int projectId, int userId, int picker)
        {
            if (IsExist(f => f.id == billID && f.status == (int)RowState.Valid && f.order_status == (int)WaveHousingState.Waiting && f.projectid == projectId))
            {
                var orderData = Get(f => f.id == billID && f.status == (int)RowState.Valid && f.order_status == (int)WaveHousingState.Waiting && f.projectid == projectId);
                //check all
                //检测供应商信息
                if (orderData.category != EnumHelper.GetEnumDesc(WaveHousingType.Production) &&
                    orderData.category != EnumHelper.GetEnumDesc(WaveHousingType.ProductionOut) &&
                    orderData.category != EnumHelper.GetEnumDesc(WaveHousingType.OtherOut) &&
                    orderData.category != EnumHelper.GetEnumDesc(WaveHousingType.SalesOut))
                {
                    foreach (var item in inventories)
                    {
                        if (!dbContext.siger_wms_bussinese_contacts.Any(f => f.id == item.businessID && f.projectid == projectId && f.status == (int)RowState.Valid && f.supply_type == (int)WMSEnum.Business))
                        {
                            throw new BadRequestException(RequestEnum.BusinessIDNotExist);
                        }
                    }
                }
                if(orderData != null && picker > 0)
                {
                    orderData.picker = picker;
                    dbContext.siger_wms_stock_access_order.Update(orderData);
                }

                var oldData = dbContext.siger_wms_stock_access_order_detail.Where(f => f.orderid == billID && f.status == (int)RowState.Valid
                                             && f.projectid == projectId).ToList();
                foreach (var item in oldData)
                {
                    item.status = (int)RowState.Invalid;
                    item.update_time = DateTime.Now;
                    dbContext.siger_wms_stock_access_order_detail.Update(item);
                }

                foreach (var item in inventories)
                {
                    var material = GetMaterial(item.InventoryID, projectId);
                    if (material == null)
                    {
                        throw new BadRequestException(RequestEnum.MaterialNotExist);
                    }
                    var data = new siger_wms_stock_access_order_detail
                    {
                        orderid = billID,
                        material_id = item.InventoryID,
                        material_name = material.name,
                        material_pn = material.pn,
                        material_spec = material.spec,
                        manage_mode = material.manage_mode,
                        quantity = item.Count,
                        creator = userId,
                        create_time = DateTime.Now,
                        update_time = DateTime.Now,
                        updator = userId,
                        projectid = projectId,
                        status = (int)RowState.Valid,                            
                    };
                    data.businessid = item.businessID;

                    dbContext.siger_wms_stock_access_order_detail.Add(data);

                }
                if (dbContext.SaveChanges() <= 0)
                    throw new BadRequestException(CommonEnum.Fail);
            }
            else
            {
                throw new BadRequestException(CommonEnum.RecordNotFound);
            }
        }
    }
}

