ImportMethod.cs 22.5 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513
using Hh.Mes.Common;
using Hh.Mes.Common.config;
using Hh.Mes.Common.log;
using Hh.Mes.Pojo.System;
using Hh.Mes.POJO.Entity;
using Hh.Mes.POJO.Response;
using Hh.Mes.POJO.WebEntity;
using Hh.Mes.Service.Repository;
using MySqlX.XDevAPI.Common;
using MySqlX.XDevAPI.Relational;
using NPOI.OpenXmlFormats.Dml.Diagram;
using NPOI.SS.Formula.Functions;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using static Hh.Mes.Common.Exel.NpoiExcelImportHelper;

namespace Hh.Mes.Service.WebService.Planned
{
    /// <summary>
    /// 定义导入方法加上特性
    /// dicDtSource 添加需要保存到数据源的数据源 
    /// 注意:只改对应业务的dt 数据【公共方法里面的读取的数据源不要修改、其他地方可能需要用到】
    /// </summary>
    public class ImportMethod : RepositorySqlSugar<base_material>
    {
        public string materialDtKey { get; set; }

        public ImportMethod()
        {

        }

        #region 设备管理 Action里面的 equipment  是数据库表名 ,方法名没有特殊要求 ,注意不要删除sysDicDtSource里面的key
        [Action("equipment")]
        public Response EquipmentMethod(Dictionary<string, SysDtAllCls> sysDicDtSource, dynamic user, DateTime nowTime)
        {
            #region init
            var response = new Response();
            //【修改项1】
            var excelFileNameKeys = ExcelName.equipment.ToString();
            response = ImportOhter.ImportMethodBefore(sysDicDtSource, response, excelFileNameKeys);
            if (response.Code != 200) {
                response.Message = $"【{TableName.excelFileNameEquipment}】" + response.Message;
                return response;
            }
            //公共方法数据源,需要判断的数据源单独建一个
            DataTable excelDtSourceDt = response.Result.data;

            DataTable titleVerifySourceDt = response.Result.title;
            #endregion

            #region 创建dt、添加保存到数据库的dicDtSource 【修改项2
            var tableName = TableName.tableNameEquipment;
            var eqSaveDt = GetTableStructure(tableName);
            var temp = new SysDtAllCls()
            {
                dtData = eqSaveDt
            };
            var dtSourceNameKey = tableName + TableName.tableSuffix;
            sysDicDtSource.Add(dtSourceNameKey, temp);
            #endregion

            #region 去重 【修改项3 根据实际业务】
            var tempExcelDtSourceDt = excelDtSourceDt.Distinct("Code");
            #endregion

            #region 赋值  理论上是通用的,修改excel文件名 【修改项4
            var columns = tempExcelDtSourceDt.Columns;
            for (int i = 0; i < tempExcelDtSourceDt.Rows.Count; i++)
            {
                var dr = eqSaveDt.NewRow();
                for (int c = 0; c < columns.Count; c++)
                {
                    var colName = columns[c].ColumnName;
                    dynamic colNameVal = tempExcelDtSourceDt.Rows[i][colName].ToString();
                    response= ImportOhter.SetDataTableDataBefore(response, i, colName, colNameVal, titleVerifySourceDt, TableName.excelFileNameEquipment);
                    if (response.Code != 200) return response;

                    colNameVal = ImportOhter.SetDataTableData(colNameVal, eqSaveDt.Columns[colName].DataType.Name);
                    dr[colName] = colNameVal;
                }

                dr["CreatedBy"] = user.Account;
                dr["Created"] =nowTime;
                eqSaveDt.Rows.Add(dr);
            }
            #endregion

            #region 逻辑判断


            #endregion

            return response;
        }
        #endregion

