copydownload.aspx.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408
  1. using BizCom;
  2. using CorelDRAW;
  3. using ICSharpCode.SharpZipLib.Zip;
  4. using SQLData;
  5. using System;
  6. using System.Collections.Generic;
  7. using System.Configuration;
  8. using System.Data;
  9. using System.Data.SqlClient;
  10. using System.Diagnostics;
  11. using System.IO;
  12. using System.Text;
  13. using System.Web;
  14. using System.Web.UI;
  15. using System.Web.UI.WebControls;
  16. public partial class copydownload : System.Web.UI.Page
  17. {
  18. public static string upPath = ConfigurationManager.AppSettings["upPath"];
  19. public static string copyPath = ConfigurationManager.AppSettings["copyPath"];
  20. private void conErc(string msg)
  21. {
  22. Response.Write("{\"type\":\"error\",\"result\":\"" + msg + "\"}");
  23. //Response.End();
  24. }
  25. private void conSuc(string msg)
  26. {
  27. Response.Write("{\"type\":\"success\",\"result\":\"" + msg + "\"}");
  28. //Response.End();
  29. }
  30. private string dealMemoName(string name)
  31. {
  32. string[] al = name.Split('-');
  33. List<string> list = new List<string>();
  34. string pa = string.Empty;
  35. for (int i = 0; i < al.Length; i++)
  36. {
  37. if (i == 1)
  38. {
  39. if (al[i].Contains("(") || al[i].Contains("("))
  40. {
  41. string tname = al[i].Replace(")", "").Replace(")", "").Replace("(", "").Replace("(", "");
  42. if (!string.IsNullOrEmpty(tname))
  43. {
  44. pa = al[i];
  45. }
  46. continue;
  47. }
  48. }
  49. list.Add(al[i]);
  50. }
  51. if (!string.IsNullOrEmpty(pa))
  52. {
  53. list.Insert(3, pa);
  54. }
  55. name = string.Join("-", list);
  56. return name;
  57. }
  58. protected void Page_Load(object sender, EventArgs e)
  59. {
  60. if (Request["hexdata"] != null)
  61. {
  62. string tids = Request["hexdata"];
  63. if (tids.Trim() == "")
  64. {
  65. conErc("无法下载");
  66. return;
  67. }
  68. int userId = 0;
  69. if (Request["userid"] != null)
  70. {
  71. userId = Convert.ToInt32(Request["userid"]);
  72. }
  73. try
  74. {
  75. string[] tArr = tids.Split(',');
  76. List<string> tLst = new List<string>();
  77. foreach (string id in tArr)
  78. {
  79. tLst.Add("'" + id + "'");
  80. }
  81. tids = string.Join(",", tLst.ToArray());
  82. StringBuilder sql = new StringBuilder();
  83. sql.AppendFormat("select ctid,seller_memo,FinishDesignTime,OrderState,SupplierName,OrderSn,tid,SupplierId from view_erptradecell where orderstate=5 and ctid in ({0})", tids);
  84. DataTable dt = CeErpTradeCell.ExecuteDataset(sql.ToString()).Tables[0];
  85. if (dt == null || dt.Rows.Count < 1)
  86. {
  87. conErc("没有找到相关订单");
  88. return;
  89. }
  90. List<string> files = new List<string>();
  91. string dTime = "";
  92. string fname = "";
  93. int fc = 0;
  94. bool hasFile = false;
  95. string df_name = "";
  96. string[] extArr = new string[] { ".cdr", ".zip", ".rar", ".pdf" };
  97. List<string> noFileLst = new List<string>();
  98. List<string> errorFileLst = new List<string>();
  99. foreach (DataRow dr in dt.Rows)
  100. {
  101. if (dr["FinishDesignTime"].ToString() == "") continue;
  102. hasFile = false;
  103. DateTime ftime = Convert.ToDateTime(dr["FinishDesignTime"]);
  104. DateTime splitTime = new DateTime(2023, 06, 27, 15, 30, 0);
  105. if (ftime.CompareTo(splitTime) > 0)
  106. {
  107. dTime = getDesignTimeWithDay(dr["FinishDesignTime"]);//这个时间以后得按天分文件夹
  108. }
  109. else
  110. {
  111. dTime = getDesignTime(dr["FinishDesignTime"]);//上传原来按月分文件夹
  112. }
  113. string tid = dr["tid"].ToString();
  114. string orderSn = dr["OrderSn"].ToString();
  115. string rname = "";
  116. df_name = upPath + "\\" + dTime + "\\" + formatMemo(dr["seller_memo"]);
  117. foreach (string ext in extArr)
  118. {
  119. fname = df_name + ext;
  120. rname = formatMemo(dr["seller_memo"]) + ext;
  121. if ("14".Equals(dr["SupplierId"].ToString()))
  122. {
  123. rname = dealMemoName(rname);
  124. }
  125. if (!hasFile)
  126. {
  127. if (File.Exists(fname))
  128. {
  129. bool isCopyError = false;
  130. double payment = 0;
  131. string ctid = dr["ctid"].ToString();
  132. CeErpTradeCell entity = CeErpTradeCell.GetByCtid(ctid);
  133. try
  134. {
  135. if (entity != null)
  136. {
  137. payment = entity.payment;
  138. }
  139. hasFile = true;
  140. files.Add(fname);
  141. copyFile(getDesignDate(dr["FinishDesignTime"]), dr["SupplierName"].ToString(), fname, payment, rname);
  142. fc++;
  143. }
  144. catch (Exception ex)
  145. {
  146. isCopyError = true;
  147. errorFileLst.Add("'" + dr["ctid"].ToString() + "'");
  148. XLog.SaveLog(0, "复制文件发生错误," + fname + "," + ex.Message);
  149. }
  150. //复制完成后修改数据
  151. if (!isCopyError)
  152. {
  153. try
  154. {
  155. if (entity != null)
  156. {
  157. //update ce_erptradecell WITH(ROWLOCK) set FinishPlaceTime = getdate(), OrderState = 6, IsReturn = 0, PlaceUserId = @userid where CHARINDEX(',' + ctid + ',',',' + @mainctids + ',')> 0 and orderstate = 5 and isDianziOrder = 0
  158. //insert into CE_ErpTradeLog(tid, orderstate, userid, operatetime, con) select ctid,6,@userid,getdate(),'下载设计文件' from ce_erptradecell where CHARINDEX(',' + ctid + ',', ',' + @mainctids + ',') > 0
  159. entity.FinishPlaceTime = DateTime.Now;
  160. entity.OrderState = 6;
  161. entity.IsReturn = 0;
  162. entity.PlaceUserId = userId;
  163. entity.Update();
  164. CeErpTradeLog logenty = new CeErpTradeLog();
  165. logenty.tid = ctid;
  166. logenty.OrderState = 6;
  167. logenty.UserId = userId;
  168. logenty.OperateTime = DateTime.Now;
  169. logenty.Con = "下载设计文件";
  170. logenty.Create();
  171. CeErpDataSendOrderInfo.createObject(entity.ctid);
  172. }
  173. SqlParameter[] sqlParameter ={
  174. new SqlParameter("@mainctids", SqlDbType.VarChar,500),
  175. new SqlParameter("@userid", SqlDbType.VarChar,4),
  176. new SqlParameter("@res", SqlDbType.VarChar, 4000)
  177. };
  178. sqlParameter[0].Value = dr["ctid"].ToString();
  179. sqlParameter[1].Value = userId;
  180. sqlParameter[2].Direction = ParameterDirection.Output;
  181. CeErpTradeCell.ExecuteDataSetStore("sp_set_download", sqlParameter);
  182. }
  183. catch (Exception ex)
  184. {
  185. errorFileLst.Add("'" + dr["ctid"].ToString() + "'");
  186. XLog.SaveLog(0, "下载发生错误,ctid:" + dr["ctid"].ToString() + "," + ex.Message);
  187. }
  188. }
  189. }
  190. }
  191. else
  192. {
  193. break;
  194. }
  195. }
  196. if (!hasFile)
  197. {
  198. noFileLst.Add("'" + dr["ctid"].ToString() + "'");
  199. //sql = new StringBuilder();
  200. //sql.AppendFormat("insert into CE_ErpTradeLog(tid,orderstate,userid,operatetime,con) select ctid,{1},{2},getdate(),'{3}' from ce_erptradecell where ctid='{0}' ;", dr["ctid"], (int)OrderState.下单完成, 0, "找不到设计文件");
  201. //CeErpTradeCell.ExecuteNonQuery(sql.ToString());
  202. //conErc("找不到文件,订单号:" + dr["ctid"]);
  203. //return;
  204. }
  205. //if (hasFile)
  206. //{
  207. // fname = upPath + "\\" + dTime + "\\" + formatMemo(dr["seller_memo"]) + ".png";
  208. // if (File.Exists(fname))
  209. // {
  210. // files.Add(fname);
  211. // copyFile(getDesignDate(dr["FinishDesignTime"]), dr["SupplierName"].ToString(), fname);
  212. // }
  213. //}
  214. }
  215. if (fc == 0)
  216. {
  217. conErc("没有找到相关的设计附件");
  218. return;
  219. }
  220. //sql = new StringBuilder();
  221. //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, "下载设计文件");
  222. //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.设计完成);
  223. //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.设计完成);
  224. //CeErpTradeCell.ExecuteNonQuery(sql.ToString());
  225. foreach (string ctid in tArr)
  226. {
  227. CeErpTradeCell.UpdateRelationOrder(ctid);
  228. }
  229. if (Request["supplier"] != null && Request["supplier"].ToString() == "1")
  230. {
  231. ZipFileDownload(files, "LT_" + DateTime.Now.ToString("yyyyMMddhhMmss") + ".zip");
  232. }
  233. else if (noFileLst.Count > 0 || errorFileLst.Count > 0)
  234. {
  235. string tips = "";
  236. if (noFileLst.Count > 0)
  237. {
  238. string notids = string.Join(",", noFileLst.ToArray());
  239. sql = new StringBuilder();
  240. sql.AppendFormat("insert into CE_ErpTradeLog(tid,orderstate,userid,operatetime,con) select ctid,{1},{2},getdate(),'{3}' from ce_erptradecell where ctid in ({0}) ;", notids, (int)OrderState.下单完成, 0, "找不到设计文件");
  241. CeErpTradeCell.ExecuteNonQuery(sql.ToString());
  242. tips += "找不到文件,单号:" + notids;
  243. }
  244. if (errorFileLst.Count > 0)
  245. {
  246. string ertids = string.Join(",", errorFileLst.ToArray());
  247. sql = new StringBuilder();
  248. sql.AppendFormat("insert into CE_ErpTradeLog(tid,orderstate,userid,operatetime,con) select ctid,{1},{2},getdate(),'{3}' from ce_erptradecell where ctid in ({0}) ;", ertids, (int)OrderState.下单完成, 0, "下载设计文件出错");
  249. CeErpTradeCell.ExecuteNonQuery(sql.ToString());
  250. tips += " 复制下载出错,单号:" + ertids;
  251. }
  252. conErc(tips);
  253. }
  254. else
  255. {
  256. conSuc("文件已下载到共享目录");
  257. }
  258. return;
  259. }
  260. catch (Exception ex)
  261. {
  262. conErc("复制错误的下载访问");
  263. XLog.SaveLog(0, "copydown" + ex.Message);
  264. return;
  265. }
  266. }
  267. }
  268. private string formatMemo(object memo)
  269. {
  270. string m = memo.ToString();
  271. m = m.Replace("\\", "").Replace("/", "").Replace(":", "").Replace("*", "").Replace("?", "").Replace("<", "").Replace(">", "").Replace("|", "");
  272. return m;
  273. }
  274. Dictionary<string, string> replaceRules = new Dictionary<string, string>
  275. {
  276. { "皙贝", "白卡" },
  277. { "睿狐", "莱尼" },
  278. { "岚蝶", "安格" },
  279. { "琮纹", "刚古" },
  280. { "珠光", "珠光" },
  281. { "溪雪", "珠光" },
  282. { "雅柔", "雅柔" },
  283. { "萱姿", "雅柔" },
  284. { "草香", "草香" },
  285. { "芳怡", "草香" },
  286. { "金绒", "牛皮" },
  287. { "素芸", "棉卡" },
  288. { "玉蕊", "蛋壳" }
  289. };
  290. private void copyFile(string date, string supplier, string file, double payment, string rname)
  291. {
  292. string SupName = supplier;
  293. if (payment >= 500)
  294. {
  295. SupName = supplier + "500";
  296. }
  297. string path = copyPath + "\\" + date + "\\" + SupName;
  298. if (!Directory.Exists(path)) Directory.CreateDirectory(path);
  299. string fname = Path.GetFileName(file);
  300. foreach (var rule in replaceRules)
  301. {
  302. rname = rname.Replace(rule.Key, rule.Value);
  303. }
  304. File.Copy(file, path + "\\" + rname, true);
  305. if (!File.Exists(path + "\\" + rname))
  306. {
  307. File.Copy(file, path + "\\" + rname, true);
  308. }
  309. }
  310. private string getDesignTime(object v)
  311. {
  312. if (v.ToString() == "") return "";
  313. return Convert.ToDateTime(v).ToString("yyyyMM");
  314. }
  315. private string getDesignTimeWithDay(object v)
  316. {
  317. if (v.ToString() == "") return "";
  318. return Convert.ToDateTime(v).ToString("yyyyMMdd");
  319. }
  320. private string getDesignDate(object v)
  321. {
  322. return DateTime.Now.ToString("yyyy-MM-dd");
  323. if (v.ToString() == "") return "";
  324. return Convert.ToDateTime(v).ToString("yyyy-MM-dd");
  325. }
  326. /// 批量进行多个文件压缩到一个文件
  327. /// </summary>
  328. /// <param name="files">文件列表(绝对路径)</param> 这里用的数组,你可以用list 等或者
  329. /// <param name="zipFileName">生成的zip文件名称</param>
  330. private void ZipFileDownload(List<string> files, string zipFileName)
  331. {
  332. MemoryStream ms = new MemoryStream();
  333. byte[] buffer = null;
  334. using (ZipFile file = ZipFile.Create(ms))
  335. {
  336. file.BeginUpdate();
  337. //file.NameTransform = new ZipNameTransform();
  338. file.NameTransform = new MyNameTransfom();
  339. foreach (var item in files)
  340. {
  341. if (File.Exists(item)) file.Add(item);
  342. }
  343. file.CommitUpdate();
  344. buffer = new byte[ms.Length];
  345. ms.Position = 0;
  346. ms.Read(buffer, 0, buffer.Length); //读取文件内容(1次读ms.Length/1024M)
  347. ms.Flush();
  348. ms.Close();
  349. }
  350. Response.Clear();
  351. Response.Buffer = true;
  352. Response.ContentType = "application/x-zip-compressed";
  353. Response.AddHeader("Set-Cookie", "fileDownload=true; path=/");
  354. Response.AddHeader("content-disposition", "attachment;filename=" + HttpUtility.UrlEncode(zipFileName));
  355. Response.BinaryWrite(buffer);
  356. Page.Response.Flush();
  357. Page.Response.SuppressContent = true;
  358. HttpContext.Current.ApplicationInstance.CompleteRequest();
  359. //ScriptManager.RegisterStartupScript(Page, Page.GetType(), "popup", "alert('123');", true);
  360. //Response.Flush();
  361. //Response.End();
  362. }
  363. private void downLoadFile(string file)
  364. {
  365. string filePath = Server.MapPath("d/" + file);//路径
  366. //以字符流的形式下载文件
  367. FileStream fs = new FileStream(filePath, FileMode.Open);
  368. byte[] bytes = new byte[(int)fs.Length];
  369. fs.Read(bytes, 0, bytes.Length);
  370. fs.Close();
  371. Response.ContentType = "application/octet-stream";
  372. //通知浏览器下载文件而不是打开
  373. Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(file, System.Text.Encoding.UTF8));
  374. Response.BinaryWrite(bytes);
  375. Response.Flush();
  376. Response.End();
  377. }
  378. }