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/JobAutoCreateFee/JobGetMscSwbData.cs

594 lines
23 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 JobAutoCreateFee.Model;
using log4net;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Quartz;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.IO;
using System.Net;
using System.Diagnostics;
namespace JobCreateFee
{
public class JobGetMscSwbData : IJob
{
private ILog log = LogManager.GetLogger(typeof(JobGetMscSwbData));
public void Execute(IJobExecutionContext context)
{
try
{
string connStr = context.JobDetail.JobDataMap.GetString("ConnectString");
string sqlQuery = context.JobDetail.JobDataMap.GetString("QuerySql");
string reqUrl = context.JobDetail.JobDataMap.GetString("ReqUrl");
int reqTimeout = Convert.ToInt32(context.JobDetail.JobDataMap.GetString("RequestTimeout"));
string tempPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "BcTmp");
log.Debug($"连接字符串:{connStr}");
log.Debug($"查询SQL{sqlQuery}");
log.Debug($"请求URL{reqUrl}");
log.Debug($"请求超时:{reqTimeout}");
SqlConnection conn = new SqlConnection(connStr);
SqlDataAdapter dataAdapter = new SqlDataAdapter(sqlQuery, conn);
DataTable tQuery = new DataTable();
dataAdapter.Fill(tQuery);
if (tQuery.Rows.Count == 0)
{
log.Debug("没有要发送的数据!");
return;
}
var json = DataTableToJsonHelper.ConvertToJson(tQuery);
log.Debug($"jsonStr{json.ToString(Formatting.None)}");
JObject reqObj = new JObject();
reqObj.Add("type", new JValue("search"));
reqObj.Add("data", json);
log.Debug($"reqObj{reqObj.ToString(Formatting.None)}");
//发送请求数据
string rtn = WebRequestHelper.DoPost(reqUrl, reqObj.ToString(Formatting.None), reqTimeout * 1000);
var objRtn = JsonConvert.DeserializeAnonymousType(rtn, new { code = "", msg = "" });
log.Debug($"爬取服务返回:{objRtn.msg}(Code:{objRtn.code})");
if (objRtn.code == "200") {
var JsonMscSwBObj = JsonConvert.DeserializeObject<JsonMscSwBResponse>(rtn);
foreach (var item in JsonMscSwBObj.data)
{
if (item.code == 1) {
if (!string.IsNullOrEmpty(item.details.file_url)) {
var mblno = item.mbn;
var bsno = GetBsNo(mblno,conn);
var tarpath = "";
var swbfile = Path.Combine(tempPath, item.details.file_name);
WebClient wc = new WebClient();
wc.DownloadFile(item.details.file_url, swbfile);
log.Debug($"下载swb" + swbfile);
Guadan(mblno, bsno, "Seaway挂单", swbfile, conn, out tarpath, true);
}
}
}
}
}
catch (Exception ex)
{
log.Error(ex.Message);
log.Error(ex.StackTrace);
}
}
static public string GetBsNo(string MBLNO, SqlConnection dbcon)
{
var headList = new List<MsChFee>();
var strSql = new StringBuilder();
strSql.Append("SELECT 编号 from t_op_seae where 业务类型='普通货' and 主提单号='" + MBLNO + "'");
var BSNO = "";
SqlDataAdapter adapter = new SqlDataAdapter(strSql.ToString(), dbcon);
DataTable table = new DataTable();
adapter.Fill(table);
if (table.Rows.Count > 0)
{
foreach (DataRow row in table.Rows)
{
BSNO= row["编号"].ToString();
}
}
return BSNO;
}
/// <summary>
///
/// </summary>
/// <param name="realfilepath"></param>
/// <param name="newreportid"></param>
/// <param name="fromway"></param>
/// <returns></returns>
public static bool TaskFileToNass(string realfilepath, string newreportid, int fromway)
{
bool isok = true;
return isok;
}
/// <summary>
/// 挂单之前要验证委托的业务是否存在
/// </summary>
/// <param name="mainNo"></param>
/// <param name="bsno"></param>
/// <param name="filetype"></param>
/// <param name="filename_src"></param>
/// <param name="guadanPath"></param>
/// <param name="isAddMblNoAsFilePre">是否将提单号作为目标文件前缀</param>
/// <returns></returns>
public bool Guadan(string mainNo, string bsno, string filetype, string filename_src, SqlConnection dbcon, out string guadanPath, bool isAddMblNoAsFilePre = false)
{
bool result;
double fsize;
int numunzipped;
int fid;
string naspath;
guadanPath = "";
filename_src = filename_src.Replace("/", "\\");
// 解决文件锁定的问题
try
{
result = true;
string insertsql;
//@ Undeclared identifier(3): 'get_parameters_value'
// naspath = FtpCommon.GetNassServerPath();
naspath = "";
string strsql = string.Format("select * from [t_op_file] where 编号='{0}'", bsno);
SqlCommand cmd = new SqlCommand();
cmd.CommandText = strsql.ToString();
cmd.CommandTimeout = 120000; //要加这一句
cmd.Connection = dbcon;
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
DataTable qry_op_file = new DataTable();
adapter.Fill(qry_op_file);
if (qry_op_file.Rows.Count <= 0)
{
insertsql = string.Format(@"INSERT INTO [t_op_file] ([编号],[文件类型],[备注]) VALUES('{0}','托书','是');
INSERT INTO [t_op_file] ([编号],[文件类型],[备注]) VALUES('{0}','入货通知','否');
INSERT INTO [t_op_file] ([编号],[文件类型],[备注]) VALUES('{0}','提单OK件','是');
INSERT INTO [t_op_file] ([编号],[文件类型],[备注]) VALUES('{0}','费用确认','是');
INSERT INTO [t_op_file] ([编号],[文件类型],[备注]) VALUES('{0}','提单留底','否');
INSERT INTO [t_op_file] ([编号],[文件类型],[备注]) VALUES('{0}','提单确认','否');
INSERT INTO [t_op_file] ([编号],[文件类型],[备注]) VALUES('{0}','舱单','否');
INSERT INTO [t_op_file] ([编号],[文件类型],[备注]) VALUES('{0}','报关资料','否');
INSERT INTO [t_op_file] ([编号],[文件类型],[备注]) VALUES('{0}','提单COPY','否');
INSERT INTO [t_op_file] ([编号],[文件类型],[备注]) VALUES('{0}','船公司账单','否');
INSERT INTO [t_op_file] ([编号],[文件类型],[备注]) VALUES('{0}','正本提单交回回执条','否');
INSERT INTO [t_op_file] ([编号],[文件类型],[备注]) VALUES('{0}','保函','否');
INSERT INTO [t_op_file] ([编号],[文件类型],[备注]) VALUES('{0}','船公司挂单','否');", bsno);
dbcon.Open();
SqlCommand cmdinsert = new SqlCommand(insertsql, dbcon);
cmdinsert.ExecuteNonQuery();
dbcon.Close();
}
strsql = string.Format("select * from [t_op_file] where 编号='{0}' and 文件类型='{1}'", bsno, filetype);
cmd.CommandText = strsql.ToString();
cmd.CommandTimeout = 120000; //要加这一句
cmd.Connection = dbcon;
SqlDataAdapter adaptertmp = new SqlDataAdapter(cmd);
adapter.Fill(qry_op_file);
if (qry_op_file.Rows.Count < 1)
{
insertsql = string.Format(@"INSERT INTO [t_op_file] ([编号],[文件类型],[备注]) VALUES('{0}','{1}','否');", bsno, filetype);
dbcon.Open();
SqlCommand cmdinsert = new SqlCommand(insertsql, dbcon);
cmdinsert.ExecuteNonQuery();
dbcon.Close();
}
// 上传附件
if (File.Exists(filename_src))
{
//// 拷贝到临时目录
////@ Undeclared identifier(3): 'GetWinTempPath'
//filename = GetWinTempPath() + Path.GetFileName(filename_src);
//if ((File.Exists(filename)))
//{
// File.Delete(filename);
//}
//File.Copy((filename_src as string), (filename as string), false);
FileInfo flinfo = new FileInfo(filename_src);
fsize = flinfo.Length;
//@ Unsupported property or method(A): 'fieldbyname'
//@ Unsupported property or method(D): 'AsInteger'
fid = int.Parse(qry_op_file.Rows[0]["FID"].ToString());
try
{
if (UpLoadProFile(filename_src, naspath, "user", "user", mainNo, bsno, fid, filetype, dbcon, out guadanPath, isAddMblNoAsFilePre))
{
// 更新数量及任务路径
}
//updateGuadanFilecount(fid, bsno, dbcon);
}
finally
{
}
}
else
{
log.Debug("文件不存在或者不能访问 ");
result = false;
return result;
}
}
catch (Exception ex)
{
result = false;
log.Error("文件不存在或者不能访问 " + filename_src + ex.Message);
}
return result;
}
/// <summary>
/// 电子文档挂单
/// </summary>
/// <param name="filename_src"></param>
/// <param name="RemotePathName"></param>
/// <param name="Users"></param>
/// <param name="pw"></param>
/// <param name="mblNo">主提单号</param>
/// <param name="bsno"></param>
/// <param name="fid"></param>
/// <param name="filetype"></param>
/// <param name="newpath"></param>
/// <param name="isAddMblNoAsFilePre">是否在目标文件名前加[mblNo]前缀:true表示加,反之不加</param>
/// <returns></returns>
public static bool UpLoadProFile(string filename_src, string RemotePathName, string Users, string pw, string mblNo, string bsno, int fid, string filetype, SqlConnection dbcon, out string newpath, bool isAddMblNoAsFilePre = false)
{
string path;
string filePath;
string filepath_pre;
string filename;
string fileExt;
// 上传文件
newpath = "";
filename = Path.GetFileName(filename_src);
fileExt = Path.GetExtension(filename);
bool status = false;
try
{
//连接共享文件夹
status = connectState(RemotePathName, Users, pw);
if (status)
{
//共享文件夹的目录
DirectoryInfo theFolder = new DirectoryInfo(RemotePathName);
//相对共享文件夹的路径
//string fielpath = @"\123\456\";
// filePath = FormatDateTime("YYYYMM",DateTime.Today);
filePath = DateTime.Today.ToString("yyyyMM");
if (!Directory.Exists(RemotePathName + '\\' + filePath))
{
Directory.CreateDirectory(RemotePathName + '\\' + filePath);
}
if (!Directory.Exists(RemotePathName + '\\' + filePath + '\\' + mblNo))
{
Directory.CreateDirectory(RemotePathName + '\\' + filePath + '\\' + mblNo);
}
// 增加类型
filepath_pre = RemotePathName + '\\' + filePath + '\\' + mblNo.Trim() + '\\' + filetype;
if (!Directory.Exists(filepath_pre))
{
Directory.CreateDirectory(filepath_pre);
}
///newpath = filepath_pre + '\\' + filename;
if (isAddMblNoAsFilePre)
{
filename = mblNo.Trim() + "_" + DateTime.Now.ToString("yyyyMMddHHmmss") + "_" + filename;
}
newpath = filepath_pre + '\\' + filename;
//获取保存文件的路径
string filePathTarget = filepath_pre;// theFolder.ToString() + fielpath;
//执行方法
Transport(filename_src, filePathTarget, filename);
}
else
{
return false;
}
FileInfo flinfo = new FileInfo(filename_src);
long fsize = flinfo.Length;
string insertsql_dbfile_pre = "INSERT INTO [t_op_file_items]([编号],[名称], [大小],[上传日期],[所有者],[类型],[文件类型],[Pid],[文件存储])"
+ "VALUES('{0}','{1}','{2}',GETDATE(),'DEMO-SA','{3}','{4}','{5}',1);";
string insertsql_dbfile = string.Format(insertsql_dbfile_pre, new object[] { bsno, newpath, fsize, fileExt, filetype, fid });
dbcon.Open();
SqlCommand cmdinsert = new SqlCommand(insertsql_dbfile, dbcon);
cmdinsert.ExecuteNonQuery();
dbcon.Close();
status = true;
}
catch (Exception ex)
{
status = false;
}
return status;
}
//public static bool updateGuadanFilecount(int fid, string bsno)
//{
// string sqlCount;
// sqlCount = string.Format("select count(fid) as ncount from t_op_file_items where PID='{0}' and 编号='{1}';", fid, bsno);
// string ncount = DbHelperSQL.GetNassPath(sqlCount);
// string updatecount = string.Format("Update t_op_file set 大小='{0}' where FID='{1}'", ncount, fid);
// int i = DbHelperSQL.ExecuteSql(updatecount);
// return i > 0;
//}
/// <summary>
/// 任务文件路径复制到Nass
/// </summary>
/// <param name="extPath"></param>
/// <param name="filename_src"></param>
/// <param name="mblNo"></param>
/// <param name="filetype"></param>
/// <param name="newpath"></param>
/// <param name="bsno"></param>
/// <param name="isAddMblNoAsFilePre">是否使用主提单号[mblNo]作为上传文件名的前缀</param>
/// <returns></returns>
//public static bool UpLoadFileToNass(string extPath, string filename_src, string mblNo, string filetype, out string newpath, string bsno = null, bool isAddMblNoAsFilePre = false)
//{
// newpath = "";
// string filePath;
// string filepath_pre;
// string filename;
// string fileExt;
// string RemotePathName, Users, pw;
// bool isok = true;
// filename_src = filename_src.Replace("/", "\\");
// try
// {
// // 解决文件锁定的问题
// string insertsql;
// //@ Undeclared identifier(3): 'get_parameters_value'
// RemotePathName = FtpCommon.GetNassServerPath();
// Users = "user";
// pw = "user";
// // 上传文件
// newpath = "";
// filename = Path.GetFileName(filename_src);
// fileExt = Path.GetExtension(filename);
// bool status = false;
// //连接共享文件夹
// status = connectState(RemotePathName, Users, pw);
// if (status)
// {
// //共享文件夹的目录
// DirectoryInfo theFolder = new DirectoryInfo(RemotePathName);
// //相对共享文件夹的路径:Task任务
// if (!string.IsNullOrEmpty(extPath))
// {
// RemotePathName += '\\' + extPath;
// if (!Directory.Exists(RemotePathName))
// {
// Directory.CreateDirectory(RemotePathName);
// }
// }
// filePath = DateTime.Today.ToString("yyyyMM");
// if (!Directory.Exists(RemotePathName + '\\' + filePath))
// {
// Directory.CreateDirectory(RemotePathName + '\\' + filePath);
// }
// if (string.IsNullOrEmpty(mblNo))
// {
// if (!string.IsNullOrEmpty(bsno))
// mblNo = bsno.Trim();
// else mblNo = "tmp" + DateTime.Today.ToString("yyyyMM");
// }
// if (!Directory.Exists(RemotePathName + '\\' + filePath + '\\' + mblNo))
// {
// Directory.CreateDirectory(RemotePathName + '\\' + filePath + '\\' + mblNo);
// }
// // 增加类型
// if (string.IsNullOrEmpty(filetype))
// {
// filetype = "未指定";
// }
// filepath_pre = RemotePathName + '\\' + filePath + '\\' + mblNo.Trim() + '\\' + filetype;
// if (!Directory.Exists(filepath_pre))
// {
// Directory.CreateDirectory(filepath_pre);
// }
// ///newpath = filepath_pre + '\\' + filename;
// if (isAddMblNoAsFilePre)
// {
// //filename = mblNo.Trim() + "_" + filename;
// filename = mblNo.Trim() + "_" + DateTime.Now.ToString("yyyyMMddHHmmss") + "_" + filename;
// }
// // out 参数,目标文件名
// newpath = filepath_pre + '\\' + filename;
// //获取保存文件的路径
// string filePathTarget = filepath_pre;// theFolder.ToString() + fielpath;
// //执行方法
// Transport(filename_src, filePathTarget, filename);
// isok = true;
// }
// else
// {
// isok = false;
// }
// }
// catch (Exception ex)
// {
// LogHelper.WriteLog("复制文件到Nass服务器发生错误", ex.Message);
// isok = false;
// }
// return isok;
//}
/// <summary>
/// 匿名连接
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
public static bool connectState(string path)
{
return connectState(path, "", "");
}
/// <summary>
/// 连接远程共享文件夹
/// </summary>
/// <param name="path">远程共享文件夹的路径</param>
/// <param name="userName">用户名</param>
/// <param name="passWord">密码</param>
/// <returns></returns>
public static bool connectState(string path, string userName, string passWord)
{
bool Flag = false;
Process proc = new Process();
try
{
proc.StartInfo.FileName = "cmd.exe";
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.RedirectStandardInput = true;
proc.StartInfo.RedirectStandardOutput = true;
proc.StartInfo.RedirectStandardError = true;
proc.StartInfo.CreateNoWindow = true;
proc.Start();
string dosLine = "net use " + path + " " + passWord + " /user:" + userName;
proc.StandardInput.WriteLine(dosLine);
proc.StandardInput.WriteLine("exit");
while (!proc.HasExited)
{
proc.WaitForExit(1000);
}
string errormsg = proc.StandardError.ReadToEnd();
proc.StandardError.Close();
if (string.IsNullOrEmpty(errormsg))
{
Flag = true;
}
else
{
throw new Exception(errormsg);
}
}
catch (Exception ex)
{
throw ex;
}
finally
{
proc.Close();
proc.Dispose();
}
return Flag;
}
/// <summary>
/// 向远程文件夹保存本地内容,或者从远程文件夹下载文件到本地
/// </summary>
/// <param name="src">要保存的文件的路径,如果保存文件到共享文件夹,这个路径就是本地文件路径如:@"D:\1.avi"</param>
/// <param name="dst">保存文件的路径,不含名称及扩展名</param>
/// <param name="fileName">保存文件的名称以及扩展名</param>
public static void Transport(string src, string dst1, string fileName)
{
FileStream inFileStream = new FileStream(src, FileMode.Open);
if (!Directory.Exists(dst1))
{
Directory.CreateDirectory(dst1);
}
string dst = Path.Combine(dst1, fileName);
if (File.Exists(dst))
{
try
{
File.Delete(dst);
}
catch (Exception)
{
File.Move(dst, dst + ".bak");
}
}
FileStream outFileStream = new FileStream(dst, FileMode.OpenOrCreate);
byte[] buf = new byte[inFileStream.Length];
int byteCount;
while ((byteCount = inFileStream.Read(buf, 0, buf.Length)) > 0)
{
outFileStream.Write(buf, 0, byteCount);
}
inFileStream.Flush();
inFileStream.Close();
outFileStream.Flush();
outFileStream.Close();
}
}
}