        #region 用户表 Action里面的 sys_user  是数据库表名 ,方法名没有特殊要求 ,注意不要删除sysDicDtSource里面的key
        [Action("sys_user")]
        public Response SysUserMethod(Dictionary<string, SysDtAllCls> sysDicDtSource, dynamic user, DateTime nowTime)
        {
            #region init
            var response = new Response();
            //【修改项1】
            var excelFileNameKeys = ExcelName.sys_user.ToString();
            response = ImportOhter.ImportMethodBefore(sysDicDtSource, response, excelFileNameKeys);
            if (response.Code != 200)
            {
                response.Message = $"【{TableName.excelFileNameSysUser}】" + response.Message;
                return response;
            }
            //公共方法数据源,需要判断的数据源单独建一个
            DataTable excelDtSourceDt = response.Result.data;

            DataTable titleVerifySourceDt = response.Result.title;
            #endregion

            #region 创建dt、添加保存到数据库的dicDtSource 【修改项2
            var tableName = TableName.tableNameSysUser;
            var eqSaveDt = GetTableStructure(tableName);
            if (eqSaveDt.Columns.Contains("Id")) eqSaveDt.Columns.Remove("Id");
            var temp = new SysDtAllCls()
            {
                dtData = eqSaveDt
            };
            var dtSourceNameKey = tableName + TableName.tableSuffix;
            sysDicDtSource.Add(dtSourceNameKey, temp);
            #endregion

            #region 去重 【修改项3 根据实际业务】
            var tempExcelDtSourceDt = excelDtSourceDt.Distinct("account");
            #endregion

            #region 赋值  理论上是通用的,修改excel文件名 【修改项4
            var columns = tempExcelDtSourceDt.Columns;
            for (int i = 0; i < tempExcelDtSourceDt.Rows.Count; i++)
            {
                var dr = eqSaveDt.NewRow();
                for (int c = 0; c < columns.Count; c++)
                {
                    var colName = columns[c].ColumnName;
                    dynamic colNameVal = tempExcelDtSourceDt.Rows[i][colName].ToString();
                    response = ImportOhter.SetDataTableDataBefore(response, i, colName, colNameVal, titleVerifySourceDt, TableName.excelFileNameSysUser);
                    if (response.Code != 200) return response;

                    colNameVal = ImportOhter.SetDataTableData(colNameVal, eqSaveDt.Columns[colName].DataType.Name);
                    dr[colName] = colNameVal;
                }

                dr["password"] = Encryption.Encrypt(ConfigRead.GetInstance.GetAppsetConnection().ResetPwd);
                dr["status"] = 1;
                dr["createBy"] = user.Account;
                dr["createTime"] = nowTime;
                eqSaveDt.Rows.Add(dr);
            }
            #endregion

            #region 逻辑判断

            //response.ResponseError("");
            //return response;
            #endregion

            return response;
        }
        #endregion

        #region 物料表 Action里面的 base_material  是数据库表名 ,方法名没有特殊要求 ,注意不要删除sysDicDtSource里面的key
        [Action("base_material")]
        public Response BaseMaterialMethod(Dictionary<string, SysDtAllCls> sysDicDtSource, dynamic user, DateTime nowTime)
        {
            #region init
            var response = new Response();
            //【修改项1】
            var excelFileNameKeys = ExcelName.base_material.ToString();
            response = ImportOhter.ImportMethodBefore(sysDicDtSource, response, excelFileNameKeys);
            if (response.Code != 200)
            {
                response.Message = $"【{TableName.excelFileNameBaseMaterial}】" + response.Message;
                return response;
            }
            //公共方法数据源,需要判断的数据源单独建一个
            DataTable excelDtSourceDt = response.Result.data;

            DataTable titleVerifySourceDt = response.Result.title;
            #endregion

            #region 创建dt、添加保存到数据库的dicDtSource 【修改项2
            var tableName = TableName.tableNameBaseMaterial;
            var eqSaveDt = GetTableStructure(tableName);
            if (eqSaveDt.Columns.Contains("Id")) eqSaveDt.Columns.Remove("Id");
            var temp = new SysDtAllCls()
            {
                dtData = eqSaveDt
            };
            var dtSourceNameKey = tableName + TableName.tableSuffix;
            sysDicDtSource.Add(dtSourceNameKey, temp);
            #endregion

            #region 去重 【修改项3 根据实际业务】
            var tempExcelDtSourceDt = excelDtSourceDt.Distinct("materialCode");
            #endregion

            #region 赋值  理论上是通用的,修改excel文件名 【修改项4
            var columns = tempExcelDtSourceDt.Columns;
            for (int i = 0; i < tempExcelDtSourceDt.Rows.Count; i++)
            {
                var dr = eqSaveDt.NewRow();
                for (int c = 0; c < columns.Count; c++)
                {
                    var colName = columns[c].ColumnName;
                    dynamic colNameVal = tempExcelDtSourceDt.Rows[i][colName].ToString();
                    response = ImportOhter.SetDataTableDataBefore(response, i, colName, colNameVal, titleVerifySourceDt, TableName.excelFileNameBaseMaterial);
                    if (response.Code != 200) return response;

                    colNameVal = ImportOhter.SetDataTableData(colNameVal, eqSaveDt.Columns[colName].DataType.Name);
                    dr[colName] = colNameVal;
                }
                dr["keys"]=Guid.NewGuid().ToString();
                dr["createBy"] = user.Account;
                dr["createTime"] = nowTime;
                eqSaveDt.Rows.Add(dr);
            }
            #endregion

            #region 逻辑判断

            //response.ResponseError("");
            //return response;
            #endregion

            return response;
        }
        #endregion

