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.

1679 lines
80 KiB
C#

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity.Validation;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Web.Mvc;
using DSWeb.Areas.CommMng.DAL;
using Microsoft.Office.Interop.Excel;
using NPOI.SS.Formula.Functions;
using System.Data.Entity;
using System.Text;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using System.Net.Http;
using System.Net.Http.Headers;
using DSWeb.Common.Helper;
using System.Net;
using DSWeb.MvcShipping.Helper;
using JsonConvert = Newtonsoft.Json.JsonConvert;
using Microsoft.Practices.EnterpriseLibrary.Data;
using DSWeb.EntityDA;
using System.Threading;
using DSWeb.MvcShipping.DAL.DsSendmail;
using DSWeb.Common.DbContexts.Model;
using DSWeb.Common.DbContexts;
using log4net;
using DSWeb.Common.DB;
using System.Threading.Tasks;
using DSWeb.Common.Model;
using System.Runtime.Caching;
namespace DSWeb.MvcShipping.Controllers
{
/// <summary>
/// 拼箱申请单
/// </summary>
public class MsFormRequisitionController : Controller
{
#region 拼箱申请单
private OpSeaePxDbContenxt context = new OpSeaePxDbContenxt();
private delegate string FuncHandle(string str, string url, int timeout);
private string SendId;
private OpSeaePx SendUpd;
private DSWeb.Common.DbContexts.Model.CustFee CustAdd;
private DSWeb.Common.DbContexts.Model.CustBalance BalanceUpd;
private ILog logger = LogManager.GetLogger("MsFormRequisitionController");
public ActionResult StandingBook()
{
var a = BasicDataRefDAL.GetVesselList("");
ViewData["ShipName"] = BasicDataRefDAL.GetVesselList("");
var pxCom = context.ComNameInfo.Select(p => p).Where(p => p.ISPXCOMPANY != 0).ToList();
ViewData["pxCom"] = pxCom.Select(p => p.COMNAME).ToList();
return View();
}
[HttpGet]
//public JsonResult GetPageTab(int start, int limit, string sort, string condition)
public JsonResult GetPageTab(PxTableClass vlass, int offset = 1, int limit = 12)
{
try
{
string userid = Convert.ToString(Session["USERID"]);
var str = GetRangDAStr("index", userid, Convert.ToString(Session["SHOWNAME"]), Convert.ToString(Session["COMPANYID"]));
if (userid == "" || userid == null)
{
var jsonRespose2 = new JsonResponse { Success = false, Message = "登陆状态失效,请重新登陆进行操作!" };
return Json(new { Success = false, Message = "登陆状态失效,请重新登陆进行操作!", totalCount = 0, data = 0 }, JsonRequestBehavior.AllowGet);
}
int count = 0;
StringBuilder sqlStr = new StringBuilder("select *,(select COMNAME from [user] where GID=op_seae_px.LuRuRenId) as COMNAME from op_seae_px where 1=1");
if (!string.IsNullOrEmpty(vlass.ShangPinBianMa))
{
sqlStr.Append(" and (select COUNT(ShangPinBianMa) from op_seae_px_details where PXID=op_seae_px.GID and ShangPinBianMa like '%" + vlass.ShangPinBianMa + "%')>0"); ;
}
if (!string.IsNullOrEmpty(vlass.MBLNO))
{
sqlStr.Append(" and MBLNO like '%" + vlass.MBLNO + "%'");
}
if (!string.IsNullOrEmpty(vlass.ShenBaoZhuangTai))
{
sqlStr.Append(" and ShenBaoZhuangTai='" + vlass.ShenBaoZhuangTai + "'");
}
if (!string.IsNullOrEmpty(vlass.CangKuMingCheng))
{
sqlStr.Append(" and CangKuMingCheng='" + vlass.CangKuMingCheng + "'");
}
if (!string.IsNullOrEmpty(vlass.ChuanMing))
{
sqlStr.Append(" and ChuanMing like '%" + vlass.ChuanMing + "%'");
}
if (!string.IsNullOrEmpty(vlass.HangCi))
{
sqlStr.Append(" and HangCi='" + vlass.HangCi + "'");
}
if (!string.IsNullOrEmpty(vlass.LuRuRiQi.ToString()))
{
sqlStr.Append(" and LuRuRiQi>='" + vlass.LuRuRiQi + "'");
}
if (!string.IsNullOrEmpty(vlass.Dao.ToString()))
{
sqlStr.Append(" and LuRuRiQi<='" + vlass.Dao + "'");
}
if (!string.IsNullOrEmpty(vlass.PXCOMNAME))
{
sqlStr.Append(" and PXCOMNAME='" + vlass.PXCOMNAME + "'");
}
if (!string.IsNullOrEmpty(vlass.LuRuRen))
{
sqlStr.Append(" and LuRuRen='" + vlass.LuRuRen + "'");
}
if (!string.IsNullOrEmpty(str))
{
sqlStr.Append("and " + str);
}
sqlStr.Append(" order by LuRuRiQi desc");
var lists = context.OpSeaePxs.SqlQuery(sqlStr.ToString()).Skip(offset).Take(limit).OrderByDescending(p => p.LuRuRiQi).ToList();
var counts = context.OpSeaePxs.SqlQuery(sqlStr.ToString()).Count();
//var listAll=list.Select<>
var json = new { total = counts, rows = lists, Offset = offset };
return Json(json, JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
logger.ErrorFormat("GetPageTab" + ex);
return Json(new { total = 1, rows = ex }, JsonRequestBehavior.AllowGet);
}
}
[HttpGet]
public ActionResult GetSendDatas(string idstr)
{
AsyncCallback callback = new AsyncCallback(MethodCompleted);
FuncHandle fh = new FuncHandle(DoPost);
IAsyncResult ar = fh.BeginInvoke(idstr, "http://47.104.90.170:9000/qdpxd/upload", 90000, callback, fh);
return Json("", JsonRequestBehavior.AllowGet);
//Thread thead = new Thread(()=>GetSendDatas(idstr));
//thead.Start();
//return Json("", JsonRequestBehavior.AllowGet);
}
private void MethodCompleted(IAsyncResult asyncResult)
{
lock (this)
{
if (asyncResult == null) return;
var msg = (asyncResult.AsyncState as FuncHandle).EndInvoke(asyncResult);
var data = (JObject)JsonConvert.DeserializeObject(msg);
context = new OpSeaePxDbContenxt();
if (Convert.ToInt32(data["status"]) > 0)
{
SendUpd.ShenBaoZhuangTai = "发送成功";
OpSeaePxTips tips = new OpSeaePxTips();
tips.GID = getGUID();
tips.PXID = SendUpd.Gid;
tips.PXSTATUS = SendUpd.ShenBaoZhuangTai;
tips.@operator = SendUpd.LuRuRen;
tips.optime = DateTime.Now;
tips.remark = data["message"].ToString();
context.OpSeaePxTips.Add(tips);
context.Entry(SendUpd).State = System.Data.Entity.EntityState.Modified;
CustAdd.GID = Guid.NewGuid().ToString().Replace("-", "");
context.CustFee.Add(CustAdd);
context.Entry(BalanceUpd).State = System.Data.Entity.EntityState.Modified;
}
else
{
OpSeaePxTips tips = new OpSeaePxTips();
tips.GID = getGUID();
tips.PXID = SendUpd.Gid;
tips.PXSTATUS = "发送失败";
tips.@operator = SendUpd.LuRuRen;
tips.optime = DateTime.Now;
tips.remark = data["message"].ToString();
context.OpSeaePxTips.Add(tips);
OpSeaePx send = context.OpSeaePx.Select(p => p).Where(p => p.Gid.Equals(SendId)).ToList().FirstOrDefault();
send.ShenBaoZhuangTai = "发送失败";
context.Entry(send).State = System.Data.Entity.EntityState.Modified;
}
var state = context.SaveChanges();
}
}
[HttpGet]
public ActionResult GetSendData(string idstr)
{
try
{
string userid = Convert.ToString(Session["USERID"]);
if (userid == "" || userid == null)
{
var jsonRespose2 = new JsonResponse { Success = false, Message = "登陆状态失效,请重新登陆进行操作!" };
return Json(new { status = 0, message = "登陆状态失效,请重新登陆进行操作!" }, JsonRequestBehavior.AllowGet);
}
var idArr = idstr.Substring(0, idstr.Length - 1);
var arry = idArr.Split(',');
JObject sendObj = new JObject();
string sql = "select op_seae_px.GID as PGID,op_seae_px.ChuanMing,op_seae_px.HangCi,op_seae_px.CangKuMingCheng,op_seae_px.TiJi,op_seae_px.MBLNO,op_seae_px.JianShu,op_seae_px_details.GID,op_seae_px_details.ShangPinBianMa,op_seae_px_details.ShangPinMingCheng,op_seae_px_details.ShenBaoShuLiang,MaoZhong,COMNAME_INFO.ISPXCOMPANY,COMNAME_INFO.PXCOMACCOUNT,COMNAME_INFO.PXCOMPASSWORD,COMNAME_INFO.EPortCardNO from op_seae_px join op_seae_px_details on op_seae_px.GID=op_seae_px_details.PXID left join COMNAME_INFO on op_seae_px.PXCOMNAME=COMNAME_INFO.COMNAME where op_seae_px.GID in (" + idArr + ")";
var liss = context.PxAndDelat.SqlQuery(sql).ToList();
var com = Convert.ToString(Session["COMNAME"]);
//string Url = "http://47.104.90.170:9000/qdpxd/upload";
var money = context.CustBalance.Where(b => b.COMNAME == com).FirstOrDefault();
var price = context.CustPrice.Where(p => p.COMNAME == com && p.BSTYPE == 2 && p.SENDTYPE == 0).OrderByDescending(p => p.UPDATETIME).FirstOrDefault();
if (price == null)
{
return Json(new { status = 0, message = "单价模板未配置,请联系管理员添加!" }, JsonRequestBehavior.AllowGet);
}
decimal unitPrice = price.PRICE;
if (money.Balance < (unitPrice * arry.Count()) || money == null)
{
return Json(new { status = 0, message = "余额不足!" }, JsonRequestBehavior.AllowGet);
}
var date = context.SysParamSet.Where(p => p.GID == "B97B49D4-14E7-4ED7-8F42-D8D1FF47E67F").FirstOrDefault();
if (date == null)
{
return Json(new { status = 0, message = "请联系管理员设置拼箱申请单参数!" }, JsonRequestBehavior.AllowGet);
}
string rtn = "";
JObject SendData;
var tu = "";
var state = 0;
bool ts = Convert.ToInt32(date.PARAMVALUE) > 0 ? true : false;
foreach (var item in arry)
{
var a = item.Substring(1, (item.Length - 2));
List<PxAndDelat> lis = liss.Select(p => p).Where(p => p.PGID == a).ToList();
if (lis.Count < 1)
{
return Json(new { status = 0, message = "请录入HS编码一个提单号下可有多个" }, JsonRequestBehavior.AllowGet);
}
#region 2021-3-8修改改用户名、密码方式为卡号方式
#region 原逻辑,用户名密码方式
sendObj.Add("yardid", new JValue("qdpxd"));
if (string.IsNullOrEmpty(lis[0].PXCOMACCOUNT) || string.IsNullOrEmpty(lis[0].PXCOMPASSWORD) || lis[0].ISPXCOMPANY == 0)
{
var pxCurrentLogin = context.ComNameInfo.Where(p => p.COMNAME == com && p.ISPXCOMPANY != null).ToList();
if (pxCurrentLogin.Count < 1 || string.IsNullOrEmpty(pxCurrentLogin[0].PXCOMACCOUNT) || string.IsNullOrEmpty(pxCurrentLogin[0].PXCOMPASSWORD))
{
var pxAdm = context.ComNameInfo.Select(p => p).Where(p => p.COMNAME == "青岛东胜伟业软件有限公司" && p.ISPXCOMPANY != null).ToList();
if (pxAdm.Count < 1 || string.IsNullOrEmpty(pxAdm[0].PXCOMACCOUNT) || string.IsNullOrEmpty(pxAdm[0].PXCOMPASSWORD))
{
return Json(new { status = 0, message = "请先联系业务人员配置拼箱平台账号信息!" }, JsonRequestBehavior.AllowGet);
}
else
{
sendObj.Add("username", new JValue(pxAdm[0].PXCOMACCOUNT));
sendObj.Add("password", new JValue(pxAdm[0].PXCOMPASSWORD));
}
}
else
{
sendObj.Add("username", new JValue(pxCurrentLogin[0].PXCOMACCOUNT));
sendObj.Add("password", new JValue(pxCurrentLogin[0].PXCOMPASSWORD));
}
}
else
{
sendObj.Add("username", new JValue(lis[0].PXCOMACCOUNT));
sendObj.Add("password", new JValue(lis[0].PXCOMPASSWORD));
}
#endregion
#region 新逻辑:卡号方式
//if (string.IsNullOrEmpty(lis[0].EPortCardNO) || lis[0].ISPXCOMPANY == 0)
//{
// var pxCurrentLogin = context.ComNameInfo.Where(p => p.COMNAME == com && p.ISPXCOMPANY != null).ToList();
// if (pxCurrentLogin.Count < 1 || string.IsNullOrEmpty(pxCurrentLogin[0].EPortCardNO))
// {
// var pxAdm = context.ComNameInfo.Select(p => p).Where(p => p.COMNAME == "青岛东胜伟业软件有限公司" && p.ISPXCOMPANY != null).ToList();
// if (pxAdm.Count < 1 || string.IsNullOrEmpty(pxAdm[0].EPortCardNO))
// {
// return Json(new { status = 0, message = "请先联系业务人员配置拼箱平台卡号信息!" }, JsonRequestBehavior.AllowGet);
// }
// else
// {
// sendObj.Add("username", new JValue(pxAdm[0].EPortCardNO));
// }
// }
// else
// {
// sendObj.Add("username", new JValue(pxCurrentLogin[0].EPortCardNO));
// }
//}
//else
//{
// sendObj.Add("username", new JValue(lis[0].EPortCardNO));
//}
#endregion
#endregion
JArray jarrTemps = new JArray();
var q = 0;
foreach (var items in lis)
{
tu = items.MBLNO;
JObject jobjCtn = new JObject();
//if (i != 0)
//{
// data += ",";
//}
q++;
if (string.IsNullOrEmpty(items.MBLNO))
{
return Json(new { status = 0, message = "提单号不能为空!" }, JsonRequestBehavior.AllowGet);
}
if (string.IsNullOrEmpty(items.ChuanMing))
{
return Json(new { status = 0, message = "提单号" + items.MBLNO + "的船名不能为空!" }, JsonRequestBehavior.AllowGet);
}
if (string.IsNullOrEmpty(items.CangKuMingCheng))
{
return Json(new { status = 0, message = "提单号" + items.MBLNO + "的仓库名称不能为空!" }, JsonRequestBehavior.AllowGet);
}
if (string.IsNullOrEmpty(items.HangCi))
{
return Json(new { status = 0, message = "提单号" + items.MBLNO + "的航次不能为空!" }, JsonRequestBehavior.AllowGet);
}
if (items.JianShu == 0)
{
return Json(new { status = 0, message = "提单号" + items.MBLNO + "的件数不能为空!" }, JsonRequestBehavior.AllowGet);
}
if (items.MaoZhong == 0)
{
return Json(new { status = 0, message = "提单号" + items.MBLNO + "的重量不能为空!" }, JsonRequestBehavior.AllowGet);
}
if (items.TiJi == 0)
{
return Json(new { status = 0, message = "提单号" + items.MBLNO + "的尺码不能为空!" }, JsonRequestBehavior.AllowGet);
}
if (string.IsNullOrEmpty(items.ShangPinBianMa))
{
return Json(new { status = 0, message = "提单号" + items.MBLNO + "的商品编码不能为空!" }, JsonRequestBehavior.AllowGet);
}
if (string.IsNullOrEmpty(items.ShangPinMingCheng))
{
return Json(new { status = 0, message = "提单号" + items.MBLNO + ",商品编码" + items.ShangPinBianMa + "的商品名称不能为空!" }, JsonRequestBehavior.AllowGet);
}
if (items.ShenBaoShuLiang == 0)
{
return Json(new { status = 0, message = "提单号" + items.MBLNO + ",商品编码" + items.ShangPinBianMa + "的申报数量不能为空!" }, JsonRequestBehavior.AllowGet);
}
jobjCtn.Add("Vessel", new JValue(items.ChuanMing));
jobjCtn.Add("Voyage", new JValue(items.HangCi));
jobjCtn.Add("mblno", new JValue(items.MBLNO.Trim()));
jobjCtn.Add("PCode", new JValue(items.ShangPinBianMa.Length > 8 ? items.ShangPinBianMa.Substring(0, 8) : items.ShangPinBianMa));
jobjCtn.Add("PName", new JValue(items.ShangPinMingCheng.Replace(',', '')));
jobjCtn.Add("Count", new JValue(Convert.ToDouble(items.ShenBaoShuLiang).ToString()));
jobjCtn.Add("StoreName", new JValue(items.CangKuMingCheng));
if (q != lis.Count())
{
jobjCtn.Add("noc", new JValue("0.001"));
jobjCtn.Add("GrossWeight", new JValue("0.001"));
jobjCtn.Add("Volume", new JValue("0.001"));
}
else
{
jobjCtn.Add("noc", new JValue(Convert.ToDouble((items.JianShu - (lis.Count() - 1) * (decimal)0.001)).ToString()));
jobjCtn.Add("GrossWeight", new JValue(Convert.ToDouble((items.MaoZhong - (lis.Count() - 1) * (decimal)0.001)).ToString()));
jobjCtn.Add("Volume", new JValue(Convert.ToDouble((items.TiJi - (lis.Count() - 1) * (decimal)0.001)).ToString()));
}
//data += @"{'Vessel': '" + item.ChuanMing + "','Voyage': '" + item.HangCi + "','mblno': '" + item.MBLNO + "','PCode': '" + item.ShangPinBianMa + "','PName': '" + item.ShangPinMingCheng + "','Count': '" + item.ShenBaoShuLiang + "','StoreName': '" + item.CangKuMingCheng + "','noc': '" + item.JianShu + "','GrossWeight': '" + item.MaoZhong + "','Volume': '" + item.TiJi + "'}";
//i = 1;
jarrTemps.Add(jobjCtn);
}
sendObj.Add("ts", new JValue(ts));
sendObj.Add("bslist", jarrTemps);
var b = sendObj.ToString();
logger.Debug($"拼箱申请单发送:{b}");
SendData = (JObject)JsonConvert.DeserializeObject(rtn);
//if (Convert.ToInt32(SendData["status"]) > 0)
//{
context = new OpSeaePxDbContenxt();
SendId = item.ToString().Substring(1, item.Length - 2);
var t = item.ToString().Substring(1, item.Length - 2);
OpSeaePx send = context.OpSeaePx.Select(p => p).Where(p => p.Gid.Equals(t)).ToList().FirstOrDefault();
send.ShenBaoZhuangTai = "已发送";
send.SendTim = DateTime.Now;
SendUpd = send;
context.Entry(send).State = System.Data.Entity.EntityState.Modified;
DSWeb.Common.DbContexts.Model.CustFee custFee = new DSWeb.Common.DbContexts.Model.CustFee();
custFee.GID = Guid.NewGuid().ToString().Replace("-", "");
custFee.BSNO = t;
custFee.MBLNO = send.MBLNO;
custFee.PRICE = unitPrice;
custFee.CREATETIME = DateTime.Now;
custFee.SENDTIME = DateTime.Now;
custFee.BSTYPE = 2;
custFee.BEIZHU = "";
custFee.SENDTYPE = 0;
custFee.VESSEL = send.ChuanMing;
custFee.VOYNO = send.HangCi;
//custFee.SENDUSER = user.SHOWNAME;
//custFee.SENDCOM = user.COMNAME;
//custFee.COMNAME = user.COMNAME;
//custFee.SENDUSERID = user.GID;
//custFee.LURURENID = user.GID;
custFee.SENDCOM = com;
custFee.SENDUSER = Convert.ToString(Session["SHOWNAME"]);
custFee.SENDUSERID = Convert.ToString(Session["USERID"]);
custFee.LURURENID = Convert.ToString(Session["USERID"]);
custFee.LURUREN = Convert.ToString(Session["SHOWNAME"]);
custFee.CANGKU = send.CangKuMingCheng;
custFee.PKGS = (float)send.JianShu;
custFee.KGS = (float)send.MaoZhong;
custFee.COMNAME = com;
CustAdd = custFee;
//context.CustFee.Add(custFee);
money.Balance -= unitPrice;
BalanceUpd = money;
//context.Entry(money).State = System.Data.Entity.EntityState.Modified;
OpSeaePxTips tips = new OpSeaePxTips();
tips.GID = getGUID();
tips.PXID = send.Gid;
tips.PXSTATUS = send.ShenBaoZhuangTai;
tips.@operator = Convert.ToString(Session["SHOWNAME"]);
tips.optime = DateTime.Now;
tips.remark = "发送业务";
context.OpSeaePxTips.Add(tips);
state = context.SaveChanges();
AsyncCallback callback = new AsyncCallback(MethodCompleted);
FuncHandle fh = new FuncHandle(DoPost);
var strJsonSend = sendObj.ToString();
logger.Debug($"拼箱申请单发送GID{tips.GID},内容:{strJsonSend}");
//IAsyncResult ar = fh.BeginInvoke(strJsonSend, "http://47.104.90.170:9000/qdpxd/card/upload", 90000, callback, fh);
IAsyncResult ar = fh.BeginInvoke(strJsonSend, "http://47.104.90.170:9000/qdpxd/upload", 90000, callback, fh);
jarrTemps = new JArray();
sendObj = new JObject();
//return Json(new { status = 1, message = "提单号" + tu + "发送失败" }, JsonRequestBehavior.AllowGet);
//}
//else
//{
// context = new OpSeaePxDbContenxt();
// var t = item.ToString().Substring(1, item.Length - 2);
// OpSeaePx send = context.OpSeaePx.Select(p => p).Where(p => p.Gid.Equals(t)).ToList().FirstOrDefault();
// send.SendState = "发送失败";
// context.Entry(send).State = System.Data.Entity.EntityState.Modified;
// context.SaveChanges();
// return Json(new { status = 0, message = "提单号" + tu + "发送失败," + SendData["message"] });
//}
}
SendPXEmil(userid, liss);
//if (state > 0)
//{
// return Json(new { status = 1, message = "" });
//}
return Json(new { status = 1, message = "服务器错误,请稍后重试" }, JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
logger.ErrorFormat("GetSendData" + ex);
return Json(new { status = 0, message = ex.ToString() }, JsonRequestBehavior.AllowGet);
}
}
#region 发送拼箱申请单2022-4-21重写
//原逻辑好像支持多个,新逻辑按衣国豪要求,只能发送一个
[HttpPost]
public ActionResult SendPinXiangData(string idstr)
{
RespCommonData resp = new RespCommonData();
var userid = Session["USERID"].ToString();
var comname = Session["COMNAME"].ToString();
var username = Session["SHOWNAME"].ToString();
if (string.IsNullOrEmpty(userid))
{
resp.Success = false;
resp.Message = "登陆状态失效,请重新登陆进行操作!";
return Json(resp);
}
//判断公司钱包账户和单价设置
var balance = context.CustBalance.AsNoTracking().FirstOrDefault(b => b.COMNAME == comname);
var price = context.CustPrice.AsNoTracking().OrderByDescending(p => p.UPDATETIME).FirstOrDefault(p => p.COMNAME == comname && p.BSTYPE == 2 && p.SENDTYPE == 0);
if (price == null)
{
resp.Success = false;
resp.Message = "单价模板未配置,请联系管理员添加!";
return Json(resp);
}
decimal unitPrice = price.PRICE;
if (balance.Balance < unitPrice || balance == null)
{
resp.Success = false;
resp.Message = "余额不足!";
return Json(resp);
}
//拼箱申请单暂存参数
var pIsSave = context.SysParamSet.AsNoTracking().FirstOrDefault(p => p.PARAMNAME == "ISSTAGINGARE");
if (pIsSave == null)
{
resp.Success = false;
resp.Message = "请联系管理员设置拼箱申请单是否暂存参数!";
return Json(resp);
}
var isSave = pIsSave.PARAMVALUE == "0" ? false : true;
//拼箱申请单发送爬虫的url地址
var spiderUrl = context.SysParamSet.AsNoTracking().FirstOrDefault(p => p.PARAMNAME == "pPxSendSpiderUrl");
if (spiderUrl == null || string.IsNullOrEmpty(spiderUrl.PARAMVALUE))
{
resp.Success = false;
resp.Message = "拼箱申请单发送爬虫的url地址未正确配置";
return Json(resp);
}
//拼箱申请单发送爬虫的userkey和secret
var spiderSpiderUserId = context.SysParamSet.AsNoTracking().FirstOrDefault(p => p.PARAMNAME == "pPinXiangSpiderUserId");
var spiderSpiderUserSecret = context.SysParamSet.AsNoTracking().FirstOrDefault(p => p.PARAMNAME == "pPinXiangSpiderUserSecret");
if (spiderSpiderUserId == null
|| string.IsNullOrEmpty(spiderSpiderUserId.PARAMVALUE)
|| spiderSpiderUserSecret == null
|| string.IsNullOrEmpty(spiderSpiderUserSecret.PARAMVALUE))
{
resp.Success = false;
resp.Message = "拼箱申请单发送爬虫的user key和secret未正确配置";
return Json(resp);
}
var pxModel = context.OpSeaePx.AsNoTracking().Where(x => x.Gid == idstr).First();
var pxDetails = context.OpSeaeDetalis.AsNoTracking().Where(x => x.PXID == idstr).ToList();
if (pxDetails.Count == 0)
{
resp.Success = false;
resp.Message = "请录入商品明细!";
return Json(resp);
}
#region 构建发送的json
var jobjSend = new JObject();
jobjSend.Add("user_key", spiderSpiderUserId.PARAMVALUE);
jobjSend.Add("user_secret", spiderSpiderUserSecret.PARAMVALUE);
//操作方式
var cnInfo = context.ComNameInfo.AsNoTracking().FirstOrDefault(x => x.COMNAME == comname);
var cnInfoDS = context.ComNameInfo.AsNoTracking().FirstOrDefault(x => x.COMNAME == "青岛东胜伟业软件有限公司");
if (cnInfo == null || cnInfo.ISPXCOMPANY == 0)
{
jobjSend.Add("uid", cnInfoDS.PXCOMACCOUNT);//卡号
jobjSend.Add("psw", cnInfoDS.PXCOMPASSWORD);//卡密
}
else
{
jobjSend.Add("uid", cnInfo.PXCOMACCOUNT);//卡号
jobjSend.Add("psw", cnInfo.PXCOMPASSWORD);//卡密
}
jobjSend.Add("operate", isSave ? "0" : "1");//操作方式 0:暂存, 1:发送
jobjSend.Add("warehouse_name", pxModel.CangKuMingCheng);//仓库
jobjSend.Add("vessel", pxModel.ChuanMing);//船名
jobjSend.Add("voyage", pxModel.HangCi.ToUpper());//航次(字母大写)
jobjSend.Add("bno", pxModel.MBLNO);//单号
jobjSend.Add("pieces", pxModel.JianShu);//件数
jobjSend.Add("heavy", pxModel.MaoZhong);//重量
jobjSend.Add("foot", pxModel.TiJi);//尺码
var jarr = new JArray();
jobjSend.Add("infos", jarr);//明细数据
foreach (var detail in pxDetails)
{
var jobj = new JObject();
jobj.Add("hs_code", detail.ShangPinBianMa);
jobj.Add("product_name", detail.ShangPinMingCheng);
jobj.Add("declare_num", detail.ShenBaoShuLiang);
jarr.Add(jobj);
}
var strJson = JsonConvert.SerializeObject(jobjSend);
#endregion
var threadId = Guid.NewGuid().ToString();
resp.Success = true;
resp.Message = "";
resp.Data = threadId;
MemoryCache.Default.Add(new CacheItem(threadId, JsonConvert.SerializeObject(new RespCommon() { Success = true, Code = 100 })), new CacheItemPolicy() { AbsoluteExpiration = DateTime.Now.AddMinutes(3) });
Task.Run(() =>
{
logger.Debug($"发送拼箱申请单{spiderUrl.PARAMVALUE}\n{strJson}");
string postRtn = string.Empty;
var pinxiangModel = context.OpSeaePx.Where(x => x.Gid == idstr).First();
try
{
postRtn = WebRequestHelper.DoPost(spiderUrl.PARAMVALUE, strJson, timeout: 180000);
logger.Debug($"发送拼箱申请单返回:\n{postRtn}");
var rtnObj = JsonConvert.DeserializeAnonymousType(postRtn, new { code = 0, msg = "" });
if (rtnObj.code == 200)
{
pinxiangModel.ShenBaoZhuangTai = "发送成功";
pinxiangModel.SendTim = DateTime.Now;
OpSeaePxTips tips = new OpSeaePxTips();
tips.GID = Guid.NewGuid().ToString();
tips.PXID = pinxiangModel.Gid;
tips.PXSTATUS = pinxiangModel.ShenBaoZhuangTai;
tips.@operator = pinxiangModel.LuRuRen;
tips.optime = DateTime.Now;
tips.remark = rtnObj.msg;
context.OpSeaePxTips.Add(tips);
DSWeb.Common.DbContexts.Model.CustFee custFee = new DSWeb.Common.DbContexts.Model.CustFee();
custFee.GID = Guid.NewGuid().ToString().Replace("-", "");
custFee.BSNO = pinxiangModel.Gid;
custFee.MBLNO = pinxiangModel.MBLNO;
custFee.PRICE = unitPrice;
custFee.CREATETIME = DateTime.Now;
custFee.SENDTIME = DateTime.Now;
custFee.BSTYPE = 2;
custFee.BEIZHU = "";
custFee.SENDTYPE = 0;
custFee.VESSEL = pinxiangModel.ChuanMing;
custFee.VOYNO = pinxiangModel.HangCi;
custFee.SENDCOM = comname;
custFee.SENDUSER = username;
custFee.SENDUSERID = userid;
custFee.LURURENID = userid;
custFee.LURUREN = username;
custFee.CANGKU = pinxiangModel.CangKuMingCheng;
custFee.PKGS = (float)pinxiangModel.JianShu;
custFee.KGS = (float)pinxiangModel.MaoZhong;
custFee.COMNAME = comname;
custFee.COMID = context.Users.Where(x => x.GID == userid).Select(x => x.CompId).FirstOrDefault();
context.CustFee.Add(custFee);
var bal = context.CustBalance.FirstOrDefault(b => b.COMNAME == comname);
bal.Balance -= unitPrice;
#region 新加逻辑
var url = context.SysParamSet.AsNoTracking().FirstOrDefault(p => p.PARAMNAME == "pPxSendSpiderStatusUrl");
var jobjSend1 = new JObject();
jobjSend1.Add("user_key", spiderSpiderUserId.PARAMVALUE);
jobjSend1.Add("user_secret", spiderSpiderUserSecret.PARAMVALUE);
jobjSend1.Add("bno", pinxiangModel.MBLNO.ToString());
var strJson1 = JsonConvert.SerializeObject(jobjSend1);
var data = WebRequestHelper.DoPost(url.PARAMVALUE, strJson1, timeout: 180000);
JObject jobjRtn = JObject.Parse(data);
if (jobjRtn != null)
{
if (jobjRtn["code"].ToString() == "200")
{
logger.Debug(pinxiangModel.MBLNO.ToString() + "调取成功");
Dictionary<string, DateTime> dic1 = new Dictionary<string, DateTime>();
var depot_status = jobjRtn["msg"]["depot_status"].ToString();
var depot_time = jobjRtn["msg"]["depot_time"].ToString();
if (!string.IsNullOrEmpty(depot_time))
{
dic1.Add(depot_status, Convert.ToDateTime(depot_time));
}
var order_status = jobjRtn["msg"]["order_status"].ToString();
var order_time = jobjRtn["msg"]["order_time"].ToString();
if (!string.IsNullOrEmpty(order_time))
{
dic1.Add(order_status, Convert.ToDateTime(order_time));
}
var release_status = jobjRtn["msg"]["release_status"].ToString();
var release_time = jobjRtn["msg"]["release_time"].ToString();
if (!string.IsNullOrEmpty(release_time))
{
dic1.Add(release_status, Convert.ToDateTime(release_time));
}
var shipto_status = jobjRtn["msg"]["shipto_status"].ToString();
var shipto_time = jobjRtn["msg"]["shipto_time"].ToString();
if (!string.IsNullOrEmpty(shipto_time))
{
dic1.Add(shipto_status, Convert.ToDateTime(shipto_time));
}
var sluice_status = jobjRtn["msg"]["sluice_status"].ToString();
var sluice_time = jobjRtn["msg"]["sluice_time"].ToString();
if (!string.IsNullOrEmpty(sluice_time))
{
dic1.Add(sluice_status, Convert.ToDateTime(sluice_time));
}
var oplist = context.OpSeaePxTips.Where(p => p.PXID == pinxiangModel.Gid).ToList();
var dic = dic1.OrderBy(x => x.Value).ToList();
foreach (var itc in dic)
{
if (oplist.Where(x => x.PXSTATUS == itc.Key).ToList().Count == 0)
{
OpSeaePxTips tips1 = new OpSeaePxTips();
tips1.GID = Guid.NewGuid().ToString();
tips1.PXID = pinxiangModel.Gid;
tips1.PXSTATUS = itc.Key;
tips1.@operator = pinxiangModel.LuRuRen;
tips1.optime = DateTime.Now;
tips1.remark = itc.Key;
context.OpSeaePxTips.Add(tips1);
pinxiangModel.ReceiptState = itc.Key;
pinxiangModel.ReceiptTim = itc.Value;
}
}
context.Entry(pinxiangModel).State = System.Data.Entity.EntityState.Modified;
}
}
#endregion
}
else
{
pinxiangModel.ShenBaoZhuangTai = "发送失败";
OpSeaePxTips tips = new OpSeaePxTips();
tips.GID = Guid.NewGuid().ToString();
tips.PXID = pinxiangModel.Gid;
tips.PXSTATUS = "发送失败";
tips.@operator = pinxiangModel.LuRuRen;
tips.optime = DateTime.Now;
tips.remark = rtnObj.msg;
context.OpSeaePxTips.Add(tips);
}
if (MemoryCache.Default.Contains(threadId))
{
var result = JsonConvert.DeserializeObject<RespCommon>(MemoryCache.Default[threadId].ToString());
if (rtnObj.code == 200)
{
result.Code = 0;
result.Message = "发送成功";
}
else
{
result.Code = 10;
result.Message = rtnObj.msg;
}
MemoryCache.Default[threadId] = JsonConvert.SerializeObject(result);
}
}
catch (Exception ex)
{
logger.Error(ex);
pinxiangModel.ShenBaoZhuangTai = "发送失败";
OpSeaePxTips tips = new OpSeaePxTips();
tips.GID = Guid.NewGuid().ToString();
tips.PXID = pinxiangModel.Gid;
tips.PXSTATUS = "发送失败";
tips.@operator = pinxiangModel.LuRuRen;
tips.optime = DateTime.Now;
tips.remark = ex.Message;
context.OpSeaePxTips.Add(tips);
if (MemoryCache.Default.Contains(threadId))
{
var result = JsonConvert.DeserializeObject<RespCommon>(MemoryCache.Default[threadId].ToString());
resp.Code = 500;
resp.Message = ex.Message;
MemoryCache.Default[threadId] = JsonConvert.SerializeObject(result);
}
}
context.SaveChanges();
});
return Json(resp);
}
public static bool IsDateTime(string StrSource)
{
return System.Text.RegularExpressions.Regex.IsMatch(StrSource, @"^(((((1[6-9]|[2-9]\d)\d{2})-(0?[13578]|1[02])-(0?[1-9]|[12]\d|3[01]))|(((1[6-9]|[2-9]\d)\d{2})-(0?[13456789]|1[012])-(0?[1-9]|[12]\d|30))|(((1[6-9]|[2-9]\d)\d{2})-0?2-(0?[1-9]|1\d|2[0-8]))|(((1[6-9]|[2-9]\d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00))-0?2-29-)) (20|21|22|23|[0-1]?\d):[0-5]?\d:[0-5]?\d)$ ");
}
//异步获取发送结果
[HttpGet]
public ActionResult GetThreadResult(string threadId)
{
RespCommon resp = new RespCommon();
if (MemoryCache.Default.Contains(threadId))
{
resp = JsonConvert.DeserializeObject<RespCommon>(MemoryCache.Default[threadId].ToString());
}
else
{
resp.Success = false;
resp.Code = -1;
}
return Json(resp, JsonRequestBehavior.AllowGet);
}
#endregion
public ActionResult GetSendState()
{
//var url = "http://47.104.90.170:9000/qdpxd/status";
JObject sendobj = new JObject();
return Content("");
}
/// <summary>
/// 查看余额
/// </summary>
/// <param name="com"></param>
/// <param name="Gid"></param>
/// <returns></returns>
public bool Debit(string com, int sum)
{
var msg = true;
var money = context.CustBalance.Where(b => b.COMNAME == com).FirstOrDefault();
var price = context.CustPrice.Where(p => p.COMNAME == com && p.BSTYPE == 2).OrderByDescending(p => p.UPDATETIME).ToList();
if (money.Balance < (price[0].PRICE * sum) || money == null)
{
msg = false;
}
if (price == null)
{
msg = false;
}
return msg;
}
[HttpGet]
public JsonResult DropPx(string str)
{
try
{
var idstr = str.Substring(0, str.Length - 1);
var idArr = idstr.Split(',');
foreach (var item in idArr)
{
var lisTips = context.OpSeaePxTips.Where(p => p.PXID == item).ToList();
foreach (var me in lisTips)
{
context.Entry(me).State = System.Data.Entity.EntityState.Deleted;
}
OpSeaePx op = new OpSeaePx() { Gid = item };
context.Entry(op).State = System.Data.Entity.EntityState.Deleted;
var lis = context.OpSeaeDetalis.Select(p => new { p.GID, p.PXID }).Where(p => p.PXID == item).ToList().Select(p => new OpSeaeDetalis { GID = p.GID });
foreach (var ix in lis)
{
OpSeaeDetalis det = new OpSeaeDetalis { GID = ix.GID };
context.Entry(det).State = System.Data.Entity.EntityState.Deleted;
}
}
int state = context.SaveChanges();
return Json(state, JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
logger.ErrorFormat("DropPx" + ex);
return Json(0, JsonRequestBehavior.AllowGet);
}
}
[HttpPost]
public ActionResult Import()
{
try
{
string userid = Convert.ToString(Session["USERID"]);
if (userid == "" || userid == null)
{
var jsonRespose2 = new JsonResponse { Success = false, Message = "登陆状态失效,请重新登陆进行操作!" };
return new ContentResult() { Content = Helper.JsonConvert.Serialize(jsonRespose2) };
}
System.Web.HttpFileCollection _file = System.Web.HttpContext.Current.Request.Files;
var code = 0;
if (_file.Count > 0)
{
long size = _file[0].ContentLength;
string type = _file[0].ContentType;
string name = _file[0].FileName;
string _tp = Path.GetExtension(name);
Stream stream = _file[0].InputStream;
string savaName = DateTime.Now.ToString("yyyyMMddHHssmm") + _tp; //保存文件
string filepath = "../../Areas/MvcShipping/Contens/" + savaName;
string path = Server.MapPath(filepath);
if (!Directory.Exists(Server.MapPath("../../Areas/MvcShipping/Contens")))
{
Directory.CreateDirectory(Server.MapPath("../../Areas/MvcShipping/Contens/"));
}
_file[0].SaveAs(path);
string dirpath = Server.MapPath("../../Areas/MvcShipping/Contens/");
code = ReadFileToLis(path, savaName, dirpath);
}
if (code > 0)
{
return Content("模板导入成功");
}
if (code == -1)
{
return Content("提单号已存在,请检查!");
}
return Content("模板导入失败");
}
catch (Exception ex)
{
logger.ErrorFormat("Import" + ex);
return Content("模板导入失败," + ex + "");
}
}
[HttpPost]
public ActionResult EditDet(OpSeaePx seae, string Gids)
{
try
{
string userid = Convert.ToString(Session["USERID"]);
if (userid == "" || userid == null)
{
var jsonRespose2 = new JsonResponse { Success = false, Message = "登陆状态失效,请重新登陆进行操作!" };
return new ContentResult() { Content = Helper.JsonConvert.Serialize(jsonRespose2) };
}
var state = 0;
if (!string.IsNullOrEmpty(Gids))
{
var oldData = context.OpSeaePx.Where(p => p.Gid == seae.Gid).First();
if (string.IsNullOrEmpty(seae.CangKuMingCheng))
{
seae.CangKuMingCheng = oldData.CangKuMingCheng;
}
if (string.IsNullOrEmpty(seae.Corpid))
{
seae.Corpid = oldData.Corpid;
}
if (string.IsNullOrEmpty(seae.GuanQuDaiMa))
{
seae.GuanQuDaiMa = oldData.GuanQuDaiMa;
}
if (string.IsNullOrEmpty(seae.LuRuRenId))
{
seae.LuRuRenId = oldData.LuRuRenId;
}
if (string.IsNullOrEmpty(seae.ShenBaoZhuangTai))
{
seae.ShenBaoZhuangTai = oldData.ShenBaoZhuangTai;
}
if (string.IsNullOrEmpty(seae.PXCOMNAME))
{
seae.PXCOMNAME = oldData.PXCOMNAME;
}
seae.LuRuRen = oldData.LuRuRen;
seae.LuRuRenId = oldData.LuRuRenId;
seae.Corpid = oldData.Corpid;
seae.LuRuRiQi = oldData.LuRuRiQi;
context = new OpSeaePxDbContenxt();
context.Entry(seae).State = System.Data.Entity.EntityState.Modified;
state = context.SaveChanges();
}
else
{
var c = context.OpSeaePx.Where(p => p.MBLNO == seae.MBLNO).Count();
if (c > 0)
{
var cdc = new CommonDataContext();
var inputuser = cdc.Users.Where(x => x.GID == seae.LuRuRenId).ToList();
//return Content("平台中已存在提单号" + seae.MBLNO + ",请检查");
return Content("提单号" + seae.MBLNO + "已存在,录入公司:" + inputuser[0].COMNAME + ",录入人:" + seae.LuRuRen + ".");
}
context = new OpSeaePxDbContenxt();
seae.Gid = seae.Gid;
seae.GuanQuDaiMa = "黄岛海关";
if (string.IsNullOrEmpty(seae.ShenBaoZhuangTai))
{
seae.ShenBaoZhuangTai = "已录入";
}
seae.YeWuLeiXing = "出口拼箱";
seae.LuRuRen = Convert.ToString(Session["SHOWNAME"]);
seae.LuRuRenId = Convert.ToString(Session["USERID"]);
seae.LuRuRiQi = DateTime.Now;
seae.Corpid = Convert.ToString(Session["COMPANYID"]);
seae.TiJi = Math.Round(seae.TiJi, 4);
seae.MaoZhong = Math.Round(seae.MaoZhong, 4);
context = new OpSeaePxDbContenxt();
OpSeaePxTips tips = new OpSeaePxTips();
tips.GID = getGUID();
tips.PXID = seae.Gid;
tips.PXSTATUS = seae.ShenBaoZhuangTai;
tips.@operator = seae.LuRuRen;
tips.optime = DateTime.Now;
tips.remark = "创建业务";
context.OpSeaePxTips.Add(tips);
context.OpSeaePx.Add(seae);
state = context.SaveChanges();
}
if (state > 0)
{
return Content("操作成功");
}
else
{
return Content("操作失败");
}
}
catch (DbEntityValidationException ex)
{
logger.ErrorFormat("EditDet" + ex);
return Content("操作失败");
}
}
public ActionResult EditBook(string Gid, string MBLNO = null, string PXCOMNAME = null, string CangKuMingCheng = null, string ChuanMing = null, string HangCi = null, string JianShu = null, string MaoZhong = null, string TiJi = null, string BeiZhu = null)
{
string userid = Convert.ToString(Session["USERID"]);
if (userid == "" || userid == null)
{
var jsonRespose2 = new JsonResponse { Success = false, Message = "登陆状态失效,请重新登陆进行操作!" };
return new ContentResult() { Content = Helper.JsonConvert.Serialize(jsonRespose2) };
}
ViewData["ShipName"] = BasicDataRefDAL.GetVesselList("");
var pxCom = context.ComNameInfo.Select(p => p).Where(p => p.ISPXCOMPANY != 0).ToList();
ViewData["pxCom"] = pxCom.Select(p => p.COMNAME).ToList();
var lrr = context.Users.Select(p => p.SHOWNAME).ToList();
ViewData["lrr"] = lrr;
ViewData["ckm"] = new List<string> { "中创", "外运", "大亚", "捷运", "万嘉", "邦达", "五洲" };
if (Gid == "" || Gid == null)
{
ViewData["Gid"] = getGUID();
ViewData["MBLNO"] = "";
ViewData["PXCOMNAME"] = PXCOMNAME == null || PXCOMNAME == "null" ? "" : PXCOMNAME;
ViewData["CangKuMingCheng"] = CangKuMingCheng == null || CangKuMingCheng == "null" ? "" : CangKuMingCheng == "" ? "" : CangKuMingCheng;
ViewData["ChuanMing"] = ChuanMing == null || ChuanMing == "null" ? "" : ChuanMing;
ViewData["HangCi"] = HangCi == null || HangCi == "null" ? "" : HangCi;
ViewData["JianShu"] = JianShu == null || JianShu == "null" ? "" : JianShu;
ViewData["MaoZhong"] = MaoZhong == null || MaoZhong == "null" ? "" : MaoZhong;
ViewData["TiJi"] = TiJi == null || TiJi == "null" ? "" : TiJi;
ViewData["LuRuRen"] = Convert.ToString(Session["SHOWNAME"]);
ViewData["LuRuRiQi"] = DateTime.Now;
ViewData["BeiZhu"] = BeiZhu == null || BeiZhu == "null" ? "" : BeiZhu;
ViewData["ShenBaoZhuangTai"] = "已录入";
ViewData["opseaedeli"] = new List<DSWeb.Common.DbContexts.Model.OpSeaeDetalis>();
}
else
{
ViewData["Gid"] = Gid;
var lis = context.OpSeaePx.Where(p => p.Gid == Gid).FirstOrDefault();
ViewData["MBLNO"] = lis.MBLNO;
ViewData["CangKuMingCheng"] = lis.CangKuMingCheng == null ? "" : lis.CangKuMingCheng;
ViewData["ChuanMing"] = lis.ChuanMing;
ViewData["HangCi"] = lis.HangCi;
ViewData["JianShu"] = lis.JianShu;
ViewData["MaoZhong"] = lis.MaoZhong;
ViewData["TiJi"] = lis.TiJi;
ViewData["LuRuRen"] = lis.LuRuRen;
ViewData["LuRuRiQi"] = lis.LuRuRiQi;
ViewData["BeiZhu"] = lis.BeiZhu;
ViewData["ShenBaoZhuangTai"] = lis.ShenBaoZhuangTai;
ViewData["PXCOMNAME"] = lis.PXCOMNAME == null ? "" : lis.PXCOMNAME;
ViewData["opseaedeli"] = context.OpSeaeDetalis.Where(p => p.PXID == Gid).OrderBy(p => p.XuHao).ToList();
}
return View();
}
[HttpGet]
public int DropBook(string IdStr)
{
try
{
string id = IdStr.Substring(0, IdStr.Length - 1);
var idarr = id.Split(',');
foreach (var ix in idarr)
{
OpSeaeDetalis det = new OpSeaeDetalis { GID = ix };
context.Entry(det).State = System.Data.Entity.EntityState.Deleted;
}
return context.SaveChanges();
}
catch (Exception ex)
{
logger.ErrorFormat("DropBook" + ex);
return 0;
}
}
[HttpPost]
public ActionResult AddOrEditCell(string PxId, string Gid, string Code, string Name, string Counts, string Unit)
{
try
{
var state = 0;
if (string.IsNullOrEmpty(Gid))
{
OpSeaeDetalis deta = new OpSeaeDetalis();
deta.PXID = PxId;
deta.ShangPinBianMa = Code;
deta.ShangPinMingCheng = Name;
deta.ShenBaoShuLiang = Convert.ToDecimal(Counts);
deta.GID = getGUID();
deta.FaDingDanWei = Unit;
deta.XuHao = context.OpSeaeDetalis.Where(p => p.PXID == PxId).Count() + 1;
context = new OpSeaePxDbContenxt();
context.OpSeaeDetalis.Add(deta);
state = context.SaveChanges();
}
else
{
OpSeaeDetalis deta = new OpSeaeDetalis();
deta.PXID = PxId;
deta.GID = Gid;
deta.ShangPinBianMa = Code;
deta.ShangPinMingCheng = Name;
deta.ShenBaoShuLiang = Convert.ToDecimal(Counts);
deta.FaDingDanWei = Unit;
deta.XuHao = context.OpSeaeDetalis.Where(p => p.PXID == PxId).Count() + 1;
context = new OpSeaePxDbContenxt();
context.Entry(deta).State = System.Data.Entity.EntityState.Modified;
state = context.SaveChanges();
}
if (state > 0)
{
return Content("操作成功");
}
else
{
return Content("操作失败");
}
}
catch (Exception ex)
{
logger.ErrorFormat("AddOrEditCell" + ex);
return Content("操作失败," + ex);
}
}
public string DoPost(string json, string url, int timeout = 90000)
{
string responseString = "";//post返回的结果
ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, err) => { return true; };
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url);
req.Method = "POST";
if (!string.IsNullOrWhiteSpace(json))
{
byte[] postBytes = Encoding.UTF8.GetBytes(json);
req.ContentType = "application/json; charset=utf-8";
req.ContentLength = Encoding.UTF8.GetByteCount(json);
Stream stream = req.GetRequestStream();
stream.Write(postBytes, 0, postBytes.Length);
req.Timeout = 90000;
stream.Close();
}
else
{
req.ContentLength = 0;
}
var response = req.GetResponse();
Stream streamResponse = response.GetResponseStream();
StreamReader streamRead = new StreamReader(streamResponse);
responseString = streamRead.ReadToEnd();
response.Close();
streamRead.Close();
return responseString;
}
private int ReadFileToLis(string path, string Name, string dirpath)
{
List<OpSeaeDetalis> enlist = new List<OpSeaeDetalis>(); // 转换后的集合
OpSeaePx seaepx = new OpSeaePx();
try
{
using (FileStream fs = System.IO.File.OpenRead(path))
{
string fileEX = Path.GetExtension(path).ToLower();
NPOI.SS.UserModel.IWorkbook workbook;
if (fileEX == ".xlsx")
{
workbook = new NPOI.XSSF.UserModel.XSSFWorkbook(fs);
}
else if (fileEX == ".xls")
{
workbook = new NPOI.HSSF.UserModel.HSSFWorkbook(fs);
}
else
{
return 0;
}
NPOI.SS.UserModel.ISheet sheet = (NPOI.SS.UserModel.ISheet)workbook.GetSheetAt(0);
var t = 1;
for (int i = 1; i < sheet.LastRowNum; i++)
{
if (sheet.GetRow(i) == null)
{
break;
}
var a = sheet.GetRow(i);
if (a.Cells[0].ToString() == "拼箱库名称")
{
if (string.IsNullOrEmpty(a.Cells[1].ToString()))
{
return 0;
}
seaepx.Gid = getGUID();
seaepx.CangKuMingCheng = a.Cells[1].ToString();
seaepx.ChuanMing = a.Cells[3].ToString();
seaepx.HangCi = a.Cells[5].ToString();
seaepx.MBLNO = a.Cells[7].ToString();
seaepx.GuanQuDaiMa = "黄岛海关";
seaepx.YeWuLeiXing = "出口拼箱";
seaepx.LuRuRiQi = DateTime.Now;
seaepx.LuRuRen = Convert.ToString(Session["SHOWNAME"]);
seaepx.LuRuRenId = Convert.ToString(Session["USERID"]);
seaepx.Corpid = Convert.ToString(Session["COMPANYID"]);
//seaepx.LuRuRen = "衣国豪";
//seaepx.LuRuRenId = "d85fd590-d9f6-4410-93a1-f6fac77b606e";
//seaepx.Corpid = "Comcab2d43f60454327af30a131fc1d3abd";
}
else if (a.Cells[0].ToString() == "仓库联系人")
{
}
else if (a.Cells[0].ToString() == "本票合计总数")
{
seaepx.JianShu = Convert.ToDecimal(a.Cells[2].ToString());
seaepx.MaoZhong = Convert.ToDecimal(a.Cells[5].ToString());
seaepx.TiJi = Convert.ToDecimal(a.Cells[8].ToString());
seaepx.ShenBaoZhuangTai = "已录入";
seaepx.BeiZhu = "";
break;
}
else
{
if (string.IsNullOrEmpty(a.Cells[1].ToString()))
{
continue;
}
OpSeaeDetalis detalis = new OpSeaeDetalis();
detalis.XuHao = t;
detalis.GID = getGUID();
detalis.PXID = seaepx.Gid;
detalis.ShangPinBianMa = a.Cells[1].ToString();
detalis.ShangPinMingCheng = a.Cells[3].ToString();
detalis.ShenBaoShuLiang = Convert.ToDecimal(a.Cells[5].ToString());
var u = context.SeaePxHscode.Where(p => p.HSCODE == detalis.ShangPinBianMa).FirstOrDefault();
detalis.FaDingDanWei = u.UNIT;
detalis.PeiZaiShuLiang = 0;
detalis.RuKuShuLiang = 0;
t = t + 1;
enlist.Add(detalis);
}
}
}
int state = 0;
if (seaepx != null && enlist != null)
{
state = ImportDb(seaepx, enlist);
}
return state;
}
catch (Exception ex)
{
logger.ErrorFormat("ReadFileToLis" + ex);
return 0;
}
finally
{
DropFile(dirpath);
};
}
private int ImportDb(OpSeaePx seaepx, List<OpSeaeDetalis> enlist)
{
try
{
if (context.OpSeaePx.Where(p => p.MBLNO == seaepx.MBLNO).Count() > 0)
{
return -1;
}
OpSeaePxTips tips = new OpSeaePxTips();
tips.GID = getGUID();
tips.PXID = seaepx.Gid;
tips.PXSTATUS = seaepx.ShenBaoZhuangTai;
tips.@operator = seaepx.LuRuRen;
tips.optime = DateTime.Now;
tips.remark = "创建业务";
context.OpSeaePxTips.Add(tips);
context.OpSeaePx.Add(seaepx);
foreach (var item in enlist)
{
context.OpSeaeDetalis.Add(item);
}
var code = context.SaveChanges();
return code;
}
catch (DbEntityValidationException ex)
{
logger.ErrorFormat("ImportDb" + ex);
return 0;
}
}
private void DropFile(string path)
{
try
{
DirectoryInfo dir = new DirectoryInfo(path);
FileSystemInfo[] fileinfo = dir.GetFileSystemInfos(); //返回目录中所有文件和子目录
foreach (FileSystemInfo i in fileinfo)
{
if (i is DirectoryInfo) //判断是否文件夹
{
DirectoryInfo subdir = new DirectoryInfo(i.FullName);
subdir.Delete(true);
}
else
{
System.IO.File.Delete(i.FullName);
}
}
}
catch (Exception e)
{
logger.ErrorFormat("DropFile" + e);
}
}
[HttpGet]
public ActionResult GetCodeMessage(string code)
{
try
{
var lis = context.SeaePxHscode.Select(p => p).Where(p => p.HSCODE == code).FirstOrDefault();
if (lis == null)
{
lis = context.SeaePxHscode.Select(p => p).Where(p => p.HSCODE.Contains(code)).FirstOrDefault();
lis.NAME = "";
}
return Json(new { state = 1, name = lis.NAME, unit = lis.UNIT }, JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
return Json(new { state = 0, name = "error", unit = ex.Message }, JsonRequestBehavior.AllowGet);
}
}
[HttpGet]
public ActionResult GetLog(string idstr)
{
try
{
var lis = context.OpSeaePxTips.Where(p => p.PXID == idstr).OrderByDescending(p => p.optime).ToList();
return Json(new { data = lis, state = 1 }, JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
return Json(new { data = ex.ToString(), state = 1 }, JsonRequestBehavior.AllowGet);
}
}
private string getGUID()
{
System.Guid guid = new Guid();
guid = Guid.NewGuid();
string str = guid.ToString();
return str;
}
public static string GetRangDAStr(string tb, string userid, string username, string companyid, int type = 0)
{
string str = "";
var strSql = new StringBuilder();
strSql.Append("SELECT ");
strSql.Append(" VISIBLERANGE,OPERATERANGE ");
strSql.Append(" from VW_User_Authority ");
strSql.Append(" where [NAME]='modPXList' and USERID='" + userid + "' and ISDELETE=0");
string visiblerange = "4";
string operaterange = "4";
Microsoft.Practices.EnterpriseLibrary.Data.Database db = DatabaseFactory.CreateDatabase();
using (IDataReader reader = db.ExecuteReader(CommandType.Text, strSql.ToString()))
{
while (reader.Read())
{
visiblerange = Convert.ToString(reader["VISIBLERANGE"]);
operaterange = Convert.ToString(reader["OPERATERANGE"]);
break;
}
reader.Close();
}
if (visiblerange == "4")
{
str = "1=2";
}
else if (visiblerange == "3")
{
str = " (lururenid ='" + userid + "')";
}
else if (visiblerange == "2")
{
if (tb == "index")
{
var rangeDa = new RangeDA();
var deptname = rangeDa.GetDEPTNAME(userid);
var userstr = new StringBuilder();
userstr.Append(" select SHOWNAME from [user] where GID in (select USERID from user_company where COMPANYID='" + companyid + "') and GID in (select userid from user_baseinfo where DEPTNAME='" + deptname + "')");
Microsoft.Practices.EnterpriseLibrary.Data.Database userdb = DatabaseFactory.CreateDatabase();
using (IDataReader reader = userdb.ExecuteReader(CommandType.Text, userstr.ToString()))
{
str = "";
while (reader.Read())
{
if (str == "")
{
str = " (INPUTBY='" + Convert.ToString(reader["SHOWNAME"]) + "'";
}
else
{
str = str + " or INPUTBY='" + Convert.ToString(reader["SHOWNAME"]) + "'";
};
}
str = str + ")";
reader.Close();
}
}
else
{
str = " UPPER(Corpid)='" + companyid + "'";
}
}
else if (visiblerange == "1")
{
str = " gid in (select gid from op_seae_px where lururenid in (select userid from [user_company] where companyid = '" + companyid + "'))";
//str = " UPPER(Corpid)='" + companyid + "'";
}
else if (visiblerange == "7")
{
str = " gid in (select gid from op_seae_px where lururenid in (select gid from [user] where COMNAME = (select COMNAME from [user] where GID='" + userid + "')))";
}
return str;
}
public static bool SendPXEmil(string userid, List<PxAndDelat> headList, int optype = 0)
{
try
{
string showname = "";
string comname = "";
string email = "";
string tel = "";
string sql = @"select u.SHOWNAME,u.COMNAME,ub.EMAIL1,ub.MOBILE from [User] u
left join user_baseinfo ub on u.GID = ub.USERID
where u.GID= '" + userid + "'";
Microsoft.Practices.EnterpriseLibrary.Data.Database db = DatabaseFactory.CreateDatabase();
using (IDataReader reader = db.ExecuteReader(CommandType.Text, sql))
{
while (reader.Read())
{
showname = reader[0].ToString();
comname = reader[1].ToString();
email = reader[2].ToString();
tel = reader[3].ToString();
}
}
string strtype = "";
if (optype == 0)
{
strtype = "新增";
}
else if (optype == 1)
{
strtype = "修改";
}
else if (optype == 2)
{
strtype = "删除";
}
else
{
strtype = "-";
}
var mailtopic = "拼箱申请单发送-" + comname;
string mailbodyP1 = "";
string ids = "";
foreach (var item in headList)
{
ids += "'" + item.GID + "',";
mailbodyP1 += "提单号:" + item.MBLNO + "\r\n" + "发送类型:" + strtype + "\r\n" + "仓库:" + item.CangKuMingCheng + "\r\n";
}
var mailbody = "公司名称:" + comname + "\r\n" + "申请人:" + showname + "\r\n" + "邮箱:" + email
+ "\r\n" + "电话:" + tel + "\r\n" + mailbodyP1;
//string toNames = "frank,lee";
SendEmail se = new SendEmail("dongshengsoft@dongshengsoft.com", "dongshengcangdan@h8j.top", "", "", mailtopic, mailbody, false);
// SendEmail se = new SendEmail("dev001@dongshengsoft.com", "admin@dongshengsoft.com", "", "", mailtopic, mailbody, false);
//string filePath = path;
//se.Attachments(filePath);
se.SetSmtp("dongshengcangdan@h8j.top", "A1B2C3ds040201", "smtpdm.aliyun.com", 80, false, System.Net.Mail.MailPriority.Normal); //必须在所有参数设置完后调用此方法
return true;
}
catch (Exception ex)
{
return false;
throw;
}
}
#endregion
}
public class ShipAndStore
{
public string ShipName { get; set; }
public string StoreName { get; set; }
}
public class PxTableClass
{
public string GID { get; set; }
public string ShenBaoZhuangTai { get; set; }
public string MBLNO { get; set; }
public string CangKuMingCheng { get; set; }
public string ChuanMing { get; set; }
public string HangCi { get; set; }
public decimal JianShu { get; set; }
public decimal MaoZhong { get; set; }
public decimal TiJi { get; set; }
public string LuRuRen { get; set; }
public string LuRuRenId { get; set; }
public DateTime? LuRuRiQi { get; set; }
public DateTime? Dao { get; set; }
public string COMNAME { get; set; }
public string PXCOMNAME { get; set; }
public string BeiZhu { get; set; }
public string ShangPinBianMa { get; set; }
}
public static class GetRecript
{
public static void UpdSendState()
{
OpSeaePxDbContenxt context = new OpSeaePxDbContenxt();
var yytoday = Convert.ToDateTime(DateTime.Now.AddDays(-2));
var lis = context.OpSeaePx.Where(p => p.ShenBaoZhuangTai == "发送成功" && p.ReceiptState != "已审批通过" && p.SendTim > yytoday).ToList();
var url = "http://47.104.90.170:9000/qdpxd/status";
foreach (var item in lis)
{
var data = DoPosts(item.MBLNO.ToString(), url);
var sendData = (JObject)JsonConvert.DeserializeObject(data);
if (sendData != null)
{
if (Convert.ToInt32(sendData["status"]) > 0)
{
if (item.ReceiptState != sendData["message"]["order_status"].ToString())
{
OpSeaePxTips tips = new OpSeaePxTips();
tips.GID = getGUID();
tips.PXID = item.Gid;
tips.PXSTATUS = sendData["message"]["order_status"].ToString();
tips.@operator = item.LuRuRen;
tips.optime = DateTime.Now;
if (sendData["message"]["order_status"].ToString() == "已保存")
{
tips.remark = "拼箱系统已接收";
}
if (sendData["message"]["order_status"].ToString() == "已暂存")
{
tips.remark = "业务已暂存";
}
if (sendData["message"]["order_status"].ToString() == "已审批通过")
{
tips.remark = "仓库已审核";
}
context.OpSeaePxTips.Add(tips);
}
item.ReceiptState = sendData["message"]["order_status"].ToString();
var s = IsDateTime(Convert.ToString(sendData["message"]["order_date"].ToString()));
if (s)
{
item.ReceiptTim = Convert.ToDateTime(sendData["message"]["order_date"].ToString());
}
else
{
item.ReceiptTim = Convert.ToDateTime(DateTime.Now.ToString());
}
context.Entry(item).State = System.Data.Entity.EntityState.Modified;
}
}
}
context.SaveChanges();
}
public static bool IsDateTime(string StrSource)
{
return System.Text.RegularExpressions.Regex.IsMatch(StrSource, @"^(((((1[6-9]|[2-9]\d)\d{2})-(0?[13578]|1[02])-(0?[1-9]|[12]\d|3[01]))|(((1[6-9]|[2-9]\d)\d{2})-(0?[13456789]|1[012])-(0?[1-9]|[12]\d|30))|(((1[6-9]|[2-9]\d)\d{2})-0?2-(0?[1-9]|1\d|2[0-8]))|(((1[6-9]|[2-9]\d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00))-0?2-29-)) (20|21|22|23|[0-1]?\d):[0-5]?\d:[0-5]?\d)$ ");
}
private static string getGUID()
{
System.Guid guid = new Guid();
guid = Guid.NewGuid();
string str = guid.ToString();
return str;
}
public static string DoPost(string json, string url, int timeout = 90000)
{
string responseString = "";//post返回的结果
ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, err) => { return true; };
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url);
req.Method = "POST";
if (!string.IsNullOrWhiteSpace(json))
{
byte[] postBytes = Encoding.UTF8.GetBytes(json);
req.ContentType = "application/json; charset=utf-8";
req.ContentLength = Encoding.UTF8.GetByteCount(json);
Stream stream = req.GetRequestStream();
stream.Write(postBytes, 0, postBytes.Length);
req.Timeout = 90000;
stream.Close();
}
else
{
req.ContentLength = 0;
}
var response = req.GetResponse();
Stream streamResponse = response.GetResponseStream();
StreamReader streamRead = new StreamReader(streamResponse);
responseString = streamRead.ReadToEnd();
response.Close();
streamRead.Close();
return responseString;
}
private static string DoPosts(string json, string url, int timeout = 90000)
{
string responseString = "";//post返回的结果
ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, err) => { return true; };
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url);
req.Method = "POST";
if (!string.IsNullOrWhiteSpace(json))
{
byte[] postBytes = Encoding.UTF8.GetBytes(json);
req.ContentType = "application/x-www-form-urlencoded";
string ss = System.Web.HttpUtility.UrlEncode("mblno") + "=" + System.Web.HttpUtility.UrlEncode(json);
byte[] postData = Encoding.UTF8.GetBytes(ss);
req.ContentLength = postData.Length;
Stream stream = req.GetRequestStream();
stream.Write(postData, 0, postData.Length);
req.Timeout = 90000;
stream.Close();
}
else
{
req.ContentLength = 0;
}
var response = req.GetResponse();
Stream streamResponse = response.GetResponseStream();
StreamReader streamRead = new StreamReader(streamResponse);
responseString = streamRead.ReadToEnd();
response.Close();
streamRead.Close();
return responseString;
}
}
}