chenhaozhe
3 天以前 da84e4e72c9d9cc7e2bd40dc4bb7b3222ca3519a
WebAPI/Controllers/³É±¾¹ÜÀí/CB_ItemMoneyBillController.cs
@@ -6,8 +6,13 @@
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Web;
using System.Web.Http;
using WebAPI.Models;
using WebAPI.Controllers.SCGL.日计划管理;
using System.IO;
using System.Linq;
using System.Text;
namespace WebAPI.Controllers
{
@@ -950,5 +955,463 @@
        #endregion
        #region æ–‡ä»¶ä¸Šä¼ 
        [Route("CB_ItemMoneyBillController/CB_ItemMoneyBill_Excel")]
        [HttpPost]
        public json CB_ItemMoneyBill_Excel()
        {
            json res = new json();
            try
            {
                //获取文件名称
                var file = HttpContext.Current.Request.Files[0];
                //获取文件物理路径
                string ExcelPath = HttpContext.Current.Server.MapPath("~/" + file.FileName);
                //保存文件
                file.SaveAs(ExcelPath);
                SCGL.日计划管理.NpoiHelper np = new NpoiHelper();
                DataSet ExcelDs = np.ReadExcel(ExcelPath, 1, 1, "0");
                //删除文件
                File.Delete(ExcelPath);
                //创建临时表
                DataTable provisional = new DataTable("dt2");
                //添加列名
                for (int i = 0; i < ExcelDs.Tables[0].Columns.Count; i++)
                {
                    provisional.Columns.Add(ExcelDs.Tables[0].Rows[0][i].ToString());
                }
                provisional.Columns.Add("单据号", typeof(string));
                //添加数据
                for (int i = 1; i < ExcelDs.Tables[0].Rows.Count; i++)
                {
                    DataRow row = provisional.NewRow();
                    for (int j = 0; j < ExcelDs.Tables[0].Columns.Count; j++)
                    {
                        row[j] = ExcelDs.Tables[0].Rows[i][j].ToString();
                    }
                    provisional.Rows.Add(row);
                }
                //判断列
                string error = JudgmentColumns(provisional);
                if (error.Length > 0)
                {
                    res.code = "0";
                    res.count = 0;
                    res.Message = $"Excel模板存在错误,{error}\r\n";
                    res.data = null;
                    return res;
                }
                for (int i = 0; i <= provisional.Rows.Count - 1; i++)
                {
                    //string HBillNo= DBUtility.ClsPub.CreateBillCode("1802", ref DBUtility.ClsPub.sExeReturnInfo, true);
                    //provisional.Rows[i]["单据号"] = HBillNo;
                    string HDepNumber = DBUtility.ClsPub.isStrNull(provisional.Rows[i]["部门代码"].ToString());
                    string HDepName = DBUtility.ClsPub.isStrNull(provisional.Rows[i]["部门"].ToString());
                    string HEmpNumber = DBUtility.ClsPub.isStrNull(provisional.Rows[i]["职员代码"].ToString());
                    string HEmpName = DBUtility.ClsPub.isStrNull(provisional.Rows[i]["职员"].ToString());
                    string HICMOBillNo = DBUtility.ClsPub.isStrNull(provisional.Rows[i]["生产订单号"].ToString());
                    string HProc = DBUtility.ClsPub.isStrNull(provisional.Rows[i]["工序"].ToString());
                    string HCostItemNumber = DBUtility.ClsPub.isStrNull(provisional.Rows[i]["成本项目代码"].ToString());
                    string HCostItemName = DBUtility.ClsPub.isStrNull(provisional.Rows[i]["成本项目"].ToString());
                    //string HEntryID = DBUtility.ClsPub.isStrNull(provisional.Rows[i]["子表内码"].ToString());
                    //string HDepNumber_sub = DBUtility.ClsPub.isStrNull(provisional.Rows[i]["子部门代码"].ToString());
                    //string HDepName_sub = DBUtility.ClsPub.isStrNull(provisional.Rows[i]["子部门"].ToString());
                    string HMaterNumber = DBUtility.ClsPub.isStrNull(provisional.Rows[i]["物料编码"].ToString());
                    string HMaterName = DBUtility.ClsPub.isStrNull(provisional.Rows[i]["物料名称"].ToString());
                    string HQty = DBUtility.ClsPub.isStrNull(provisional.Rows[i]["数量"].ToString());
                    string HPrice = DBUtility.ClsPub.isStrNull(provisional.Rows[i]["单价"].ToString());
                    string HMoney = DBUtility.ClsPub.isStrNull(provisional.Rows[i]["金额"].ToString());
                    string HWaster = DBUtility.ClsPub.isStrNull(provisional.Rows[i]["损耗量"].ToString());
                    //string HRelationQty = DBUtility.ClsPub.isStrNull(provisional.Rows[i]["关联数量"].ToString());
                    //string HRelationMoney = DBUtility.ClsPub.isStrNull(provisional.Rows[i]["关联金额"].ToString());
                    string remark = DBUtility.ClsPub.isStrNull(provisional.Rows[i]["备注"].ToString());
                    //获取真实行数
                    int line = i + 1;
                }
                res.code = "1";
                res.count = 1;
                res.Message = error;
                res.data = provisional;
                return res;
            }
            catch (Exception e)
            {
                res.code = "0";
                res.count = 0;
                res.Message = "Exception!" + e.ToString();
                res.data = null;
                return res;
            }
        }
        /// <summary>
        /// åˆ¤æ–­åˆ—
        /// </summary>
        /// <param name="provisional"></param>
        /// <returns></returns>
        private static string JudgmentColumns(DataTable provisional)
        {
            var error = "";
            //查询没有的列
            //if (!provisional.Columns.Contains("子表内码"))
            //    error += "没有找到【子表内码】的标题,";
            if (!provisional.Columns.Contains("物料编码"))
                error += "没有找到【物料编码】的标题,";
            return error;
        }
        #endregion
        #region ä¸Šä¼ ä¿å­˜
        [Route("CB_ItemMoneyBillController/Excel_btnSave")]
        [HttpPost]
        public object Excel_btnSave([FromBody] JObject sMainSub)
        {
            var _value = sMainSub["sMainSub"].ToString();
            string msg1 = _value.ToString();
            string[] sArray = msg1.Split(new string[] { "&和" }, StringSplitOptions.RemoveEmptyEntries);
            string msg2 = sArray[0].ToString();
            string user = sArray[1].ToString();
            string organ = sArray[2].ToString();
            json res = new json();
            try
            {
                oCN.BeginTran();
                List<object> Excel = Newtonsoft.Json.JsonConvert.DeserializeObject<List<object>>(msg2);
                List<Dictionary<string, string>> list = new List<Dictionary<string, string>>();
                foreach (JObject item in Excel)
                {
                    Dictionary<string, string> dic = new Dictionary<string, string>();
                    foreach (var itm in item.Properties())
                    {
                        dic.Add(itm.Name, itm.Value.ToString());
                    }
                    list.Add(dic);
                }
                // 1. æ”¶é›†æ‰€æœ‰éœ€è¦æŸ¥è¯¢çš„æ•°æ®
                var HBillnos = list.Select(x => x["单据号"].ToString()).Distinct().ToList();
                var HProc = list.Select(x => x["工序"].ToString()).Distinct().ToList();
                //var HDeptNames = list.Select(x => x["部门"].ToString()).Distinct().ToList();
                //var HDeptNumbers = list.Select(x => x["部门代码"].ToString()).Distinct().ToList();
                var HDeptNames_sub = list.Select(x => x["部门"].ToString()).Distinct().ToList();
                var HDeptNumbers_sub = list.Select(x => x["部门代码"].ToString()).Distinct().ToList();
                var materialNumbers = list.Select(x => x["物料编码"].ToString()).Distinct().ToList();
                var materialNames = list.Select(x => x["物料名称"].ToString()).Distinct().ToList();
                //var EmpNumbers = list.Select(x => x["职员代码"].ToString()).Distinct().ToList();
                //var EmpNames = list.Select(x => x["职员"].ToString()).Distinct().ToList();
                var EmpNumbers = list.Select(x => x["职员代码"]?.ToString())
                     .Where(s => !string.IsNullOrEmpty(s))
                     .Distinct()
                     .ToList();
                var EmpNames = list.Select(x => x["职员"]?.ToString())
                                   .Where(s => !string.IsNullOrEmpty(s))
                                   .Distinct()
                                   .ToList();
                var CostNumbers = list.Select(x => x["成本项目代码"].ToString()).Distinct().ToList();
                var CostNames = list.Select(x => x["成本项目"].ToString()).Distinct().ToList();
                var ICMONumbers = list.Select(x => x["生产订单号"].ToString()).Distinct().ToList();
                // 2. æ‰¹é‡æŸ¥è¯¢ç”Ÿäº§è®¢å•内码
                string ICMOQuery = $"SELECT HInterID,HBillNo FROM Sc_ICMOBillMain WHERE HBillNo IN ({string.Join(",", ICMONumbers.Select(s => $"'{s.Replace("'", "''")}'"))}) and HPRDORGID={organ}";
                DataSet icmoData = oCN.RunProcReturn(ICMOQuery, "Sc_ICMOBillMain");
                Dictionary<string, int> ICMODict = new Dictionary<string, int>();
                foreach (DataRow row in icmoData.Tables[0].Rows)
                {
                    ICMODict[row["HBillNo"].ToString()] = (int)row["HInterID"];
                }
                //// 2. æ‰¹é‡æŸ¥è¯¢ä¸»å­è¡¨éƒ¨é—¨ä¿¡æ¯
                //string supplierQuery = $"SELECT HItemID, HName FROM Gy_Department WHERE HName IN ({string.Join(",", HDeptNames.Select(s => $"'{s.Replace("'", "''")}'"))})";
                //DataSet supData = oCN.RunProcReturn(supplierQuery, "Gy_Department");
                //Dictionary<string, int> supplierDict = new Dictionary<string, int>();
                //foreach (DataRow row in supData.Tables[0].Rows)
                //{
                //    supplierDict[row["HName"].ToString()] = (int)row["HItemID"];
                //}
                // 2.1 æ‰¹é‡æŸ¥è¯¢ä¸»å­è¡¨éƒ¨é—¨ä¿¡æ¯
                string supplierQuery_sub = $"SELECT HItemID, HName FROM Gy_Department WHERE HName IN ({string.Join(",", HDeptNames_sub.Select(s => $"'{s.Replace("'", "''")}'"))}) and HUSEORGID ={organ}";
                DataSet supData_sub = oCN.RunProcReturn(supplierQuery_sub, "Gy_Department");
                Dictionary<string, int> supplierDict_sub = new Dictionary<string, int>();
                foreach (DataRow row in supData_sub.Tables[0].Rows)
                {
                    supplierDict_sub[row["HName"].ToString()] = (int)row["HItemID"];
                }
                // 3. æ‰¹é‡æŸ¥è¯¢ç‰©æ–™ä¿¡æ¯
                string materialQuery =
                $"SELECT HItemID, HNumber, HName FROM Gy_Material WHERE HNumber IN ({string.Join(",", materialNumbers.Select(m => $"'{m.Replace("'", "''")}'"))}) AND HName IN ({string.Join(",", materialNames.Select(m => $"'{m.Replace("'", "''")}'"))})  and HUSEORGID ={organ}";
                DataSet materData = oCN.RunProcReturn(materialQuery, "Gy_Material");
                Dictionary<string, int> materialDict = new Dictionary<string, int>();
                foreach (DataRow row in materData.Tables[0].Rows)
                {
                    string key = $"{row["HNumber"]}_{row["HName"]}";
                    materialDict[key] = (int)row["HItemID"];
                }
                if (EmpNames.Count == 0 && EmpNumbers.Count == 0)
                {
                }
                // 3. æ‰¹é‡æŸ¥è¯¢èŒå‘˜ä¿¡æ¯
                string empNumbersIn = EmpNumbers.Any()
                    ? string.Join(",", EmpNumbers.Select(m => $"'{m.Replace("'", "''")}'"))
                    : "''";
                string empNamesIn = EmpNames.Any()
                    ? string.Join(",", EmpNames.Select(m => $"'{m.Replace("'", "''")}'"))
                    : "''";
                string EmployeeQuery = $"SELECT HItemID, HNumber, HName FROM Gy_Employee WHERE HNumber IN ({empNumbersIn}) AND HName IN ({empNamesIn})  and HUSEORGID ={organ}";
                DataSet EmpData = oCN.RunProcReturn(EmployeeQuery, "Gy_Employee");
                Dictionary<string, int> EmpDict = new Dictionary<string, int>();
                foreach (DataRow row in EmpData.Tables[0].Rows)
                {
                    string key = $"{row["HName"].ToString()}";
                    EmpDict[key] = (int)row["HItemID"];
                }
                // 3. æ‰¹é‡æŸ¥è¯¢chengbenxiangmu信息
                string CostQuery = $"SELECT HItemID, HNumber, HName FROM Gy_CostItem WHERE HNumber IN ({string.Join(",", CostNumbers.Select(m => $"'{m.Replace("'", "''")}'"))}) AND HName IN ({string.Join(",", CostNames.Select(m => $"'{m.Replace("'", "''")}'"))}) and HUSEORGID ={organ}";
                DataSet CostData = oCN.RunProcReturn(CostQuery, "Gy_CostItem");
                Dictionary<string, int> CostDict = new Dictionary<string, int>();
                foreach (DataRow row in CostData.Tables[0].Rows)
                {
                    string key = $"{row["HName"].ToString()}";
                    CostDict[key] = (int)row["HItemID"];
                }
                // 3.1 æ‰¹é‡æŸ¥è¯¢å·¥åºä¿¡æ¯
                string ProcessQuery = $"SELECT HItemID, HNumber, HName FROM Gy_Process WHERE  HName IN ({string.Join(",", HProc.Select(m => $"'{m.Replace("'", "''")}'"))}) and HUSEORGID ={organ}";
                DataSet ProcData = oCN.RunProcReturn(ProcessQuery, "Gy_Process");
                Dictionary<string, int> ProcDict = new Dictionary<string, int>();
                foreach (DataRow row in ProcData.Tables[0].Rows)
                {
                    string key = $"{row["HName"].ToString()}";
                    ProcDict[key] = (int)row["HItemID"];
                }
                // 4. æŸ¥è¯¢ç”¨æˆ·ä¿¡æ¯
                DataSet emp = oCN.RunProcReturn($"SELECT Czybm FROM Gy_Czygl WHERE Czymc = '{user.Replace("'", "''")}'", "Gy_Czygl");
                if (emp.Tables[0].Rows.Count == 0)
                {
                    res.code = "0";
                    res.count = 0;
                    res.Message = "用户不存在!";
                    res.data = null;
                    return res;
                }
                string HUserID = emp.Tables[0].Rows[0]["Czybm"].ToString();
                // 5. æ£€æŸ¥ç¼ºå¤±çš„部门和物料,并记录行号
                List<string> missingSupplierMessages = new List<string>();
                List<string> missingMaterialMessages = new List<string>();
                List<string> missingCostMessages = new List<string>();
                List<string> missingmoneyMessages = new List<string>();
                List<string> missingEmployeeMessages = new List<string>();
                // éåŽ†æ¯ä¸€è¡Œæ•°æ®ï¼Œè®°å½•è¡Œå·ï¼ˆä»Ž1开始)
                for (int i = 0; i < list.Count; i++)
                {
                    var item = list[i];
                    int lineNumber = i + 1; // è¡Œå·ä»Ž1开始
                    string ICMOcheck = item["生产订单号"];
                    string Costcheck = item["成本项目"];
                    string Procheck = item["工序"];
                    string supplier = item["部门"];
                    string materialNumber = item["物料编码"];
                    string materialName = item["物料名称"];
                    string monetcheck = item["金额"];
                    string materialKey = $"{materialNumber}_{materialName}";
                    string empName = item["职员"];
                    if (!string.IsNullOrEmpty(empName) && !EmpDict.ContainsKey(empName))
                    {
                        missingEmployeeMessages.Add($"第{lineNumber}行的职员【{empName}】");
                    }
                    // æ£€æŸ¥ä¾›åº”商
                    if (!supplierDict_sub.ContainsKey(supplier))
                    {
                        missingSupplierMessages.Add($"第{lineNumber}行的部门【{supplier}】");
                    }
                    // æ£€æŸ¥ç‰©æ–™
                    if (!materialDict.ContainsKey(materialKey))
                    {
                        missingMaterialMessages.Add($"第{lineNumber}行的物料【{materialName}(编码:{materialNumber})】");
                    }
                    // æ£€æŸ¥ç”Ÿäº§è®¢å•
                    if (!string.IsNullOrEmpty(ICMOcheck) && !ICMODict.ContainsKey(ICMOcheck))
                    {
                        missingMaterialMessages.Add($"第{lineNumber}行的生产订单【{ICMOcheck}】");
                    }
                    // æ£€æŸ¥é¡¹ç›®æˆæœ¬
                    if (CostDict.Count == 0|| !CostDict.ContainsKey(Costcheck))
                    {
                        missingCostMessages.Add($"第{lineNumber}行的项目成本【{Costcheck}】");
                    }
                    // æ£€æŸ¥å·¥åº
                    if (ProcDict.Count == 0 && Procheck != "")
                    {
                        missingCostMessages.Add($"第{lineNumber}行的工序【{Procheck}】");
                    }
                    if (monetcheck == "" || monetcheck == null)
                    {
                        missingmoneyMessages.Add($"第{lineNumber}行金额【{monetcheck}】");
                    }
                }
                StringBuilder errorMessage = new StringBuilder();
                if (missingSupplierMessages.Any())
                {
                    errorMessage.Append("以下部门未维护:");
                    errorMessage.Append(string.Join("、", missingSupplierMessages));
                    errorMessage.Append(";");
                }
                if (missingMaterialMessages.Any())
                {
                    errorMessage.Append("以下物料未维护:");
                    errorMessage.Append(string.Join("、", missingMaterialMessages));
                    errorMessage.Append(";");
                }
                if (missingCostMessages.Any())
                {
                    errorMessage.Append("成本项目未维护或有误:");
                    errorMessage.Append(string.Join("、", missingCostMessages));
                    errorMessage.Append(";");
                }
                if (missingmoneyMessages.Any())
                {
                    errorMessage.Append("金额未维护或有误:");
                    errorMessage.Append(string.Join("、", missingmoneyMessages));
                    errorMessage.Append(";");
                }
                if (missingEmployeeMessages.Any())
                {
                    errorMessage.Append("以下职员未维护:");
                    errorMessage.Append(string.Join("、", missingEmployeeMessages));
                    errorMessage.Append(";");
                }
                if (errorMessage.Length > 0)
                {
                    res.code = "0";
                    res.count = 0;
                    res.Message = errorMessage.ToString();
                    res.data = null;
                    return res;
                }
                // 7. æŒ‰ç…§éƒ¨é—¨ä»£ç ã€éƒ¨é—¨ã€èŒå‘˜ä»£ç ã€èŒå‘˜ã€ç”Ÿäº§è®¢å•号进行分组
                var groupedData = list.GroupBy(item => new
                {
                    éƒ¨é—¨ä»£ç  = item["部门代码"],
                    éƒ¨é—¨ = item["部门"],
                    èŒå‘˜ä»£ç  = item["职员代码"],
                    èŒå‘˜ = item["职员"],
                    ç”Ÿäº§è®¢å•号 = item["生产订单号"]
                }).ToList();
                StringBuilder insertSql = new StringBuilder();
                StringBuilder insertSql_sub = new StringBuilder();
                string currentDate = DateTime.Today.ToString("yyyy-MM-dd");
                foreach (var group in groupedData)
                {
                    var firstItem = group.First();
                    // èŽ·å–ç»„ä¿¡æ¯
                    int HSupplierID = supplierDict_sub[firstItem["部门"]];
                    //int EmpID = EmpDict[firstItem["职员"]];
                    int EmpID;
                    string empName = firstItem["职员"];
                    if (string.IsNullOrEmpty(empName))
                        EmpID = 0;   // æˆ–其他默认值
                    else
                        EmpID = EmpDict[empName];
                    string ICMO = firstItem["生产订单号"];
                    int ICMOInterID = !string.IsNullOrEmpty(ICMO) && ICMODict.ContainsKey(ICMO) ? ICMODict[ICMO] : 0;
                    // ç”Ÿæˆä¸»è¡¨ID和单据号(每组生成一个)
                    string HBillNo = DBUtility.ClsPub.CreateBillCode("1802", ref DBUtility.ClsPub.sExeReturnInfo, true);
                    long HInterID = DBUtility.ClsPub.CreateBillID("1802", ref DBUtility.ClsPub.sExeReturnInfo);
                    DateTime firstDayWithTime = new DateTime(Convert.ToInt32(list[0]["年份"]), Convert.ToInt32(list[0]["月份"]), 1);
                    // æ’入主表(每组插入一次)
                    insertSql.AppendLine($"INSERT INTO CB_ItemMoneyBillMain  ([HInterID], [HBillNo], [HDate], [HYear], [HPeriod], [HBillType], [HBillSubType], [HBillStatus], [HCheckItemNowID], [HCheckItemNextID], [HCheckFlowID], [HRemark], [HBacker], [HBackDate], [HBackRemark], [HChecker], [HCheckDate], [HMaker], [HMakeDate], [HUpDater], [HUpDateDate], [HCloseMan], [HCloseDate], [HCloseType], [HDeleteMan], [HDeleteDate], [HMainSourceBillType], [HMainSourceInterID], [HMainSourceEntryID], [HMainSourceBillNo], [HPrintQty],  [HEmpID], [HDeptID], [HICMOInterID], [HMaterID], [HICMOBillNo], [HExplanation], [HInnerBillNo], [HBeginDate], [HEndDate], [HOrgID]) VALUES (");
                        insertSql.AppendLine($"'{HInterID}', '{HBillNo}', '{firstDayWithTime}', {list[0]["年份"]}, {list[0]["月份"]}, {"1802"}, '{"1802"}', '{"1"}',  '{"0"}', '{"0"}', '{"0"}', '{"excel导入"}', '{""}', '{DateTime.Now}', '{""}', '{""}', '{DateTime.Now}', '{user}', '{DateTime.Now}', '{""}', '{DateTime.Now}', '{""}', '{DateTime.Now}', '{"0"}', '{""}', '{DateTime.Now}', '{""}', '{"0"}', '{"0"}', '{""}', '{"0"}', '{EmpID}', '{HSupplierID}', '{ICMOInterID}','{0}','{ICMO}','{""}','{"0"}','{DateTime.Now}','{DateTime.Now}','{"100038"}');");
                        // æ’入子表(组内每个物料插入一次)
                        int HEntryID = 1;
                        foreach (var item in group)
                        {
                            int HMaterID = materialDict[$"{item["物料编码"]}_{item["物料名称"]}"];
                            int HCostID = CostDict[item["成本项目"]];
                            int HProcID = ProcDict[item["工序"]];
                            insertSql_sub.AppendLine($"INSERT INTO [CB_ItemMoneyBillSub] ([HInterID], [HEntryID], [HCloseMan], [HEntryCloseDate], [HCloseType], [HRemark],[HSourceInterID], [HSourceEntryID], [HSourceBillNo], [HSourceBillType],[HRelationQty], [HRelationMoney], [HBillNo_bak], [HCostItemID],[HDeptID], [HQty], [HPrice], [HMoney],[HMaterID], [HWaster], [HDate], [HBeginBalance], [HEndBalance], [HTimes],[HProcID]) VALUES (");
                            insertSql_sub.AppendLine($"'{HInterID}', '{HEntryID}', '{""}', '{DateTime.Now}', '{"0"}', '{"excel导入"}','{"0"}', '{"0"}',  '{"0"}', '{"0"}','{"0"}', '{"0"}', '{""}', '{HCostID}', '{HSupplierID}', '{item["数量"]}', '{item["单价"]}', '{item["金额"]}','{HMaterID}', '{item["损耗量"] ?? "0"}', '{DateTime.Now}', '{"0"}', '{"0"}', '{"0"}', '{HProcID}');");
                            HEntryID++;
                        }
                }
                // æ‰§è¡Œæ‰¹é‡æ“ä½œ
                if (insertSql.Length > 0)
                {
                    oCN.RunProc(insertSql.ToString());
                }
                if (insertSql_sub.Length > 0)
                {
                    oCN.RunProc(insertSql_sub.ToString());
                }
                oCN.Commit();
                res.code = "1";
                res.count = groupedData.Count;
                res.Message = $"导入成功! å…±å¤„理{groupedData.Count}组数据";
                res.data = null;
                return res;
            }
            catch (Exception e)
            {
                //oCN.Rollback();
                LogService.Write(e);
                res.code = "0";
                res.count = 0;
                res.Message = "Exception!" + e.ToString();
                res.data = null;
                return res;
            }
        }
        #endregion
    }
}