You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
DS7/GetPortInfo/FMain.cs

681 lines
30 KiB
C#

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

using DSWeb.Areas.MvcShipping.Comm;
using DSWeb.SoftMng.DAL;
using DSWeb.SoftMng.Model;
using ICSharpCode.SharpZipLib.Zip;
using iText.IO.Image;
using iText.Kernel.Pdf;
using iText.Layout;
using log4net;
using MailKit.Net.Smtp;
using MimeKit;
using MimeKit.Utils;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace GetPortInfo
{
public partial class FMain : Form
{
private const string CfgFileName = "app.cfg";
private static string CfgFilePath = Path.Combine(Application.StartupPath, CfgFileName);
private static string SpiderUrl = ConfigurationManager.AppSettings["SpiderUrl"];
private static string Djy_CustAuth_Userid = ConfigurationManager.AppSettings["Djy_CustAuth_Userid"];
private ILog log = LogManager.GetLogger("FMain");
private string mid;
public class pdfFileDownload
{
public string path { get; set; }
public string filename { get; set; }
public string fileno { get; set; }
}
public class JsonXFSend
{
public string userId { get; set; }
public string module { get; set; }
public string data { get; set; }
}
public FMain()
{
InitializeComponent();
}
private void FMain_Load(object sender, EventArgs e)
{
if (SpiderUrl.EndsWith("/"))
{
SpiderUrl = SpiderUrl.Substring(0, SpiderUrl.Length - 1);
}
if (File.Exists(CfgFilePath))
{
JObject jobj = JObject.Parse(File.ReadAllText(CfgFilePath));
var reqDateStart = Convert.ToDateTime(jobj.GetValue("reqStart"));
var reqDateEnd = Convert.ToDateTime(jobj.GetValue("reqEnd"));
var cardNO = jobj.GetValue("cardNO").ToString();
var pwd = jobj.GetValue("pwd").ToString();
var receiver = jobj.GetValue("receiver").ToString();
var subject = jobj.GetValue("subject").ToString();
var stmpServer = jobj.GetValue("stmpServer").ToString();
var mailAcc = jobj.GetValue("mailAcc").ToString();
var mailPwd = jobj.GetValue("mailPwd").ToString();
var port = Convert.ToInt32(jobj.GetValue("port"));
var ssl = Convert.ToBoolean(jobj.GetValue("ssl"));
var isnotgz = Convert.ToBoolean(jobj.GetValue("isnotgz"));
var updateUser = jobj.GetValue("updateUser").ToString();
var ies = jobj.GetValue("ies").ToString();
var clearance = Convert.ToBoolean(jobj.GetValue("clearance").ToString());
dtpReqStart.Value = reqDateStart;
dtpReqEnd.Value = reqDateEnd;
txtCardNO.Text = cardNO;
txtPwd.Text = pwd;
txtReceiver.Text = receiver;
txtSubject.Text = subject;
txtSmtpServer.Text = stmpServer;
txtMailAcc.Text = mailAcc;
txtMailPwd.Text = mailPwd;
numStmpPort.Value = port;
chkSSL.Checked = ssl;
chkNotGZ.Checked = isnotgz;
txtupdateUser.Text = updateUser;
if (ies == "I") rdImport.Checked=true; else rdExport.Checked = true;
checkBoxIsCl.Checked = clearance;
}
}
private void btnStart_Click(object sender, EventArgs e)
{
if (txtCardNO.Text.Trim().Length == 0)
{
MessageBox.Show("卡号不能为空");
return;
}
if (txtPwd.Text.Trim().Length == 0)
{
MessageBox.Show("密码不能为空");
return;
}
if (txtReceiver.Text.Trim().Length == 0)
{
MessageBox.Show("收件人不能为空");
return;
}
if (txtSubject.Text.Trim().Length == 0)
{
MessageBox.Show("主题不能为空");
return;
}
if (txtSmtpServer.Text.Trim().Length == 0)
{
MessageBox.Show("SMTP服务器不能为空");
return;
}
if (txtMailAcc.Text.Trim().Length == 0)
{
MessageBox.Show("邮箱账号不能为空");
return;
}
if (txtMailPwd.Text.Trim().Length == 0)
{
MessageBox.Show("邮箱密码不能为空");
return;
}
if (dtpGetTime.Value < DateTime.Now)
{
MessageBox.Show("提取时间必须晚于当前时间");
return;
}
//记录配置文件
JObject jobj = new JObject();
jobj.Add("reqStart", new JValue(dtpReqStart.Value));
jobj.Add("reqEnd", new JValue(dtpReqEnd.Value));
jobj.Add("cardNO", new JValue(txtCardNO.Text));
jobj.Add("pwd", new JValue(txtPwd.Text));
jobj.Add("receiver", new JValue(txtReceiver.Text));
jobj.Add("subject", new JValue(txtSubject.Text));
jobj.Add("stmpServer", new JValue(txtSmtpServer.Text));
jobj.Add("port", new JValue(numStmpPort.Value));
jobj.Add("ssl", new JValue(chkSSL.Checked));
jobj.Add("isnotgz", new JValue(chkNotGZ.Checked));
jobj.Add("mailAcc", new JValue(txtMailAcc.Text));
jobj.Add("mailPwd", new JValue(txtMailPwd.Text));
jobj.Add("updateUser", new JValue(txtupdateUser.Text));
jobj.Add("clearance", new JValue(checkBoxIsCl.Checked));
if (rdImport.Checked) jobj.Add("ies", new JValue("I")); else jobj.Add("ies", new JValue("E"));
File.WriteAllText(CfgFilePath, jobj.ToString());
//启用定时器
tmrStart.Enabled = true;
//界面
btnStart.Enabled = false;
btnStop.Enabled = true;
groupParaGet.Enabled = false;
groupParaMail.Enabled = false;
groupSmtpSet.Enabled = false;
tslbStatus.Text = "定时已启动,等待执行……";
}
private void btnStop_Click(object sender, EventArgs e)
{
tmrStart.Enabled = false;
tmrExecute.Enabled = false;
btnStart.Enabled = true;
btnStop.Enabled = false;
groupParaGet.Enabled = true;
groupParaMail.Enabled = true;
groupSmtpSet.Enabled = true;
tslbStatus.Text = "停止执行";
}
//执行发送
private void tmrStart_Tick(object sender, EventArgs e)
{
var tSet = dtpGetTime.Value.ToString("yyyyMMddHHmm");
var tCurr = DateTime.Now.ToString("yyyyMMddHHmm");
if (tSet == tCurr)
{
tslbStatus.Text = "正在执行……";
try
{
//var jsonReq = new
//{
// swcn = txtCardNO.Text.Trim(),
// swpw = txtPwd.Text.Trim(),
// ies = "E",
// clearance = "1",
// starttime = dtpReqStart.Value.ToString("yyyy-MM-dd"),
// endtime = dtpReqEnd.Value.ToString("yyyy-MM-dd")
//};
//string strJson = JsonConvert.SerializeObject(jsonReq);
//log.Debug($"发送参数:{strJson}");
//var strRtn = WebRequestHelper.DoPost($"{SpiderUrl}/sw/dec/save", strJson);
Dictionary<string, string> dicPara = new Dictionary<string, string>();
dicPara.Add("swcn", txtCardNO.Text.Trim());
dicPara.Add("swpw", txtPwd.Text.Trim());
if (rdImport.Checked)
dicPara.Add("ies", "I");
else dicPara.Add("ies", "E");
if (checkBoxIsCl.Checked)
dicPara.Add("clearance", "1");
else
{
if (checkBoxCYTZ.Checked)
{
dicPara.Add("clearance", "0");
dicPara.Add("release", "no");
dicPara.Add("decStatus", "11");
}
else
{
dicPara.Add("clearance", "0");
dicPara.Add("release", "yes");
}
}
dicPara.Add("starttime", dtpReqStart.Value.ToString("yyyy-MM-dd"));
dicPara.Add("endtime", dtpReqEnd.Value.ToString("yyyy-MM-dd"));
dicPara.Add("updateUser", txtupdateUser.Text.Trim());
log.Debug($"发送参数:");
foreach (string key in dicPara.Keys)
{
log.Debug($"{key}{dicPara[key]}");
}
var strRtn = WebRequestHelper.DoPost($"{SpiderUrl}/sw/dec/save", dicPara);
log.Debug($"发送返回:{strRtn}");
var rtnObj = JsonConvert.DeserializeAnonymousType(strRtn, new
{
status = "",
message = ""
});
if (rtnObj.status == "1")
{
mid = rtnObj.message;
tslbStatus.Text = "参数已发送";
tmrStart.Enabled = false;
tmrExecute.Enabled = true;
log.Debug($"参数已发送");
}
else
{
tslbStatus.Text = $"参数发送失败:{rtnObj.message}";
log.Error($"参数发送失败:{rtnObj.message}");
}
}
catch (Exception ex)
{
tslbStatus.Text = $"参数发送失败:{ex.Message}";
log.Error($"参数发送失败:{ex.Message}");
log.Error(ex.StackTrace);
}
}
}
//执行获取
private void tmrExecute_Tick(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(mid))
{
tslbStatus.Text = "正在获取状态……";
try
{
Dictionary<string, string> dicPara = new Dictionary<string, string>();
dicPara.Add("mid", mid);
log.Debug($"获取状态参数:");
foreach (string key in dicPara.Keys)
{
log.Debug($"{key}{dicPara[key]}");
}
var strRtn = WebRequestHelper.DoPost($"{SpiderUrl}/sw/dec/status", dicPara);
log.Debug($"获取状态返回:{strRtn}");
var jobjSta = JObject.Parse(strRtn);
var status = jobjSta.GetValue("status").ToString();
if (status == "1")
{
tslbStatus.Text = "获取状态成功";
log.Debug($"获取状态成功");
var jStaInner = jobjSta.GetValue("message") as JObject;
var staInner = jStaInner.GetValue("Status").ToString();
if (staInner == "1")
{
tslbStatus.Text = "数据爬取完成,正在获取数据……";
log.Debug($"数据爬取完成,正在获取数据");
//调用获取数据接口获取数据
strRtn = WebRequestHelper.DoPost($"{SpiderUrl}/sw/dec/extract", dicPara);
log.Debug($"获取数据返回:{strRtn}");
//更新数据
var _status = JsonConvert.DeserializeObject<DecHead_status>(strRtn).status;
var result = new DecHead_WebModel();
if (_status == "1")
{
tmrExecute.Enabled = false; //防止二次执行
tslbStatus.Text = "获取数据完成,正在处理……";
try
{
JsonXFSend reqObj = new JsonXFSend();
//userid对应 DsPingTai.CUST_AUTH.userid
//如无对应userid 则服务端不记录上传的数据
//虎鲸 "a738ea17-661f-4647-8150-8216dcb6b52d"
reqObj.userId = Djy_CustAuth_Userid;
reqObj.module = "报关单一窗口";
reqObj.data = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(strRtn));
var sendstr = JsonConvert.SerializeObject(reqObj);
log.Debug($"数据上传大简云:{sendstr}");
string djyrtn = WebRequestHelper.DoPost("http://djypaas.myshipping.net/api/open/datapush", sendstr, 50 * 1000);
log.Debug($"获取数据返回:{djyrtn}");
}
catch (Exception ext){
log.Debug($"上传大简云错误:{ext.Message}");
}
var jDataAll = JsonConvert.DeserializeObject<DecHead_WebModel>(strRtn);
readDAL.Dealrtn(jDataAll, "1BEC90E1-9780-472F-90C2-0C6390C044A4", "系统管理员", "Comfeae8509f593407d8c6518cab62f5ad5");
log.Debug($"处理数据完成准备下载pdf……");
tslbStatus.Text = "处理数据完成准备下载pdf……";
int filecount = 0;
//查找报关单的pdf
List<pdfFileDownload> pdfFileList = new List<pdfFileDownload>();
foreach (var model in jDataAll.message)
{
foreach (var pdf in model.pdfFile)
{
var filename = "放行通知书";
if (checkBoxCYTZ.Checked) filename = "查验通知书";
if (pdf.filename == "报关单"|| pdf.filename == filename)
{
if (pdf.path.Trim() != "")
{
var pdfFileDownload = new pdfFileDownload();
pdfFileDownload.path = pdf.path;
pdfFileDownload.filename = pdf.filename;
if (model.data.preDecHeadVo != null)
{
var ctnnum = model.data.preDecHeadVo.contaCount;
if (ctnnum == "") ctnnum = "0";
var cntrno = "";
var portContainerlist = model.data.preDecHeadVo.getpreDecContainerVo();
var j = 0;
foreach (var portContainer in portContainerlist)
{
if (j==0||j==1)
cntrno = cntrno + portContainer.containerNo+"_";
j = j + 1;
}
var declist = model.data.preDecHeadVo.getdecMergeListVo();
pdfFileDownload.fileno = model.data.preDecHeadVo.entryId + "_"+ cntrno+ declist.Count;
}
else
{
filecount = filecount + 1;
pdfFileDownload.fileno = pdf.filename + filecount.ToString();
}
var tmpfile = pdfFileList.Find(x => x.path == pdf.path);
if (!(tmpfile == null))
{
}else pdfFileList.Add(pdfFileDownload);
}
}
}
}
log.Debug($"处理数据完成2准备下载pdf……");
//下载pdf
var tmpPathName = DateTime.Now.ToString("yyyyMMddHHmmssfff");
var tmpPath = Path.Combine(Application.StartupPath, tmpPathName);
Directory.CreateDirectory(tmpPath);
foreach (var f in pdfFileList)
{
var savePdf = Path.Combine(tmpPath,f.fileno+"("+f.filename+")"+DateTime.Now.ToString("mmssfff") + ".pdf");
WebClient wc = new WebClient();
wc.DownloadFile(f.path, savePdf);
log.Debug($"下载pdf"+ savePdf);
if (!chkNotGZ.Checked) SingPdf(savePdf, f.filename);
}
log.Debug($"下载pdf完成准备打包邮件……");
tslbStatus.Text = "下载pdf完成准备打包邮件……";
//打包
var destFile = Path.Combine(tmpPath, $"{tmpPathName}.zip");
using (ZipFile zipFile = ZipFile.Create(destFile))
{
zipFile.BeginUpdate();
var files = Directory.GetFiles(tmpPath, "*.pdf");
foreach (var ff in files)
{
zipFile.Add(ff, Path.GetFileName(ff));
}
zipFile.CommitUpdate();
}
log.Debug($"打包完成,准备发送邮件……");
tslbStatus.Text = "打包完成,准备发送邮件……";
//发邮件
var message = new MimeMessage();
message.From.Add(MailboxAddress.Parse(txtMailAcc.Text.Trim()));
var receiver = txtReceiver.Text.Trim();
if (receiver.IndexOf(",") > -1)
{
var arrSendTo = receiver.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
foreach (var s in arrSendTo)
{
message.To.Add(MailboxAddress.Parse(s));
}
}
else if (receiver.IndexOf(";") > -1)
{
var arrSendTo = receiver.Split(";".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
foreach (var s in arrSendTo)
{
message.To.Add(MailboxAddress.Parse(s));
}
}
else
{
message.To.Add(MailboxAddress.Parse(receiver));
}
message.Subject = txtSubject.Text.Trim();
var plain = new TextPart("plain")
{
Text = "请查看附件"
};
var builder = new BodyBuilder();
var zipAttach = new MimePart("application", "zip")
{
Content = new MimeContent(File.OpenRead(destFile), ContentEncoding.Default),
ContentDisposition = new ContentDisposition(ContentDisposition.Attachment),
ContentTransferEncoding = ContentEncoding.Base64,
FileName = Path.GetFileName(destFile)
};
var multipart = new Multipart("mixed");
multipart.Add(plain);
multipart.Add(zipAttach);
message.Body = multipart;
using (var client = new SmtpClient())
{
client.Connect(txtSmtpServer.Text.Trim(), (int)numStmpPort.Value, chkSSL.Checked);
client.Authenticate(txtMailAcc.Text.Trim(), txtMailPwd.Text.Trim());
client.Send(message);
client.Disconnect(true);
}
log.Debug($"全部完成");
tslbStatus.Text = "全部完成";
}
}
else
{
tslbStatus.Text = "数据还在爬取,稍后再次获取";
log.Debug($"数据还在爬取,稍后再次获取");
}
}
else
{
log.Debug($"获取状态失败");
tslbStatus.Text = "获取状态失败……";
}
}
catch (Exception ex)
{
tslbStatus.Text = $"获取失败:{ex.Message}";
log.Error($"获取失败:{ex.Message}");
log.Error(ex.StackTrace);
}
//btnStop_Click(sender, e);
//tslbStatus.Text = "执行完成";
}
}
//签章
private void SingPdf(string pdfFile,string pdfFileType)
{
try
{
var saveFile = pdfFile + ".m";
var imgFile = "";
if (radioButton2.Checked)
{
if (pdfFileType == "放行通知书" || pdfFileType == "查验通知书")
imgFile = Path.Combine(Application.StartupPath, "signtwo2.png");
else imgFile = Path.Combine(Application.StartupPath, "signtwo.png");
}
else
{
if (pdfFileType == "放行通知书" || pdfFileType == "查验通知书")
imgFile = Path.Combine(Application.StartupPath, "sign2.png");
else imgFile = Path.Combine(Application.StartupPath, "sign.png");
}
PdfReader reader = new PdfReader(pdfFile);
PdfWriter writer = new PdfWriter(saveFile);
PdfDocument pdfDoc = new PdfDocument(reader, writer);
Document document = new Document(pdfDoc);
var imgDataSign = ImageDataFactory.Create(imgFile);
for (int i = 1; i <= pdfDoc.GetNumberOfPages(); i++)
{
iText.Layout.Element.Image imgSign = new iText.Layout.Element.Image(imgDataSign);
if (pdfFileType == "放行通知书")
{
imgSign.SetFixedPosition(430, 30); //左、上、右、下
imgSign.SetWidth(120);
}
else if(pdfFileType == "查验通知书")
{
imgSign.SetFixedPosition(430, 520); //左、上、右、下
imgSign.SetWidth(120);
}
else
{
imgSign.SetFixedPosition(480, 400);//左、上、右、下
imgSign.SetWidth(100);
}
imgSign.SetPageNumber(i);
document.Add(imgSign);
}
document.Close();
pdfDoc.Close();
reader.Close();
writer.Close();
File.Delete(pdfFile);
File.Move(saveFile, pdfFile);
}
catch (Exception ex)
{
log.Error(ex.Message);
log.Error(ex.StackTrace);
}
}
private void chkSSL_CheckedChanged(object sender, EventArgs e)
{
if (chkSSL.Checked)
{
numStmpPort.Value = 465;
}
else
{
numStmpPort.Value = 25;
}
}
private void button1_Click(object sender, EventArgs e)
{
//更新数据
var _status = JsonConvert.DeserializeObject<DecHead_status>(textBox1.Text).status;
var result = new DecHead_WebModel();
if (_status == "1")
{
tmrExecute.Enabled = false; //防止二次执行
tslbStatus.Text = "获取数据完成,正在处理……";
var jDataAll = JsonConvert.DeserializeObject<DecHead_WebModel>(textBox1.Text);
readDAL.Dealrtn(jDataAll, "1BEC90E1-9780-472F-90C2-0C6390C044A4", "系统管理员", "Comfeae8509f593407d8c6518cab62f5ad5");
// readDAL.Dealrtn(jDataAll, "1BEC90E1-9780-472F-90C2-0C6390C044A4", "系统管理员", "Comcab2d43f60454327af30a131fc1d3abd");
log.Debug($"处理数据完成准备下载pdf……");
tslbStatus.Text = "处理数据完成准备下载pdf……";
int filecount = 0;
//查找报关单的pdf
//List<pdfFileDownload> pdfFileList = new List<pdfFileDownload>();
//foreach (var model in jDataAll.message)
//{
// foreach (var pdf in model.pdfFile)
// {
// if (pdf.filename == "报关单" || pdf.filename == "放行通知书")
// {
// if (pdf.path.Trim() != "")
// {
// var pdfFileDownload = new pdfFileDownload();
// pdfFileDownload.path = pdf.path;
// pdfFileDownload.filename = pdf.filename;
// if (model.data.preDecHeadVo != null)
// {
// var ctnnum = model.data.preDecHeadVo.contaCount;
// if (ctnnum == "") ctnnum = "0";
// pdfFileDownload.fileno = model.data.preDecHeadVo.entryId + "_" + model.data.preDecHeadVo.contaCount;
// }
// else {
// filecount = filecount + 1;
// pdfFileDownload.fileno = pdf.filename + filecount.ToString();
// }
// pdfFileList.Add(pdfFileDownload);
// }
// }
// }
//}
//log.Debug($"处理数据完成2准备下载pdf……");
////下载pdf
//var tmpPathName = DateTime.Now.ToString("yyyyMMddHHmmssfff");
//var tmpPath = Path.Combine(Application.StartupPath, tmpPathName);
//Directory.CreateDirectory(tmpPath);
//foreach (var f in pdfFileList)
//{
// var savePdf = Path.Combine(tmpPath, f.fileno + "(" + f.filename + ")" + DateTime.Now.ToString("mmssfff") + ".pdf");
// WebClient wc = new WebClient();
// wc.DownloadFile(f.path, savePdf);
// log.Debug($"下载pdf" + savePdf);
// SingPdf(savePdf, f.filename);
//}
//log.Debug($"下载pdf完成准备打包邮件……");
//tslbStatus.Text = "下载pdf完成准备打包邮件……";
}
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void button2_Click(object sender, EventArgs e)
{
SingPdf(@"E:\202100003817274097.PDF", "查验通知书");
}
}
}