        #region 工艺路线表 Action里面的 base_process_route_head  是数据库表名 ,方法名没有特殊要求 ,注意不要删除sysDicDtSource里面的key
        [Action("base_process_route_head")]
        public Response BaseProcessRouteHeadMethod(Dictionary<string, SysDtAllCls> sysDicDtSource, dynamic user, DateTime nowTime)
        {
            #region init
            var response = new Response();
            //【修改项1】
            var excelFileNameKeys = ExcelName.base_process_route_head.ToString();
            response = ImportOhter.ImportMethodBefore(sysDicDtSource, response, excelFileNameKeys);
            if (response.Code != 200)
            {
                response.Message = $"【{TableName.excelFileNameBaseProcessRouteHead}】" + response.Message;
                return response;
            }
            //公共方法数据源,需要判断的数据源单独建一个
            DataTable excelDtSourceDt = response.Result.data;

            DataTable titleVerifySourceDt = response.Result.title;
            #endregion

            #region 创建dt、添加保存到数据库的dicDtSource 【修改项2
            var tableName = TableName.tableNameBaseProcessRouteHead;
            var eqSaveDt = GetTableStructure(tableName);
            if (eqSaveDt.Columns.Contains("Id")) eqSaveDt.Columns.Remove("Id");
            var temp = new SysDtAllCls()
            {
                dtData = eqSaveDt
            };
            var dtSourceNameKey = tableName + TableName.tableSuffix;
            sysDicDtSource.Add(dtSourceNameKey, temp);
            #endregion

            #region 去重 【修改项3 根据实际业务】
            var tempExcelDtSourceDt = excelDtSourceDt.Distinct("processCode");
            #endregion
            ///////////////////////////////////////////////////////////////////
            #region 工艺路线明细
            #region init
            var response2 = new Response();
            //【修改项1】
            var excelFileNameKeys2 = ExcelName.base_process_route_detail.ToString();
            response2 = ImportOhter.ImportMethodBefore(sysDicDtSource, response2, excelFileNameKeys2);
            if (response2.Code != 200)
            {
                response2.Message = $"【{TableName.excelFileNameBaseProcessRouteDetail}】" + response2.Message;
                return response2;
            }
            //公共方法数据源,需要判断的数据源单独建一个
            DataTable excelDtSourceDt2 = response2.Result.data;

            DataTable titleVerifySourceDt2 = response2.Result.title;
            #endregion

            #region 创建dt、添加保存到数据库的dicDtSource 【修改项2
            var tableName2 = TableName.tableNameBaseProcessRouteDetail;
            var eqSaveDt2 = GetTableStructure(tableName2);
            if (eqSaveDt2.Columns.Contains("Id")) eqSaveDt2.Columns.Remove("Id");
            var temp2 = new SysDtAllCls()
            {
                dtData = eqSaveDt2
            };
            var dtSourceNameKey2 = tableName2 + TableName.tableSuffix;
            sysDicDtSource.Add(dtSourceNameKey2, temp2);
            #endregion

            #region 去重 【修改项3 根据实际业务】
            var tempExcelDtSourceDt_detail = excelDtSourceDt2.Distinct("oprSequenceCode");
            #endregion

            #endregion

            #region 赋值  理论上是通用的,修改excel文件名 【修改项4
            var columns = tempExcelDtSourceDt.Columns;
            var detail_columns=tempExcelDtSourceDt_detail.Columns;
            for (int i = 0; i < tempExcelDtSourceDt.Rows.Count; i++)
            {
                var dr = eqSaveDt.NewRow();
                for (int c = 0; c < columns.Count; c++)
                {
                    var colName = columns[c].ColumnName;
                    dynamic colNameVal = tempExcelDtSourceDt.Rows[i][colName].ToString();
                    response = ImportOhter.SetDataTableDataBefore(response, i, colName, colNameVal, titleVerifySourceDt, TableName.excelFileNameBaseProcessRouteHead);
                    if (response.Code != 200) return response;

                    colNameVal = ImportOhter.SetDataTableData(colNameVal, eqSaveDt.Columns[colName].DataType.Name);
                    dr[colName] = colNameVal;
                }
                dr["keys"] = Guid.NewGuid().ToString();
                dr["createBy"] = user.Account;
                dr["createTime"] = nowTime;
                dr["productCode"] = "";
                dr["productHeaderCode"] = "";
                eqSaveDt.Rows.Add(dr);

                //明细表赋值
                for (int j = 0; j < tempExcelDtSourceDt_detail.Rows.Count; j++)
                {
                    var dr2 = eqSaveDt2.NewRow();
                    for (int c = 0; c < detail_columns.Count; c++)
                    {
                        var colName = detail_columns[c].ColumnName;
                        dynamic colNameVal = tempExcelDtSourceDt_detail.Rows[j][colName].ToString();
                        response2 = ImportOhter.SetDataTableDataBefore(response2, j, colName, colNameVal, titleVerifySourceDt2, TableName.excelFileNameBaseProcessRouteDetail);
                        if (response2.Code != 200) return response2;

                        colNameVal = ImportOhter.SetDataTableData(colNameVal, eqSaveDt2.Columns[colName].DataType.Name);
                        dr2[colName] = colNameVal;
                    }
                    dr2["headkeys"] = dr["keys"];
                    dr2["bodyKeys"] = Guid.NewGuid().ToString();
                    dr2["createBy"] = user.Account;
                    dr2["createTime"] = nowTime;
                    eqSaveDt2.Rows.Add(dr2);
                }
            }
            #endregion

            #region 逻辑判断
            #endregion

            return response;
        }

