华恒Mes鼎捷代码
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

654 lines
26 KiB

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using ICSSoft.Frame.User.BLL;
using ICSSoft.Base.Language.Tool;
using ICSSoft.Base.UserControl.MessageControl;
using System.Data.SqlClient;
using ICSSoft.Base.Config.AppConfig;
using ICSSoft.Base.Report.Filter;
using ICSSoft.Base.Config.DBHelper;
using ICSSoft.Base.UserControl.FormControl;
using ICSSoft.Base.ReferForm.AppReferForm;
using ICSSoft.Base.Lable.PrintTool;
using ICSSoft.Frame.Data.DAL;
using ICSSoft.Frame.Data.BLL;
using ICSSoft.Frame.Data.Entity;
using System.Collections;
using System.Net;
using System.IO;
using Newtonsoft.Json;
using System.Configuration;
using DevExpress.XtraGrid.Columns;
using System.Linq;
using ICSSoft.Frame.Common;
namespace ICSSoft.Frame.APP
{
public partial class FormICSAgvSlOrBack : DevExpress.XtraEditors.XtraForm
{
string Lotno;
string Opcode;
string Eqpcode;
Timer T = new Timer();
DataTable TableMain = new DataTable();
DataTable TableSon = new DataTable();
#region 构造函数
public FormICSAgvSlOrBack()
{
InitializeComponent();
}
public FormICSAgvSlOrBack(String Lotno,string Opcode,string Eqpcode)
{
InitializeComponent();
this.Lotno = Lotno;
this.Opcode = Opcode;
this.Eqpcode = Eqpcode;
}
#endregion
public void LoadUIMes(string Lotno,string Opcode ) {
string sql = @"Select LOTNO,MCODE,A.TRANSNO,B.INVNAME,C.OPCODE,C.OPNAME FROM ICSITEMLot a
Left join ICSINVENTORY b on a.MCODE=b.INVCODE
Left join ICSOP C ON C.OPCODE='{0}'
WHERE A.LotNO='{1}'
";
sql = string.Format(sql,Opcode,Lotno);
DataSet Set = DBHelper.ExecuteDataset(AppConfig.AppConnectString, CommandType.Text, sql);
DataTable datasource = Set.Tables[0];
TxtLotno.Text = Lotno;
TxtOpcode.Text = Opcode;
TxtOpName.Text = datasource.Rows[0]["OPNAME"].ToString();
TxtMocode.Text = datasource.Rows[0]["TRANSNO"].ToString();
TxtItemcode.Text= datasource.Rows[0]["MCODE"].ToString();
TxtItemName.Text = datasource.Rows[0]["INVNAME"].ToString();
}
public void LoadGridMes() {
StringBuilder logmes = new StringBuilder("");
try
{
TableSon = InitAgvLog().Copy();
var AreaMes = ICSAGVBLL.GetAreaCode("00088", "5", AppConfig.AppConnectString, AppConfig.WorkPointCode);
string sql = @" select vv.define1 from Sys_EnumValues vv
inner join Sys_Enumkey kk on kk.WorkPointCode=vv.WorkPointCode and kk.EnumKey=vv.EnumKey
where kk.enumname='AGV管控'
and vv.EnumText='AGVInventory'
and kk.WorkPointCode ='" + AppConfig.WorkPointCode + "'";
DataTable dt = DBHelper.ExecuteDataset(AppConfig.AppConnectString, CommandType.Text, sql).Tables[0];
if (dt == null || dt.Rows.Count == 0)
{
throw new Exception("请联系管理员,在自定义档案中维护信息:AGV管控-AGVInventory");
}
logmes.AppendLine("调用接口:AGVInventory");
string GetInventoryListUrl = dt.Rows[0]["define1"].ToString();
var Detail = new { referCode = Lotno/*, zoneCode = AreaMes.Split('@')[0].Split(':')[0]*/};
var GetInventoryListModel = new { inventoryDetail = Detail, pageSize = "100", pageNum = "1", area = AppConfig.GetDataBaseNameByConnectString(AppConfig.AppConnectString) == "ICSMES_GTSys" ? "GT" : "JJ" };
var StringContent = JsonConvert.SerializeObject(GetInventoryListModel);
logmes.AppendLine("params:" + StringContent + "");
var Rtnstr = WebInvokePost(GetInventoryListUrl, StringContent);
logmes.AppendLine("ReturnMes:" + Rtnstr + "");
ReturnMesInv ReturnMes = JsonConvert.DeserializeObject<ReturnMesInv>(Rtnstr);
if (ReturnMes.code != 200)
throw new Exception(ReturnMes.msg);
else
{
foreach (InventoryDetail inv in ReturnMes.data)
{
DataRow row = TableMain.NewRow();
row["选择"] = "";
row["子件编码"] = inv.materialCode;
row["子件名称"] = inv.materialName;
row["计划数量"] = /*inv.taskQty*/inv.qty;
row["起始区域"] = AreaMes.Split('@')[0];
row["ID"] = inv.id;
row["已领数量"] = TableSon.AsEnumerable().Where(a => a["子件编码"].ToString() == inv.materialCode && a["DetailId"].ToString() == inv.id).Sum(a => Convert.ToDecimal(a["本次数量"]));
TableMain.Rows.Add(row);
}
}
gridControl1.DataSource = TableMain;
gridControl2.DataSource = TableSon;
}
catch (Exception ex)
{
ICSBaseSimpleCode.AppshowMessageBox(ex.Message);
}
finally {
WriteLogFile(logmes.ToString(), "AGV接口");
}
}
#region 关闭 退出
private void btnClose_Click(object sender, EventArgs e)
{
this.Close();
}
#endregion
#region 移动窗体
private const int WM_NCHITTEST = 0x84;
private const int HTCLIENT = 0x1;
private const int HTCAPTION = 0x2;
//首先必须了解Windows的消息传递机制,当有鼠标活动消息时,
//系统发送WM_NCHITTEST 消息给窗体作为判断消息发生地的根据。 nchittest
//假如你点击的是标题栏,窗体收到的消息值就是 HTCAPTION ,
//同样地,若接受到的消息是 HTCLIENT,说明用户点击的是客户区,也就是鼠标消息发生在客户区。
//重写窗体,使窗体可以不通过自带标题栏实现移动
protected override void WndProc(ref Message m)
{
//当重载窗体的 WndProc 方法时,可以截获 WM_NCHITTEST 消息并改些该消息,
//当判断鼠标事件发生在客户区时,改写改消息,发送 HTCAPTION 给窗体,
//这样,窗体收到的消息就时 HTCAPTION ,在客户区通过鼠标来拖动窗体就如同通过标题栏来拖动一样。
//注意:当你重载 WndProc 并改写鼠标事件后,整个窗体的鼠标事件也就随之改变了。
switch (m.Msg)
{
case WM_NCHITTEST:
base.WndProc(ref m);
if ((int)m.Result == HTCLIENT)
m.Result = (IntPtr)HTCAPTION;
return;
}
//拦截双击标题栏、移动窗体的系统消息
if (m.Msg != 0xA3)
{
base.WndProc(ref m);
}
}
#endregion
#region 取消
private void can_Click(object sender, EventArgs e)
{
this.Close();
}
#endregion
#region 页面加载
private void FormICSItenLotAdd_Load(object sender, EventArgs e)
{
foreach (Control contorl in panel1.Controls)
{
if (contorl is TextEdit)
{
(contorl as TextEdit).Properties.ReadOnly = true;
}
}
foreach (GridColumn column in gridViewMain.Columns)
{
TableMain.Columns.Add(new DataColumn(column.FieldName));
}
LoadUIMes(Lotno,Opcode);
InitLocation();
LoadGridMes();
T.Interval = 10000;
T.Tick += delegate(object sender1, EventArgs e1) {
try
{
DataTable LogTable = InitAgvLog();
foreach (DataRow Row in LogTable.Rows) {
var SonRows = TableSon.AsEnumerable().Where(a => a["ID"].ToString()== Row["ID"].ToString()).FirstOrDefault();
if (SonRows==null)
{
DataRow NewRow = TableSon.NewRow();
NewRow.ItemArray = Row.ItemArray;
TableSon.Rows.Add(NewRow);
continue;
}
else {
SonRows["是否到料"] = Row["是否到料"];
SonRows["是否返回"] = Row["是否返回"];
}
}
//foreach (DataRow row in TableMain.Rows)
//{
// row["已领数量"] = TableSon.AsEnumerable().Where(a => a["子件编码"].ToString() == row["子件编码"].ToString() && a["DetailId"].ToString() == row["ID"].ToString()).Sum(a => Convert.ToDecimal(a["本次数量"]));
//}
}
catch (Exception ex)
{
throw ex;
}
};
T.Start();
}
#endregion
private DataTable InitAgvLog()
{
try
{
string sql = @"select A.ID,A.MaterialCode as 子件编码,'' AS 选择,A.IsArrive as 到料状态,A.Mtime as 叫料时间,B.MTIME AS 返回时间,B.ISBACK AS 返回状态,ISNULL(B.QTY,0) AS 本次数量,A.EATTRIBUTE1 AS DetailId,A.LOCATIONCODE,a.QTY,A.Groupid,a.AREA as 区域,a.locationcode as 点位,a.groupid,a.isarrive as 是否到料,a.isback as 是否返回 from ICSAGVTASKLOG a
Left Join ICSAGVTASKLOG b on a.id<>b.id AND B.TaskType='料框返回' and a.groupid=b.groupid
where A.Lotno='{0}' and A.opcode='{1}' and A.TaskType='叫料'";
sql = string.Format(sql, Lotno, Opcode);
DataTable Table = DBHelper.ExecuteDataset(AppConfig.AppConnectString, CommandType.Text, sql).Tables[0];
return Table;
}
catch (Exception ex)
{
throw ex;
}
}
public void InitLocation() {
try
{
string sql = @"select a.locationcode as 点位编码,b.LocationName as 点位名称 from IcsEqpWithLocation a left join IcsAGVLocation b on a.locationcode=b.locationcode where eqpcode='{0}'";
sql = string.Format(sql,Eqpcode);
DataTable Table = DBHelper.ExecuteDataset(AppConfig.AppConnectString, CommandType.Text, sql).Tables[0];
LookUpEditLocation.DataSource = Table;
LookUpEditLocation.DisplayMember = "点位编码";
LookUpEditLocation.ValueMember = "点位编码";
LookUpEditLocation.NullText = "";//空时的值
LookUpEditLocation.ImmediatePopup = true;//输入值是否马上弹出窗体
LookUpEditLocation.ValidateOnEnterKey = true;//回车确认
LookUpEditLocation.TextEditStyle = DevExpress.XtraEditors.Controls.TextEditStyles.Standard;//要使用户可以输入,这里须设为Standard
LookUpEditLocation.AllowNullInput = DevExpress.Utils.DefaultBoolean.True; //可用Ctrl + Delete清空选择內容 //自适应宽度
LookUpEditLocation.BestFitMode = DevExpress.XtraEditors.Controls.BestFitMode.BestFitResizePopup;
}
catch (Exception ex)
{
throw ex;
}
}
private void gridView1_CustomDrawRowIndicator(object sender, DevExpress.XtraGrid.Views.Grid.RowIndicatorCustomDrawEventArgs e)
{
if (e.Info.IsRowIndicator && e.RowHandle >= 0)
e.Info.DisplayText = (e.RowHandle + 1).ToString();
}
private void BtnBack_Click(object sender, EventArgs e)
{
try
{
List<ICSAGVTASKLOG> Log_List = new List<ICSAGVTASKLOG>();
List<AGVCreateTaskModel> Task_List = new List<AGVCreateTaskModel>();
for (int i = 0; i < TableSon.Rows.Count; i++)
{
if (TableSon.Rows[i]["选择"].ToString() == "Y")
{
Check("", "料框返回", TableSon.Rows[i]["ID"].ToString());
ICSAGVTASKLOG log = new ICSAGVTASKLOG();
log.ID = AppConfig.GetGuid();
log.Lotno = Lotno;
log.Opcode = Opcode;
log.Itemcode = TxtItemcode.Text;
log.MaterialCode = TableSon.Rows[i]["子件编码"].ToString();
log.LocationCode = TableSon.Rows[i]["点位"].ToString();
log.Area = TableSon.Rows[i]["区域"].ToString();
log.Qty =(Decimal?)(TableSon.Rows[i]["本次数量"]);
log.TaskType = "料框返回";
log.Mtime = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
log.MuserName = AppConfig.UserName;
log.IsArrive = false;
log.IsBack = false;
log.GroupID = TableSon.Rows[i]["groupid"].ToString();
Log_List.Add(log);
AGVCreateTaskModel model = new AGVCreateTaskModel();
model.area = log.Area.Split(':')[0];
model.qty =Convert.ToInt32(TableSon.Rows[i]["QTY"].ToString()) -(int)log.Qty;
model.station = log.LocationCode;
model.type = "false";
model.materialCode = log.MaterialCode;
//model.materialName = MainRow["子件名称"].ToString();
model.trackingNumber = Lotno;
Task_List.Add(model);
}
}
if (Log_List.Count <= 0)
throw new Exception("请选择要料框返回的料框!");
string mes = ICSAGVBLL.CreateAGVTaskJJorBack(Task_List, Log_List, AppConfig.AppConnectString, AppConfig.WorkPointCode);
if (string.IsNullOrEmpty(mes))
{
ICSBaseSimpleCode.AppshowMessageBox("料框返回成功!");
LoadGridMes();
}
else
ICSBaseSimpleCode.AppshowMessageBox(mes);
}
catch (Exception ex)
{
ICSBaseSimpleCode.AppshowMessageBox(ex.Message);
}
}
private void BtnCall_Click(object sender, EventArgs e)
{
try
{
List<ICSAGVTASKLOG> Log_List = new List<ICSAGVTASKLOG>();
List<AGVCreateTaskModel> Task_List = new List<AGVCreateTaskModel>();
for (int i = 0; i <gridViewMain.RowCount; i++) {
if (gridViewMain.GetRowCellValue(i, ).ToString()== "Y") {
string AgvId = gridViewMain.GetRowCellValue(i,AGVID).ToString();//子件库存查询的接口ID 可能存在多笔相同子件不同料框的情况,需要记录id区分是哪个料框叫的料
Check(AgvId,"叫料");
ICSAGVTASKLOG log = new ICSAGVTASKLOG();
log.ID = AppConfig.GetGuid();
log.Lotno = Lotno;
log.Opcode = Opcode;
log.Itemcode = TxtItemcode.Text;
log.MaterialCode = gridViewMain.GetRowCellValue(i, ).ToString();
log.LocationCode = gridViewMain.GetRowCellValue(i, ).ToString();
log.Area= gridViewMain.GetRowCellValue(i, ).ToString();
log.Qty = Convert.ToDecimal(gridViewMain.GetRowCellValue(i, ).ToString());
log.TaskType = "叫料";
log.Mtime =Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
log.MuserName = AppConfig.UserName;
log.IsArrive = false;
log.IsBack = false;
log.GroupID= AppConfig.GetGuid(); //叫料,料框返回Goupid是相同的
log.Eattribute1= AgvId;
Log_List.Add(log);
AGVCreateTaskModel model = new AGVCreateTaskModel();
model.area = log.Area.Split(':')[0];
model.qty =(int)Convert.ToDecimal(gridViewMain.GetRowCellValue(i, ));
model.station = log.LocationCode;
model.type = "true";
model.materialCode = log.MaterialCode;
model.materialName= gridViewMain.GetRowCellValue(i, ).ToString();
model.trackingNumber = Lotno;
model.warehouseCode = "KS0001";
Task_List.Add(model);
}
}
if (Log_List.Count <= 0)
throw new Exception("请选择要叫料的物料!");
string mes=ICSAGVBLL.CreateAGVTaskJJorBack(Task_List, Log_List,AppConfig.AppConnectString,AppConfig.WorkPointCode);
if (string.IsNullOrEmpty(mes))
{
ICSBaseSimpleCode.AppshowMessageBox("叫料成功!");
TableMain.Clear();
TableSon.Clear();
LoadGridMes();
}
else
ICSBaseSimpleCode.AppshowMessageBox(mes);
}
catch (Exception ex)
{
ICSBaseSimpleCode.AppshowMessageBox(ex.Message);
}
}
/// <summary>
///
/// </summary>
/// <param name="AgvID">主表信息标识</param>
/// <param name="Type">叫料or料框返回</param>
/// <param name="LogID">叫料日志id</param>
private void Check(String AgvID,string Type,params string[] LogID) {
try
{
DataTable LogTable = InitAgvLog();
if (Type == "叫料")
{
DataRow MainRow = TableMain.AsEnumerable().Where(A => A["ID"].ToString() == AgvID).FirstOrDefault();
List<DataRow> CheckRow_List = LogTable.AsEnumerable().Where(a => a["DetailId"].ToString() == AgvID).ToList();
//decimal HasLLQty = CheckRow_List.Sum(a => Convert.ToDecimal(a["本次数量"]));
string LocationCode = MainRow["到料点位"].ToString();
if (CheckRow_List.Where(a => string.IsNullOrEmpty(a["返回时间"].ToString()) == true).Count() > 0)
throw new Exception("ID:" + AgvID + ",已叫料且未料框返回,无法再次叫料!");
if (Convert.ToDecimal(MainRow["计划数量"])<=0)
throw new Exception("ID:" + AgvID + ",库存数量为0,无法再次叫料!");
if(string.IsNullOrEmpty(LocationCode))
throw new Exception("ID:" + AgvID + ",需输入到料点位!");
}
else if (Type == "料框返回") {
var BackRow=LogTable.AsEnumerable().Where(a => a["ID"].ToString() == LogID[0]).FirstOrDefault();
if (!String.IsNullOrEmpty(BackRow["返回时间"].ToString()))
throw new Exception("行标识:" + LogID[0] + ",已执行料框返回完毕,请勿重复操作!");
if(string.IsNullOrEmpty(TableSon.AsEnumerable().Where(A => A["ID"].ToString() == LogID[0]).Select(A => A["OnQty"]).ToString()))
throw new Exception("行标识:" + LogID[0] + ",需要输入本次数量!");
}
}
catch (Exception ex)
{
throw ex;
}
}
public static string WebInvokePost(string url, string JsonData)
{
//构造一个Web请求的对象
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
request.Accept = "text/html, application/xhtml+xml, */*";
request.ContentType = "application/json;charset=utf-8";
var stream=request.GetRequestStream();
byte[] Data = System.Text.Encoding.UTF8.GetBytes(JsonData);
stream.Write(Data, 0, Data.Length);
//获取web请求的响应的内容
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
{
return reader.ReadToEnd();
}
}
private void gridViewMain_DoubleClick(object sender, EventArgs e)
{
if (gridViewMain.FocusedRowHandle < 0)
{
return;
}
if (gridViewMain.FocusedColumn ==)
{
if (gridViewMain.GetRowCellValue(gridViewMain.FocusedRowHandle, ).ToString() == "")
{
gridViewMain.SetRowCellValue(gridViewMain.FocusedRowHandle, , "Y");
}
else
{
gridViewMain.SetRowCellValue(gridViewMain.FocusedRowHandle, , "");
}
}
}
private void gridViewSon_DoubleClick(object sender, EventArgs e)
{
if (gridViewSon.FocusedRowHandle < 0)
{
return;
}
if (gridViewSon.FocusedColumn == ColSelect)
{
if (gridViewSon.GetRowCellValue(gridViewSon.FocusedRowHandle, ColSelect).ToString() == "")
{
gridViewSon.SetRowCellValue(gridViewSon.FocusedRowHandle, ColSelect, "Y");
}
else
{
gridViewSon.SetRowCellValue(gridViewSon.FocusedRowHandle, ColSelect, "");
}
}
}
private void TxtOnQty_Click(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(gridViewSon.GetFocusedRowCellValue().ToString()) && gridViewSon.FocusedColumn == OnQty)
{
TxtOnQty.ReadOnly = true;
OnQty.OptionsColumn.ReadOnly = true;
}
else
{
TxtOnQty.ReadOnly = false;
OnQty.OptionsColumn.ReadOnly = false;
}
}
#region 写入日志
public static void WriteLogFile(string input, string txtName)
{
try
{
string logAdress = ConfigurationManager.AppSettings["logAdress"].ToString() + "\\Log\\";
if (!System.IO.Directory.Exists(logAdress))
{
System.IO.Directory.CreateDirectory(logAdress);//不存在就创建目录
}
string adress = logAdress + txtName;
if (!System.IO.Directory.Exists(adress))
{
System.IO.Directory.CreateDirectory(adress);//不存在就创建目录
}
// string logAdress = ConfigurationManager.AppSettings["logAdress"].ToString();
/**/
///指定日志文件的目录
string fname = adress + "\\" + "log" + DateTime.Now.ToString("yy-MM-dd") + ".txt";
/**/
///定义文件信息对象
FileInfo finfo = new FileInfo(fname);
if (!finfo.Exists)
{
FileStream fs;
fs = File.Create(fname);
fs.Close();
finfo = new FileInfo(fname);
}
/**/
///判断文件是否存在以及是否大于2K
if (finfo.Length > 1024 * 1024 * 10)
{
/**/
///文件超过10MB则重命名
File.Move(logAdress + "\\Log\\" + txtName + ".txt", Directory.GetCurrentDirectory() + DateTime.Now.TimeOfDay + "\\Log\\" + txtName + ".txt");
/**/
///删除该文件
//finfo.Delete();
}
//finfo.AppendText();
/**/
///创建只写文件流
using (FileStream fs = finfo.OpenWrite())
{
/**/
///根据上面创建的文件流创建写数据流
StreamWriter w = new StreamWriter(fs);
/**/
///设置写数据流的起始位置为文件流的末尾
w.BaseStream.Seek(0, SeekOrigin.End);
w.WriteLine("*****************Start*****************");
w.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
/**/
///写入当前系统时间并换行
/**/
///写入日志内容并换行
w.WriteLine(input);
/**/
///写入------------------------------------“并换行
w.WriteLine("------------------END------------------------");
/**/
///清空缓冲区内容,并把缓冲区内容写入基础流
w.Flush();
/**/
///关闭写数据流
w.Close();
}
}
catch (Exception ex)
{ throw ex; }
}
#endregion
private void tableLayoutPanel1_Paint(object sender, PaintEventArgs e)
{
}
}
}