main.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379
  1. const matched = window.location.search.match(/filter=(.+)/);
  2. const compilationID = matched && matched[1] || '';
  3. // 节流
  4. function throttle(fn, time) {
  5. let canRun = true;
  6. return function () {
  7. if (!canRun) {
  8. return;
  9. }
  10. canRun = false;
  11. const rst = fn.apply(this, arguments);
  12. // 事件返回错误,说明没有发起请求,允许直接继续触发事件,不进行节流处理
  13. if (rst === false) {
  14. canRun = true;
  15. return;
  16. }
  17. setTimeout(() => canRun = true, time);
  18. }
  19. }
  20. const periodReg = /\d{4}-((0[1-9])|(1[0-2]))$/;
  21. function createLib() {
  22. const name = $('#name').val();
  23. if (!name) {
  24. $('#name-error').show();
  25. return false;
  26. }
  27. const period = $('#period').val();
  28. if (!period || !periodReg.test(period)) {
  29. $('#period-error').show();
  30. return false;
  31. }
  32. $('#add-lib-form').submit();
  33. }
  34. let curLib = {};
  35. //设置当前库
  36. function setCurLib(libID) {
  37. curLib.id = libID;
  38. curLib.name = $(`#${libID}`).text();
  39. curLib.compilationID = $(`#${libID}`).data('compilationid');
  40. }
  41. // 点击编辑按钮
  42. function handleEditClick(libID) {
  43. setCurLib(libID);
  44. $('#edit').modal('show');
  45. }
  46. // 点击确认编辑
  47. function handleEditConfirm() {
  48. const rename = $('#rename-text').val();
  49. if (!rename) {
  50. $('#rename-error').show();
  51. return false;
  52. }
  53. $('#edit').modal('hide');
  54. ajaxPost('/priceInfo/renameLib', { libID: curLib.id, name: rename })
  55. .then(() => $(`#${curLib.id} a`).text(rename));
  56. }
  57. // 删除需要连需点击三次才可删除
  58. let curDelCount = 0;
  59. // 点击删除按钮
  60. function handleDeleteClick(libID) {
  61. setCurLib(libID);
  62. curDelCount = 0;
  63. $('#del').modal('show');
  64. }
  65. // 删除确认
  66. function handleDeleteConfirm() {
  67. curDelCount++;
  68. if (curDelCount === 3) {
  69. $.bootstrapLoading.start();
  70. curDelCount = -10; // 由于需要连续点击,因此没有对此事件进行节流,为防止多次请求,一旦连续点击到三次,马上清空次数。
  71. $('#del').modal('hide');
  72. ajaxPost('/priceInfo/deleteLib', { libID: curLib.id })
  73. .then(() => $(`#${curLib.id}`).parent().remove())
  74. .finally(() => $.bootstrapLoading.end());
  75. }
  76. }
  77. // 获取地区
  78. let curAreas = [];
  79. let curAreaMap = {};
  80. const getAreas = async () => {
  81. const areas = await ajaxPost('/priceInfo/getAreas', { compilationID: curLib.compilationID });
  82. return areas;
  83. }
  84. // 获取地区下拉选项映射,key为父地区、value为子地区
  85. const getAreaMap = async () => {
  86. curAreas = await getAreas();
  87. const areaMap = {};
  88. curAreas.forEach(item => {
  89. const { name } = item;
  90. if (name) {
  91. let [parent, sub] = name.split('-');
  92. if (!sub) {
  93. sub = parent;
  94. }
  95. if (!areaMap[parent]) {
  96. areaMap[parent] = [sub];
  97. } else {
  98. areaMap[parent].push(sub);
  99. }
  100. }
  101. });
  102. return areaMap;
  103. }
  104. // 根据地区选项获取地区ID
  105. const getAreaIDByOption = ($parent, $sub) => {
  106. const parentArea = $parent.val();
  107. const subArea = $sub.val();
  108. const areaItem = curAreas.find(item => [parentArea, `${parentArea}-${subArea}`].includes(item.name));
  109. console.log(areaItem);
  110. return areaItem?.ID;
  111. }
  112. // 设置地区下拉项
  113. const setAreaOption = ($parent, $sub, areaMap) => {
  114. $parent.unbind();
  115. const parentAreas = Object.keys(areaMap);
  116. $parent.empty();
  117. const parentOptionsHtml = parentAreas.map(parentArea => `<option value="${parentArea}">${parentArea}</option>`).join('');
  118. $parent.append(parentOptionsHtml);
  119. const setSubs = (subsArea) => {
  120. $sub.empty();
  121. const subOptionsHtml = subsArea.map(subArea => `<option value="${subArea}">${subArea}</option>`).join('');
  122. $sub.append(subOptionsHtml);
  123. }
  124. setSubs(areaMap[parentAreas[0]] || []);
  125. $parent.change(() => {
  126. const curParent = $parent.val();
  127. setSubs(areaMap[curParent] || []);
  128. getAreaIDByOption();
  129. });
  130. }
  131. let importType = 'originalData';
  132. const importTitleMap = {
  133. originalData: '原始数据',
  134. mainSub: '主从数据',
  135. keys: '关键字数据',
  136. };
  137. // 点击导入按钮
  138. async function handleImportClick(libID, type) {
  139. try {
  140. setCurLib(libID);
  141. importType = type;
  142. $('#import-title').text(`导入${importTitleMap[type] || '数据'}`);
  143. if (['mainSub', 'keys'].includes(importType)) {
  144. $('#import-area').show();
  145. const areaMap = await getAreaMap();
  146. setAreaOption($('#import-parent-area'), $('#import-sub-area'), areaMap);
  147. } else {
  148. $('#import-area').hide();
  149. }
  150. $('#import').modal('show');
  151. } catch (error) {
  152. alert(error.message);
  153. }
  154. }
  155. // 导入确认
  156. function handleImportConfirm() {
  157. $.bootstrapLoading.start();
  158. const self = $(this);
  159. try {
  160. const areaID = getAreaIDByOption($('#import-parent-area'), $('#import-sub-area'));
  161. if (!areaID) {
  162. throw '请选择地区!';
  163. }
  164. const formData = new FormData();
  165. const file = $("input[name='import_data']")[0];
  166. if (file.files.length <= 0) {
  167. throw '请选择文件!';
  168. }
  169. formData.append('file', file.files[0]);
  170. formData.append('libID', curLib.id);
  171. formData.append('areaID', areaID);
  172. formData.append('importType', importType);
  173. $.ajax({
  174. url: '/priceInfo/importExcel',
  175. type: 'POST',
  176. data: formData,
  177. cache: false,
  178. contentType: false,
  179. processData: false,
  180. beforeSend: function () {
  181. self.attr('disabled', 'disabled');
  182. self.text('上传中...');
  183. },
  184. success: function (response) {
  185. self.removeAttr('disabled');
  186. self.text('确定导入');
  187. if (response.err === 0) {
  188. $.bootstrapLoading.end();
  189. const message = response.msg !== undefined ? response.msg : '';
  190. if (message !== '') {
  191. alert(message);
  192. }
  193. // 成功则关闭窗体
  194. $('#import').modal("hide");
  195. } else {
  196. $.bootstrapLoading.end();
  197. const message = response.msg !== undefined ? response.msg : '上传失败!';
  198. alert(message);
  199. }
  200. },
  201. error: function () {
  202. $.bootstrapLoading.end();
  203. alert("与服务器通信发生错误");
  204. self.removeAttr('disabled');
  205. self.text('确定导入');
  206. }
  207. });
  208. } catch (error) {
  209. alert(error);
  210. $.bootstrapLoading.end();
  211. }
  212. }
  213. // 点击导出按钮
  214. async function handleExportClick(libID) {
  215. try {
  216. setCurLib(libID);
  217. $('#export').modal('show');
  218. const areaMap = await getAreaMap();
  219. setAreaOption($('#export-parent-area'), $('#export-sub-area'), areaMap);
  220. } catch (error) {
  221. alert(error.message);
  222. }
  223. }
  224. // 导出确认
  225. function handleExportConfirm() {
  226. debugger;
  227. const areaID = getAreaIDByOption($('#export-parent-area'), $('#export-sub-area'));
  228. if (!areaID) {
  229. alert('请选择地区!');
  230. return;
  231. }
  232. $('#export').modal('hide');
  233. window.location.href = `/priceInfo/export?libID=${curLib.id}&areaID=${areaID}`;
  234. }
  235. const { ProcessStatus, CRAWL_LOG_KEY } = window.PRICE_INFO_CONST;
  236. const CHECKING_TIME = 5000;
  237. // 检测爬取、导入是否完成
  238. function processChecking(key, cb) {
  239. checking();
  240. function checking() {
  241. ajaxPost('/priceInfo/processChecking', { key })
  242. .then(handleResolve)
  243. .catch(handleReject)
  244. }
  245. let timer;
  246. function handleResolve({ key, status, errorMsg }) {
  247. if (status === ProcessStatus.START) {
  248. if (!$('#progressModal').is(':visible')) {
  249. const title = key === CRAWL_LOG_KEY ? '爬取数据' : '导入数据';
  250. const text = key === CRAWL_LOG_KEY ? '正在爬取数据,请稍候……' : '正在导入数据,请稍候……';
  251. $.bootstrapLoading.progressStart(title, true);
  252. $("#progress_modal_body").text(text);
  253. }
  254. timer = setTimeout(checking, CHECKING_TIME);
  255. } else if (status === ProcessStatus.FINISH) {
  256. if (timer) {
  257. clearTimeout(timer);
  258. }
  259. $.bootstrapLoading.progressEnd();
  260. if (cb) {
  261. cb();
  262. }
  263. } else {
  264. if (timer) {
  265. clearTimeout(timer);
  266. }
  267. if (errorMsg) {
  268. alert(errorMsg);
  269. }
  270. if (cb) {
  271. cb();
  272. }
  273. $.bootstrapLoading.progressEnd();
  274. }
  275. }
  276. function handleReject(err) {
  277. if (timer) {
  278. clearInterval(timer);
  279. }
  280. alert(err);
  281. $.bootstrapLoading.progressEnd();
  282. }
  283. }
  284. // 爬取数据确认
  285. function handleCrawlConfirm() {
  286. const from = $('#period-start').val();
  287. const to = $('#period-end').val();
  288. if (!periodReg.test(from) || !periodReg.test(to)) {
  289. $('#crawl-error').show();
  290. return false;
  291. }
  292. $('#crawl').modal('hide');
  293. ajaxPost('/priceInfo/crawlData', { from, to, compilationID }, 0) // 没有timeout
  294. .then(() => {
  295. processChecking(CRAWL_LOG_KEY, () => window.location.reload());
  296. })
  297. }
  298. /* function handleCrawlConfirm() {
  299. const from = $('#period-start').val();
  300. const to = $('#period-end').val();
  301. if (!periodReg.test(from) || !periodReg.test(to)) {
  302. $('#crawl-error').show();
  303. return false;
  304. }
  305. $('#crawl').modal('hide');
  306. $.bootstrapLoading.progressStart('爬取数据', true);
  307. $("#progress_modal_body").text('正在爬取数据,请稍候……');
  308. // 不用定时器的话,可能finally处理完后,进度条界面才显示,导致进度条界面没有被隐藏
  309. const time = setInterval(() => {
  310. if ($('#progressModal').is(':visible')) {
  311. clearInterval(time);
  312. ajaxPost('/priceInfo/crawlData', { from, to, compilationID }, 0) // 没有timeout
  313. .then(() => {
  314. window.location.reload();
  315. })
  316. .finally(() => $.bootstrapLoading.progressEnd());
  317. }
  318. }, 500);
  319. } */
  320. const throttleTime = 1000;
  321. $(document).ready(function () {
  322. processChecking();
  323. // 锁定、解锁
  324. $('.lock').click(function () {
  325. lockUtil.handleLockClick($(this));
  326. });
  327. // 新增
  328. $('#add-lib').click(throttle(createLib, throttleTime));
  329. // 重命名
  330. $('#rename').click(throttle(handleEditConfirm, throttleTime));
  331. // 删除
  332. $('#delete').click(handleDeleteConfirm);
  333. // 爬取数据
  334. $('#crawl-confirm').click(throttle(handleCrawlConfirm, throttleTime));
  335. // 导出excel
  336. $('#export-confirm').click(throttle(handleExportConfirm, throttleTime));
  337. // 导入excel
  338. $('#import-confirm').click(throttle(handleImportConfirm, throttleTime));
  339. $('#add').on('hidden.bs.modal', () => {
  340. $('#name-error').hide();
  341. $('#period-error').hide();
  342. });
  343. $('#edit').on('hidden.bs.modal', () => $('#rename-error').hide());
  344. $('#crawl').on('hidden.bs.modal', () => $('#crawl-error').hide());
  345. });
  346. $.ajax({
  347. url: 'http://api.zjtcn.com/user/dyn_code',
  348. type: 'post',
  349. data: { service_id: '2020090003' },
  350. contentType: 'application/x-www-form-urlencoded',
  351. })