        #endregion

        
        #region Save BaseProcessRoute Success After
        /// <summary>
        /// 工艺路线表保存之后
        /// </summary>
        /// <param name="baseProcessRoute"></param>
        public void SaveSuccessAfterBaseProcessRoute(Dictionary<string, SysDtAllCls> sysDicDtSource,dynamic sysWebUser)
        {

            var response = new Response();
            var excelFileNameKeys = ExcelName.base_process_route_head.ToString();
            response = ImportOhter.ImportMethodBefore(sysDicDtSource, response, excelFileNameKeys);
            DataTable dt = response.Result.data;

            response=ImportOhter.ImportMethodBefore(sysDicDtSource,response,ExcelName.base_process_route_detail.ToString());
            DataTable dt_detail = response.Result.data; 

            AddBaseProcessProductRel(dt, sysWebUser?.Account);
            AddBaseWorkCenter(dt_detail, sysWebUser?.Account);
        }

        /// <summary>
        /// productCode 还是需要这个字段逗号隔开,用于生成 base_process_product_rel表;base_product_header不存在新增,存在跳过;
        /// </summary>
        /// <param name="product"></param>
        /// <param name="dr"></param>
        /// <param name="user"></param>
        private void AddBaseProcessProductRel(DataTable dt,string user)
        {
            //产品保存到base_process_product_rel表
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                string[] products = dt.Rows[i]["productCode"]?.ToString().Split(',');
                var dr = dt.Rows[i];
                if (products != null)
                {
                    foreach (var p in products)
                    {
                        var sql = $@"insert into base_process_product_rel (keys,processCode,processName,productCode,createBy,createTime)
                              values( '{Guid.NewGuid()}','{dr["processCode"]}','{dr["processName"]}','{p}','{user}','{DateTime.Now}')";
                        var isHave = Context.Queryable<base_process_product_rel>().Where(x => x.processCode == dr["processCode"].ToString() && x.productCode == p).ToList();
                        var result = 0;
                        if (isHave.Count <= 0)//同时满足(相同工艺相同产品)条件;不存在新增,存在跳过
                        {
                            result = base.Context.Ado.ExecuteCommand(sql);
                        }
                        //保存 base_product_header 不存在新增、存在跳过
                        var ProcessHeadKeys = Context.Queryable<base_process_route_head>().Where(x => x.processCode == dr["processCode"].ToString())?.First();
                        sql = $@"INSERT INTO base_product_header (keys, productCode, productName, processCode, createTime, createBy,processHeadKeys)
                         VALUES('{Guid.NewGuid()}', '{p}', '', '{dr["processCode"]}', '{DateTime.Now}', '{user}', '{ProcessHeadKeys?.keys}');";
                        var isSave = Context.Queryable<base_product_header>().Where(x => x.processCode == dr["processCode"].ToString() && x.productCode == p).ToList();
                        if (isSave.Count <= 0)
                        {
                            result = base.Context.Ado.ExecuteCommand(sql);
                        }

                        if (result <= 0 && isHave.Count <= 0 )
                        {
                            Log4NetHelper.Instance.Error($"【ImportMethod-AddBaseProcessProductRel 执行新增工艺产品列表信息失败 sql】" + sql);
                        }

                        if (result <= 0 && isSave.Count <= 0)
                        {
                            Log4NetHelper.Instance.Error($"【ImportMethod-AddBaseProductHeader 执行新增产品设置信息失败 sql】" + sql);
                        }
                    }
                }
            }
        }

