autocopy.aspx.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364
  1. using BizCom;
  2. using ICSharpCode.SharpZipLib.Zip;
  3. using SQLData;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.Configuration;
  7. using System.Data;
  8. using System.Data.SqlClient;
  9. using System.IO;
  10. using System.Text;
  11. using System.Web;
  12. using System.Web.UI;
  13. using System.Web.UI.WebControls;
  14. public partial class autocopy : System.Web.UI.Page
  15. {
  16. public static string upPath = ConfigurationManager.AppSettings["upPath"];
  17. public static string copyPath = ConfigurationManager.AppSettings["copyPath"];
  18. private void conErc(string msg)
  19. {
  20. Response.Write("{\"type\":\"error\",\"result\":\"" + msg + "\"}");
  21. //Response.End();
  22. }
  23. private void conSuc(string msg)
  24. {
  25. Response.Write("{\"type\":\"success\",\"result\":\"" + msg + "\"}");
  26. //Response.End();
  27. }
  28. protected void Page_Load(object sender, EventArgs e)
  29. {
  30. if (Request["hexdata"] != null)
  31. {
  32. string tids = Request["hexdata"];
  33. if (tids.Trim() == "")
  34. {
  35. conErc("无法下载");
  36. return;
  37. }
  38. int userId = 0;
  39. if (Request["userid"] != null)
  40. {
  41. userId = Convert.ToInt32(Request["userid"]);
  42. }
  43. try
  44. {
  45. string[] tArr = tids.Split(',');
  46. if (tArr.Length != 2)
  47. {
  48. conErc("订单ID不对,无法下载");
  49. return;
  50. }
  51. string oldctid = tArr[0].ToString();
  52. string newctid = tArr[1].ToString();
  53. StringBuilder sql = new StringBuilder();
  54. sql.AppendFormat("select ctid,tid,seller_memo,FinishDesignTime,OrderState,SupplierId,SupplierName from view_erptradecell where ctid='{0}'", oldctid);
  55. DataTable dt = CeErpTradeCell.ExecuteDataset(sql.ToString()).Tables[0];
  56. if (dt == null || dt.Rows.Count < 1)
  57. {
  58. conErc("没有找到相关订单" + oldctid);
  59. return;
  60. }
  61. StringBuilder sqlnew = new StringBuilder();
  62. sqlnew.AppendFormat("select ctid,tid,seller_memo,FinishDesignTime,OrderState,SupplierId,SupplierName,orderSn from view_erptradecell where (orderstate=3 or orderstate=4) and ctid='{0}'", newctid);
  63. DataTable dtnew = CeErpTradeCell.ExecuteDataset(sqlnew.ToString()).Tables[0];
  64. if (dtnew == null || dtnew.Rows.Count < 1)
  65. {
  66. conErc("没有找到相关new新订单" + newctid);
  67. return;
  68. }
  69. List<string> files = new List<string>();
  70. string oldDesignTime = "";
  71. string oldFilename = "";
  72. string df_name = "";
  73. string[] extArr = new string[] { ".cdr", ".zip", ".rar", ".pdf" };
  74. string oldTag = ".cdr";
  75. List<string> noFileLst = new List<string>();
  76. List<string> errorFileLst = new List<string>();
  77. DataRow dr = dt.Rows[0];
  78. if (dr["FinishDesignTime"].ToString() == "")
  79. {
  80. conErc("没有找到相关old老订单附件,FinishDesignTime为空");
  81. return;
  82. }
  83. DateTime ftime = Convert.ToDateTime(dr["FinishDesignTime"]);
  84. DateTime splitTime = new DateTime(2023, 06, 27, 15, 30, 0);
  85. if (ftime.CompareTo(splitTime) > 0)
  86. {
  87. oldDesignTime = getDesignTimeWithDay(dr["FinishDesignTime"]);
  88. }
  89. else
  90. oldDesignTime = getDesignTime(dr["FinishDesignTime"]);
  91. //oldDesignTime = getDesignTime(dr["FinishDesignTime"]);
  92. df_name = upPath + "\\" + oldDesignTime + "\\" + formatMemo(dr["seller_memo"]);
  93. foreach (string ext in extArr)
  94. {
  95. oldFilename = df_name + ext;
  96. oldTag = ext;
  97. if (File.Exists(oldFilename))
  98. {
  99. break;
  100. //if (!isUpdateError)
  101. //{
  102. // files.Add(fname);
  103. // copyFile(getDesignDate(dr["FinishDesignTime"]), dr["SupplierName"].ToString(), fname);
  104. // fc++;
  105. //}
  106. }
  107. else
  108. oldFilename = "";
  109. }
  110. if (oldFilename == "")
  111. {
  112. conErc("没有找到相关old老订单附件");
  113. return;
  114. //noFileLst.Add("'" + dr["ctid"].ToString() + "'");
  115. }
  116. //if (hasFile)
  117. //{
  118. // fname = upPath + "\\" + dTime + "\\" + formatMemo(dr["seller_memo"]) + ".png";
  119. // if (File.Exists(fname))
  120. // {
  121. // files.Add(fname);
  122. // copyFile(getDesignDate(dr["FinishDesignTime"]), dr["SupplierName"].ToString(), fname);
  123. // }
  124. //}
  125. //sql = new StringBuilder();
  126. //sql.AppendFormat("insert into CE_ErpTradeLog(tid,orderstate,userid,operatetime,con) select ctid,{1},{2},getdate(),'{3}' from ce_erptradecell where ctid in ({0}) ;", tids, (int)OrderState.下单完成, userId, "下载设计文件");
  127. //sql.AppendFormat("update ce_erptradecell set FinishPlaceTime=getdate(),OrderState={0},IsReturn=0 where ctid in ({1}) and orderstate={2} and IsReturn<>2 and seller_memo not like '%电子稿%' ;", (int)OrderState.下单完成, tids, (int)OrderState.设计完成);
  128. //sql.AppendFormat("update ce_erptradecell set FinishPlaceTime=getdate(),OrderState={0},IsReturn=0 where ctid in ({1}) and orderstate={2} and IsReturn<>2 and seller_memo like '%电子稿%' ;", (int)OrderState.已发货, tids, (int)OrderState.设计完成);
  129. //CeErpTradeCell.ExecuteNonQuery(sql.ToString());
  130. DataRow newDr = dtnew.Rows[0];
  131. string newMemo = newDr["seller_memo"].ToString();
  132. newMemo = newMemo.Replace("(", "(");
  133. newMemo = newMemo.Replace(")", ")");
  134. string newmemoctid = MidStrEx(newMemo, "(", ")").Trim();
  135. string orderSn = newDr["orderSn"].ToString();
  136. if (newctid.IndexOf("C") != -1)
  137. {
  138. /*if (newMemo.IndexOf("[") != -1 && newMemo.IndexOf("C") != -1)
  139. {
  140. if (newmemoctid.IndexOf("S_") != -1) // (S_S_1962772776865084101)[C1] 对应ctid是 S_S_C1_1962772776865084101
  141. {
  142. int lastIndex = newmemoctid.LastIndexOf("S_"); //最后一个S_的位置
  143. string sPre = newmemoctid.Substring(0, lastIndex + 2); //S_S_
  144. string initTid = newmemoctid.Substring(lastIndex + 2, newmemoctid.Length - lastIndex - 2); //1962772776865084101
  145. string pre_ctid = MidStrEx(newMemo, "[", "]"); //C1
  146. if (pre_ctid.IndexOf("+") != -1)
  147. {
  148. pre_ctid = "C" + pre_ctid.Split('+')[1];
  149. }
  150. newmemoctid = sPre + pre_ctid + "_" + initTid; //S_S_ + C1 + _ +1962772776865084101
  151. }
  152. else
  153. {
  154. string pre_ctid = MidStrEx(newMemo, "[", "]");
  155. if (pre_ctid.IndexOf("+") != -1)
  156. {
  157. pre_ctid = "C" + pre_ctid.Split('+')[1];
  158. }
  159. if (newmemoctid.IndexOf('C') == -1)
  160. {
  161. newmemoctid = pre_ctid + "_" + newmemoctid;
  162. }
  163. }
  164. }*/
  165. }
  166. if (string.IsNullOrEmpty(newmemoctid))
  167. {
  168. conErc("上传的文件名格式不正确");
  169. return;
  170. }
  171. if (orderSn != newmemoctid)
  172. {
  173. conErc("新订单备注中的订单号不正确");
  174. return;
  175. }
  176. string newUpDesignTime = getDesignTimeWithDay(DateTime.Now);
  177. //string newDfName = upPath + "\\" + newUpDesignTime + "\\" + formatMemo(newDr["seller_memo"])+oldTag;
  178. string newPathFileName = "";
  179. copyUpFile(newUpDesignTime, oldFilename, formatMemo(newDr["seller_memo"]) + oldTag, ref newPathFileName);
  180. //copyFile(getDesignDate(DateTime.Now), dr["SupplierName"].ToString(), oldFilename, formatMemo(newDr["seller_memo"]) + oldTag);
  181. CeErpTradeCell.UpdateRelationOrder(newctid);
  182. StringBuilder up_sql = new StringBuilder();
  183. up_sql.AppendFormat("update ce_erptradecell with(rowlock) set orderstate=5,IsReturn=0,StartDesignTime=getdate(),SupplierId={1},FinishDesignTime=getdate() where ctid='{0}'", newctid, dr["SupplierId"]);
  184. CeErpTradeCell.ExecuteNonQuery(up_sql.ToString());
  185. if (oldTag == ".cdr")
  186. {
  187. //string sqlpng = string.Format("insert into s_cdrtopng(name,addtime)values('{0}',getdate()) ;", newPathFileName);
  188. //CeErpTradeLog.ExecuteNonQuery(sqlpng);
  189. }
  190. CeErpTradeLog.AddLog(newctid, 5, userId, "自动上传老客户文件-" + newPathFileName);
  191. string fileSql = string.Format("INSERT INTO [dbo].[CE_ErpTradeCellFile]([tid], [ctid], [isDel], [url], [createtime], [type]) SELECT '{0}', '{1}', isDel ,url,getdate(),type FROM [dbo].[CE_ErpTradeCellFile] WHERE tid='{2}' and ctid='{3}' and isDel = 0 and type = 'AUTH_FILE'", dtnew.Rows[0]["tid"], dtnew.Rows[0]["ctid"], dt.Rows[0]["tid"], dt.Rows[0]["ctid"]);
  192. CeErpTradeCell.ExecuteNonQuery(fileSql);
  193. conSuc("文件已上传到共享目录");
  194. return;
  195. }
  196. catch (Exception ex)
  197. {
  198. conErc("错误的下载访问" + ex.Message);
  199. XLog.SaveLog(0, "autocopydown," + ex.Message);
  200. return;
  201. }
  202. }
  203. }
  204. public static string MidStrEx(string sourse, string startstr, string endstr)
  205. {
  206. string result = string.Empty;
  207. int startindex, endindex;
  208. try
  209. {
  210. startindex = sourse.IndexOf(startstr);
  211. if (startindex == -1)
  212. return result;
  213. string tmpstr = sourse.Substring(startindex + startstr.Length);
  214. endindex = tmpstr.IndexOf(endstr);
  215. if (endindex == -1)
  216. return result;
  217. result = tmpstr.Remove(endindex);
  218. }
  219. catch (Exception ex)
  220. {
  221. Console.WriteLine("MidStrEx Err:" + ex.Message);
  222. }
  223. return result;
  224. }
  225. private string formatMemo(object memo)
  226. {
  227. string m = memo.ToString();
  228. m = m.Replace("\\", "").Replace("/", "").Replace(":", "").Replace("*", "").Replace("?", "").Replace("<", "").Replace(">", "").Replace("|", "");
  229. return m;
  230. }
  231. private void copyUpFile(string date, string oldfile, string newfilename, ref string newPathFileName)
  232. {
  233. try
  234. {
  235. string path = upPath + "\\" + date;
  236. if (!Directory.Exists(path)) Directory.CreateDirectory(path);
  237. //string fname = Path.GetFileName(file);
  238. File.Copy(oldfile, path + "\\" + newfilename, true);
  239. newPathFileName = path + "\\" + newfilename;
  240. if (!File.Exists(path + "\\" + newfilename))
  241. {
  242. File.Copy(oldfile, path + "\\" + newfilename, true);
  243. }
  244. }
  245. catch (Exception ex)
  246. {
  247. XLog.SaveLog(0, "自动复制上传文件发生错误," + newfilename + "," + ex.Message);
  248. throw ex;
  249. }
  250. }
  251. private void copyFile(string date, string supplier, string oldfile, string newFileName)
  252. {
  253. try
  254. {
  255. string path = copyPath + "\\" + date + "\\" + supplier;
  256. if (!Directory.Exists(path)) Directory.CreateDirectory(path);
  257. //string fname = Path.GetFileName(file);
  258. File.Copy(oldfile, path + "\\" + newFileName, true);
  259. if (!File.Exists(path + "\\" + newFileName))
  260. {
  261. File.Copy(oldfile, path + "\\" + newFileName, true);
  262. }
  263. }
  264. catch (Exception ex)
  265. {
  266. XLog.SaveLog(0, "自动复制下载文件发生错误," + oldfile + "," + ex.Message);
  267. }
  268. }
  269. private string getDesignTime(object v)
  270. {
  271. if (v.ToString() == "") return "";
  272. return Convert.ToDateTime(v).ToString("yyyyMM");
  273. }
  274. private string getDesignTimeWithDay(object v)
  275. {
  276. if (v.ToString() == "") return "";
  277. return Convert.ToDateTime(v).ToString("yyyyMMdd");
  278. }
  279. private string getDesignDate(object v)
  280. {
  281. return DateTime.Now.ToString("yyyy-MM-dd");
  282. if (v.ToString() == "") return "";
  283. return Convert.ToDateTime(v).ToString("yyyy-MM-dd");
  284. }
  285. /// 批量进行多个文件压缩到一个文件
  286. /// </summary>
  287. /// <param name="files">文件列表(绝对路径)</param> 这里用的数组,你可以用list 等或者
  288. /// <param name="zipFileName">生成的zip文件名称</param>
  289. private void ZipFileDownload(List<string> files, string zipFileName)
  290. {
  291. MemoryStream ms = new MemoryStream();
  292. byte[] buffer = null;
  293. using (ZipFile file = ZipFile.Create(ms))
  294. {
  295. file.BeginUpdate();
  296. //file.NameTransform = new ZipNameTransform();
  297. file.NameTransform = new MyNameTransfom();
  298. foreach (var item in files)
  299. {
  300. if (File.Exists(item)) file.Add(item);
  301. }
  302. file.CommitUpdate();
  303. buffer = new byte[ms.Length];
  304. ms.Position = 0;
  305. ms.Read(buffer, 0, buffer.Length); //读取文件内容(1次读ms.Length/1024M)
  306. ms.Flush();
  307. ms.Close();
  308. }
  309. Response.Clear();
  310. Response.Buffer = true;
  311. Response.ContentType = "application/x-zip-compressed";
  312. Response.AddHeader("Set-Cookie", "fileDownload=true; path=/");
  313. Response.AddHeader("content-disposition", "attachment;filename=" + HttpUtility.UrlEncode(zipFileName));
  314. Response.BinaryWrite(buffer);
  315. Page.Response.Flush();
  316. Page.Response.SuppressContent = true;
  317. HttpContext.Current.ApplicationInstance.CompleteRequest();
  318. //ScriptManager.RegisterStartupScript(Page, Page.GetType(), "popup", "alert('123');", true);
  319. //Response.Flush();
  320. //Response.End();
  321. }
  322. private void downLoadFile(string file)
  323. {
  324. string filePath = Server.MapPath("d/" + file);//路径
  325. //以字符流的形式下载文件
  326. FileStream fs = new FileStream(filePath, FileMode.Open);
  327. byte[] bytes = new byte[(int)fs.Length];
  328. fs.Read(bytes, 0, bytes.Length);
  329. fs.Close();
  330. Response.ContentType = "application/octet-stream";
  331. //通知浏览器下载文件而不是打开
  332. Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(file, System.Text.Encoding.UTF8));
  333. Response.BinaryWrite(bytes);
  334. Response.Flush();
  335. Response.End();
  336. }
  337. }