MaterialDistributeLoadTemplateService.cs 14.7 KB
using Hh.Mes.Common.Json;
using Hh.Mes.Common.log;
using Hh.Mes.Common.Request;
using Hh.Mes.Pojo.System;
using Hh.Mes.POJO.Entity;
using Hh.Mes.Service.Repository;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using Hh.Mes.POJO.Response;

namespace Hh.Mes.Service.Distribution
{
    /// <summary>
    /// 装料数据模板
    /// </summary>
    public class MaterialDistributeLoadTemplateService : RepositorySqlSugar<bus_material_distribute_load_template_head>
    {
        #region 头表
        /// <summary>
        /// //获取列表
        /// </summary>
        public Response Load(PageReq pageReq, bus_material_distribute_load_template_head model)
        {
            var result = new Response();
            string orderBy = (pageReq == null || string.IsNullOrEmpty(pageReq.field)) ? " id desc" : $"{pageReq.field} {pageReq.order} ";
            string sqlWhere = SqlWhere(model);
            var stringBuilder = new StringBuilder();
            //页码,页数
            //Exel ture 不分页
            if (!model.Exel && pageReq != null)
            {
                stringBuilder.Append("declare @pageIndex int,@pageSize int,@offset int");
                stringBuilder.AppendLine($"  select @pageIndex={pageReq.page}, @pageSize={pageReq.limit}, @offset=(@pageIndex - 1) * @pageSize");
            }

            stringBuilder.AppendLine($@" select  * 
                                         from bus_material_distribute_load_template_head t1  with(nolock)
                                         where {sqlWhere}
                                         order by {orderBy} ");

            //Exel ture 不分页
            if (!model.Exel)
            {
                stringBuilder.AppendLine("  offset @offset row fetch next @pageSize row only ");
                stringBuilder.Append($" select rowTotal= count(*) from bus_material_distribute_load_template_head  with(nolock) where {sqlWhere}");
            }
            var ds = base.Context.Ado.GetDataSetAll(stringBuilder.ToString(), new List<SugarParameter>{
                new SugarParameter("@productCode",model.productCode)
            });
            result.Result = ds.Tables[0];
            result.Count = model.Exel ? (int)result.Result.Rows.Count : (int)ds.Tables[1].Rows[0]["rowTotal"];
            return result;
        }

        public string SqlWhere(bus_material_distribute_load_template_head model)
        {
            var sb = new StringBuilder();
            sb.Append("1=1");
            if (!string.IsNullOrWhiteSpace(model.productCode)) sb.Append(" and  t1.productCode like  '%'+@productCode+'%' ");
            return sb.ToString();
        }


        /// <summary>
        /// 新增 装料模板 head,body
        /// </summary>
        /// <returns></returns>
        public dynamic Ins(string str)
        {
            var response = new Response();
            return ExceptionsHelp.Instance.ExecuteT(() =>
            {
                var model = JsonHelper.JsonConvertObject<MateLoadingTemplate>(str);
                var isExt = Context.Queryable<bus_material_distribute_load_template_head>().Where(it => it.productCode == model.head.ProductCode).Any();
                if (isExt) return response.ResponseError($"产品号为:{model.head.ProductCode}已存在请勿重复添加");

                //
                var wcsProductType = string.IsNullOrEmpty(model.head.WcsProductType) ? -1 : int.Parse(model.head.WcsProductType);
                var head = new bus_material_distribute_load_template_head
                {
                    id = 0,
                    keys = Guid.NewGuid(),
                    productCode = model.head.ProductCode,
                    wcsProductType = wcsProductType,
                    loadQty=model.head.loadQty,

                    createBy = sysWebUser.Account,
                    createTime = DateTime.Now
                };
                var body = SetMateLoadTemplateBody(model, head.keys, "add");
                base.Context.Insertable(head).AddQueue();
                base.Context.Insertable(body).AddQueue();
                if (ExecuteQueues(Context) <= 0)
                {
                    return response.ResponseError(SystemVariable.dataActionError);

                }
                return response.ResponseSuccess(SystemVariable.dataActionOk);
            });

        }


        /// <summary>
        /// 更新 装料模板
        /// </summary>
        public dynamic Upd(string str)
        {
            var response = new Response();
            return ExceptionsHelp.Instance.ExecuteT(() =>
            {
                var model = JsonHelper.JsonConvertObject<MateLoadingTemplate>(str);
                var head = new Dictionary<string, object>
                {
                    { "id", model.head.id },
                    { "productCode", model.head.ProductCode },
                    { "wcsProductType", model.head.WcsProductType  },
                    { "loadQty", model.head.loadQty  },
 
                    { "updateTime", DateTime.Now  },
                    { "updateBy", sysWebUser.Account }
                };
                base.Context.Updateable(head).AS("bus_material_distribute_load_template_head").WhereColumns("id").AddQueue();

                var body = SetMateLoadTemplateBody(model, model.head.keys, "edit");
                for (int i = 0; i < body.Count; i++)
                {
                    var body1 = body[i];
                    base.Context.Updateable(body1).UpdateColumns(x => new
                    {
                        x.materialCode,
                        x.row,
                        x.line,
                        x.layer,
                        x.qty,

                        x.updateBy,
                        x.updateTime,

                    }).Where(x => x.id == body1.id).AddQueue();
                }
                if (ExecuteQueues(Context) <= 0)
                {
                    return response.ResponseError(SystemVariable.dataActionError);
                }
                return response.ResponseSuccess(SystemVariable.dataActionOk);
            });
        }


        /// <summary>
        /// 装料模板 编辑获取数据
        /// </summary>
        public dynamic GetMateLoadTemplateListById(Guid keys)
        {
            return ExceptionsHelp.Instance.ExecuteT(() =>
            {
                string sql = $@" DECLARE @keys  uniqueidentifier ;
                                 set @keys='{keys}';
                                 select * from dbo.bus_material_distribute_load_template_head where keys=@keys

                                 if OBJECT_ID('tempdb..#temp') is not null
                                 drop table #temp
                                 select id ,headKeys ,containerType ,sequence,materialCode,row,line ,layer ,qty into #temp 
                                 from  bus_material_distribute_load_template_detail
                                 where headKeys=@keys;
                                 select * from #temp  where containerType='A'
                                 select * from #temp  where containerType='B'
                                 select * from #temp  where containerType='C'";
                var ds = base.Context.Ado.GetDataSetAllAsync(sql).Result;
                var result = new
                {
                    Code = 200,
                    Status = true,
                    Message = "ok",
                    head = ds.Tables[0],
                    body = new
                    {
                        a = ds.Tables[1],
                        b = ds.Tables[2],
                        c = ds.Tables[3]
                    }
                };
                return result;
            });
        }

        /// <summary>
        /// 删除
        /// </summary>
        public dynamic DelByIds(Guid[] ids)
        {
            var response = new Response();
            return ExceptionsHelp.Instance.ExecuteT(() =>
            {
                Context.Deleteable<bus_material_distribute_load_template_head>().In(x => x.keys, ids).AddQueue();
                foreach (var id in ids)
                {
                    Context.Deleteable<bus_material_distribute_load_template_detail>().Where(it => it.headKeys == id).AddQueue();
                }
                var result = Context.SaveQueues();
                if (result <= 0) return response.ResponseError(SystemVariable.dataActionError);
                return response;
            });
        }


        /// <summary>
        /// 导出方法
        /// </summary>
        /// <returns></returns>
        public Task<dynamic> Export(bus_material_distribute_load_template_head Table_Entity)
        {
            return ExceptionsHelp.Instance.ExecuteT(() =>
            {
                var result = new Response();
                var dataTable = Load(null, Table_Entity);
                if (dataTable.Count == 0)
                {
                    result.Result = null;
                    result.Message = "没有查询到数据!";
                    result.Code = -1;
                    return result;
                }
                var guids = new List<Guid>();
                foreach (var item in dataTable.Result)
                {
                    guids.Add((Guid)item.keys);
                }
                var data = LoadDesc(null, new bus_material_distribute_load_template_detail { headKeyList = guids });
                result.Result = new
                {
                    head = dataTable.Result,
                    body = data.Result
                };
                return result;
            });
        }
        #endregion

        #region 明细


        /// <summary>
        /// //获取列表 C是 containerType 容器类型
        /// </summary>
        public Response LoadDesc(PageReq pageReq, bus_material_distribute_load_template_detail model)
        {
            var data = model.headKeyList != null
                ? base.Context.Queryable<bus_material_distribute_load_template_detail>().In(it => it.headKeys, model.headKeyList).ToList()
                : base.Context.Queryable<bus_material_distribute_load_template_detail>().Where(it => it.headKeys == model.headKeys&&it.containerType!="C").ToList();
            var result = new Response
            {
                Code = 200,
                Result = data,
                Count = data.Count
            };
            return result;
        }

        #endregion

        private List<bus_material_distribute_load_template_detail> SetMateLoadTemplateBody(MateLoadingTemplate model, Guid keys, string addOrEdit)
        {

            var list = new List<bus_material_distribute_load_template_detail>();
            var add = "add";
            var edit = "edit";
            for (int i = 0; i < model.body.a.Count; i++)
            {
                var cls = new bus_material_distribute_load_template_detail
                {
                    id = model.body.a[i].id,
                    headKeys = keys,
                    bodyKeys = addOrEdit == add ? Guid.NewGuid() : model.body.a[i].bodyKeys,
                    containerType = "A",
                    materialCode = model.body.a[i].materialCode,
                    sequence = model.body.a[i].sequence,

                    row = string.IsNullOrEmpty(model.body.a[i].row) ? null : int.Parse(model.body.a[i].row) as int?,
                    line = string.IsNullOrEmpty(model.body.a[i].line) ? null : int.Parse(model.body.a[i].line) as int?,
                    layer = string.IsNullOrEmpty(model.body.a[i].layer) ? null : int.Parse(model.body.a[i].layer) as int?,
                    qty = string.IsNullOrEmpty(model.body.a[i].qty) ? null : int.Parse(model.body.a[i].qty) as int?,

                    createBy = addOrEdit == add ? sysWebUser.Account : "",
                    createTime = addOrEdit == add ? (DateTime?)DateTime.Now : null,
                    updateBy = addOrEdit == edit ? sysWebUser.Account : "",
                    updateTime = addOrEdit != edit ? (DateTime?)DateTime.Now : null
                };
                list.Add(cls);
            }

            for (int i = 0; i < model.body.b.Count; i++)
            {
                var cls = new bus_material_distribute_load_template_detail
                {
                    id = model.body.b[i].id,
                    headKeys = keys,
                    bodyKeys = addOrEdit == add ? Guid.NewGuid() : model.body.b[i].bodyKeys,
                    containerType = "B",
                    materialCode = model.body.b[i].materialCode,
                    sequence = model.body.b[i].sequence,

                    row = string.IsNullOrEmpty(model.body.b[i].row) ? null : int.Parse(model.body.b[i].row) as int?,
                    line = string.IsNullOrEmpty(model.body.b[i].line) ? null : int.Parse(model.body.b[i].line) as int?,
                    layer = string.IsNullOrEmpty(model.body.b[i].layer) ? null : int.Parse(model.body.b[i].layer) as int?,
                    qty = string.IsNullOrEmpty(model.body.b[i].qty) ? null : int.Parse(model.body.b[i].qty) as int?,

                    createBy = addOrEdit == add ? sysWebUser.Account : "",
                    createTime = addOrEdit == add ? (DateTime?)DateTime.Now : null,
                    updateBy = addOrEdit == edit ? sysWebUser.Account : "",
                    updateTime = addOrEdit != edit ? (DateTime?)DateTime.Now : null
                };
                list.Add(cls);
            }

            for (int i = 0; i < model.body.c.Count; i++)
            {
                var cls = new bus_material_distribute_load_template_detail
                {
                    id = model.body.c[i].id,
                    headKeys = keys,

                    bodyKeys = addOrEdit == add ? Guid.NewGuid() : model.body.c[i].bodyKeys,
                    containerType = "C",
                    materialCode = model.body.c[i].materialCode,
                    sequence = model.body.c[i].sequence,

                    row = string.IsNullOrEmpty(model.body.c[i].row) ? null : int.Parse(model.body.c[i].row) as int?,
                    line = string.IsNullOrEmpty(model.body.c[i].line) ? null : int.Parse(model.body.c[i].line) as int?,
                    layer = string.IsNullOrEmpty(model.body.c[i].layer) ? null : int.Parse(model.body.c[i].layer) as int?,
                    qty = string.IsNullOrEmpty(model.body.c[i].qty) ? null : int.Parse(model.body.c[i].qty) as int?,

                    createBy = addOrEdit == add ? sysWebUser.Account : "",
                    createTime = addOrEdit == add ? (DateTime?)DateTime.Now : null,
                    updateBy = addOrEdit == edit ? sysWebUser.Account : "",
                    updateTime = addOrEdit != edit ? (DateTime?)DateTime.Now : null
                };
                list.Add(cls);
            }
            return list;
        }
    }
}