        /// <summary>
        /// workCenterCode、workCenterName:保存到 base_work_center 表,不存在新增、存在跳过
        /// </summary>
        private void AddBaseWorkCenter(DataTable dt, string user)
        {
            for(int i=0; i < dt.Rows.Count; i++)
            {
                var dr = dt.Rows[i];
                var sql = $@"insert into base_work_center ([key],workCenterCode,workCenterName,createBy,createTime)
                              values( '{Guid.NewGuid()}','{dr["workCenterCode"]}','{dr["workCenterName"]}','{user}','{DateTime.Now}')";
                var isHave = Context.Queryable<base_work_center>().Where(x => x.workCenterCode == dr["workCenterCode"].ToString()).ToList();
                var result = 0;
                if (isHave.Count <= 0)//不存在新增,存在跳过
                {
                    result = base.Context.Ado.ExecuteCommand(sql);
                }

                if (result <= 0 && isHave.Count<=0)
                {
                    Log4NetHelper.Instance.Error($"【ImportMethod-Addbase_work_center 执行新增工作重心失败 sql】" + sql);
                }
            }
        }
        #endregion


        #region Save SysUser Success After 
        /// <summary>
        /// SysUser表保存成功之后
        /// </summary>
        /// <param name="dateTime"></param>
        public void SaveSuccessAfterSysUesr(DateTime dateTime,dynamic sysWebUser)
        {
            UpdateSysRelevance(sysWebUser.Account);
        }
        /// <summary>
        /// 更新部门关联的用户
        /// </summary>
        private void UpdateSysRelevance(string user)
        {
            // UserOrg:用户机构关联KEY 
            var relKey = "UserOrg";
            // 26:是“工艺管线预制车间”==>“巨驰”的部门ID
            var deptId = 26;
            var sql = $@"insert into sys_relevance (relKey,firstId,secondId,createBy)
                         select  UserOrg='{relKey}' , 
		                         t1.id ,
		                         secondId={deptId},
		                         createBy='{user}' 
                        from  sys_user t1 with (nolock)
                        left join  (select distinct firstId from sys_relevance) t2 on t1.id=t2.firstId
                        where   t2.firstId  is null";
            var result = base.Context.Ado.ExecuteCommand(sql);

            if (result <= 0)
            {
                Log4NetHelper.Instance.Error($"【ImportMethod-UpdateSysRelevance 执行更新部门关联的用户失败 sql】" + sql);
            }
        }
        #endregion

        #region 公共方法

        /// <summary>
        /// 获取表结构 没有数据源,并设置dt的表名 ,去掉id列
        /// </summary>
        public DataTable GetTableStructure(string tableName)
        {
            var sql = $"select * from {tableName} where 1!=1";
            var dt = base.Context.Ado.GetDataTable(sql);
            dt.TableName = tableName;
            //var columnsId = "id";
            // if (dt.Columns.Contains(columnsId)) dt.Columns.Remove(columnsId);
            return dt;
        }


        #endregion
    }
}