ProductService.cs 15 KB
using Hh.Mes.Common.log;
using Hh.Mes.Common.Request;
using Hh.Mes.Pojo.System;
using Hh.Mes.POJO.Entity;
using Hh.Mes.POJO.EnumEntitys;
using Hh.Mes.POJO.Response;
using Hh.Mes.Service.Repository;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Hh.Mes.Service.WebService.Configure
{

    public class ProductService : RepositorySqlSugar<base_product_header>
    {
        #region 头表
        /// <summary>
        /// //获取列表
        /// </summary>
        public Response GetProductHeaderList(PageReq pageReq, base_product_header entity)
        {
            var result = new Response();
            string orderBy = (pageReq == null || string.IsNullOrEmpty(pageReq.field)) ? "  t1.createTime desc" : $"{pageReq.field} {pageReq.order} ";
            string sqlWhere = SqlWhere(entity);
            //工艺路线过滤已绑定的产品
            //string sqlWhereProcessRoute = " ";
            //if (entity.productCodeOrProductName == "no_process_product_rel") sqlWhereProcessRoute = " t1.productCode not in (select productCode from base_process_product_rel  ) ";
            var stringBuilder = new StringBuilder();
            //页码,页数
            //Exel ture 不分页
            if (!entity.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  t1.* 
                                         from [dbo].[base_product_header] t1    with(nolock)
                                         where {sqlWhere}  
                                         order by {orderBy} ");

            //Exel ture 不分页
            if (!entity.Exel)
            {
                stringBuilder.AppendLine("  offset @offset row fetch next @pageSize row only ");
                stringBuilder.Append($" select rowTotal= count(*) from base_product_header  t1  with(nolock) where {sqlWhere}");
            }
            var parameters = new List<SugarParameter>(){
                new SugarParameter("@productCode",entity.productCode),
                new SugarParameter("@productCodeOrProductName",entity.productCodeOrProductName) };

            var ds = base.Context.Ado.GetDataSetAllAsync(stringBuilder.ToString(), parameters);
            result.Result = ds.Result.Tables[0];
            result.Count = entity.Exel ? (int)result.Result.Rows.Count : (int)ds.Result.Tables[1].Rows[0]["rowTotal"];
            return result;
        }

        public string SqlWhere(base_product_header model)
        {
            var stringBuilder = new StringBuilder();
            stringBuilder.Append("1=1");
            if (!string.IsNullOrEmpty(model.productCode))
            {
                stringBuilder.Append(" and  t1.productCode like '%'+@productCode+'%' ");
            }
            //下拉弹出搜索框
            if (!string.IsNullOrEmpty(model.productCodeOrProductName)&& model.productCodeOrProductName!= "no_process_product_rel")
            {
                stringBuilder.Append(" and  (t1.productCode like   '%'+@productCodeOrProductName+'%' or  t1.productName like  '%'+@productCodeOrProductName+'%' )  ");
            }
            return stringBuilder.ToString();
        }

        public ISqlSugarClient GetContext()
        {
            return base.Context;
        }




        /// <summary>
        /// 新增  code = 字典前缀+对应表标识最大值
        /// </summary>
        /// <returns></returns>
        public dynamic Ins(base_product_header model)
        {
            var response = new Response();
            return ExceptionsHelp.Instance.ExecuteT(() =>
            {
                model.createBy = sysWebUser?.Account;
                model.createTime = DateTime.Now;
                model.keys = Guid.NewGuid();
                var prefix = base.GetDictionaryDictValue("base_product_header");
                var maxValue = GetTableMaxValue<base_product_header>("id");
                model.productCode = prefix + maxValue;
                response.Status = Add(model);
                if (!response.Status) response.Message = SystemVariable.dataActionError;
                return response;
            });
        }


        /// <summary>
        /// 根据主键数组 删除
        /// </summary>
        public dynamic DelByIds(Guid[] ids)
        {
            return ExceptionsHelp.Instance.ExecuteT(() =>
            {
                var Result = new Response();
                Result.Message = "";

                var proHead = Context.Queryable<base_product_header>().In(x => x.keys, ids).Select(x => x.processCode).ToList();
                //查看产品与工艺路线关系表是否存在,存在报错
                var exit = Context.Queryable<base_process_product_rel>().In(x => x.processCode, proHead).ToList();
                if (exit.Count > 0)
                {
                    Result.Code = 500;
                    Result.Message += $"工艺路线工艺路线编码 processCode 为【{proHead[0]}】的产品已经分配了工艺路线,不能删除!";
                    return Result;
                }
                Context.Deleteable<base_product_detail>().In(x => x.headKeys, ids).AddQueue();
                Context.Deleteable<base_product_header>().In(x => x.keys, ids).AddQueue();
                var result = Context.SaveQueues() > 0;
                if (!result)
                {
                    Result.Code = 500;
                    Result.Message = SystemVariable.dataActionError;
                }
                return Result;
            });
        }

        /// <summary>
        /// 更新
        /// </summary>
        public dynamic Upd(base_product_header model)
        {
            var response = new Response();
            return ExceptionsHelp.Instance.ExecuteT(() =>
            {
                model.updateBy = sysWebUser?.Account;
                model.updateTime = DateTime.Now;
                response.Status = Update(model);
                if (!response.Status) response.Message = SystemVariable.dataActionError;
                return response;
            });
        }


        /// <summary>
        /// 导出
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public dynamic ExportData(base_product_header entity)
        {
            return ExceptionsHelp.Instance.ExecuteT(() =>
            {
                var result = GetProductHeaderList(null, entity);
                if (result.Count == 0)
                {
                    result.Result = "[]";
                    result.Count = 0;
                }
                return result;
            }, catchRetrunValue: "list");

        }

        #endregion

        #region 明细
        /// <summary>
        /// 查询方法明细
        /// </summary>
        public Response LoadDesc(PageReq pageReq, base_product_detail model)
        {
            var totalCount = 0;
            var result = new Response();
            var query = Context.Queryable<base_product_detail,base_material>((t1, t2) => 
                                  new JoinQueryInfos(JoinType.Left, t1.materialCode == t2.materialCode))
                                 .Select((t1, t2) => new { 
                                     t1.id, 
                                     t1.materialCode,
                                     t1.headKeys,
                                     t1.createBy,
                                     t1.createTime,

                                     t2.materialName,
                                     t2.mtClassify,
                                     t2.mtTypeCode,
                                     t2.unitCode,
                                     t2.thickness,
                                     t2.diameter,
                                     t2.types
                                 });

            var data = model.headKeyList != null ? query.In(t1 => t1.headKeys, model.headKeyList).ToList() :
                       query.Where(t1 => t1.headKeys == model.headKeys).OrderBy(t1 => t1.id).ToOffsetPage(pageReq.page, pageReq.limit, ref totalCount);
            //页码,页数
            result.Result = data;
            result.Count = totalCount;
            return result;
        }

        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="model">参数</param>
        /// <returns></returns>
        public dynamic InsDesc(base_product_detail model)
        {
            var response = new Response();
            return ExceptionsHelp.Instance.ExecuteT(() =>
            {
                model.createBy = sysWebUser?.Account;
                model.createTime = DateTime.Now;
                response.Status = Add(model);
                if (!response.Status)
                {
                    response.Message = SystemVariable.dataActionError;
                }
                return response;
            });
        }

        /// <summary>
        /// 编辑方法
        /// </summary>
        /// <param name="model">参数</param>
        /// <returns></returns>

        public dynamic UpdDesc(base_product_detail model)
        {
            var response = new Response();
            return ExceptionsHelp.Instance.ExecuteT(() =>
            {
                model.updateBy = sysWebUser?.Account;
                model.updateTime = DateTime.Now;
                response.Status = base.Context.Updateable(model).IgnoreColumns(it => new { it.createBy, it.createTime }).ExecuteCommand() > 0;
                if (!response.Status)
                {
                    response.Message = SystemVariable.dataActionError;
                }
                return response;
            });
        }

        /// <summary>
        /// 删除方法
        /// </summary>
        /// <param name="ids">需要删除的id</param>
        /// <returns></returns>
        public dynamic DelByIdsDesc(int[] ids)
        {
            var response = new Response();
            return ExceptionsHelp.Instance.ExecuteT(() =>
            {
                Context.Deleteable<base_product_detail>().In(ids).AddQueue();
                response.Status = Context.SaveQueues() > 0;
                if (!response.Status)
                {
                    response.Message = SystemVariable.dataActionError;
                }
                return response;

            });
        }

        #endregion}


        /// <summary>
        /// 获取绑定在该 产品的工艺路线的产品
        /// </summary>
        public dynamic GetProductByProductCode(string processCode)
        {
            var response = new Response();
            return ExceptionsHelp.Instance.ExecuteT(() =>
            {
                response.Result = Context.Queryable<base_process_product_rel>().Where(x => x.processCode == processCode).Select(x=>new {  x.productCode}).ToList();
                return response;
            });
        }

        /// <summary>
        ///工艺路线-产品关系表 的新增与删除
        /// </summary>
        /// <returns></returns>
        public dynamic OperateProduct(string processCode, string processName, string productCode, Guid processHeadKeys, string lineCode, bool checkeds)
        {
            var response = new Response();
            return ExceptionsHelp.Instance.ExecuteT(() =>
            {
                string[] strArray = productCode.Split(new char[] { ',' });
                foreach (var item in strArray)
                {
                    if (checkeds)
                    {
                        var isExt = Context.Queryable<base_process_product_rel>().Any(x => x.productCode == item);
                        if (isExt) return response.ResponseError($"产品编码:{productCode},工艺:{processCode},已绑定工艺路线产品关系(工艺和产品一对多,一个产品只能有一个工艺)");

                        var model = new base_process_product_rel
                        {
                            keys=Guid.NewGuid(),
                            processHeadKeys= processHeadKeys,
                            lineCode=lineCode,  
                            processCode = processCode,
                            processName = processName,
                            productCode = item,
                            createBy = sysWebUser?.Account,
                            createTime = DateTime.Now
                        };
                        Context.Insertable(model).AddQueue();
                    }
                    else
                    {
                        Context.Deleteable<base_process_product_rel>().Where(x => x.productCode == item && x.processCode == processCode).AddQueue();
                    }
                }
                response.Status = Context.SaveQueues() > 0;
                if (!response.Status) response.Message = SystemVariable.dataActionError;
                return response.Status ? response.ResponseSuccess() : response.ResponseError();
            });
        }


        /// <summary>
        /// 产品明细 分配物料
        /// </summary>
        /// <param name="teamCode"></param>
        /// <param name="userId"></param>
        /// <param name="flag">(check选择,uncheck 取消)</param>
        public dynamic AssignMaterial(string materialCodes, Guid proHeadKeys, bool checkeds)
        {
            var response = new Response();
            return ExceptionsHelp.Instance.ExecuteT(() =>
            {
                string[] strArray = materialCodes.Split(new char[] { ',' });
                if (checkeds)
                {
                    foreach (var item in strArray)
                    {
                        Context.Deleteable<base_product_detail>().Where(x => x.materialCode == item&&x.headKeys== proHeadKeys).ExecuteCommand();
                        var model = new base_product_detail
                        {
                             materialCode = item,
                             headKeys = proHeadKeys,
                             createBy = sysWebUser?.Account,
                             createTime = DateTime.Now
                        };
                        Context.Insertable(model).AddQueue();
                    }
                    response.Status = Context.SaveQueues() > 0;
                    if (!response.Status)
                    {
                        response.Message = SystemVariable.dataActionError;
                    }
                }
                else
                {
                    foreach (var item in strArray)
                    {
                        Context.Deleteable<base_product_detail>().Where(x => x.headKeys == proHeadKeys).AddQueue();
                    }
                    response.Status = Context.SaveQueues() > 0;
                    if (!response.Status)
                    {
                        response.Message = SystemVariable.dataActionError;
                    }
                }
                return response;
            });
        }

    }

}