text-to-chart.js 87 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770
  1. console.log('text-to-chart');
  2. var accessToken = localStorage.getItem("access_token");
  3. console.log(accessToken);
  4. if (accessToken === null) {
  5. alert('請先登入')
  6. window.location.href = "./login.html";
  7. }
  8. var usernameEmail = localStorage.getItem("username");
  9. var unit_table_value
  10. // let username = usernameEmail.split('@')[0];
  11. Chart.register(ChartDataLabels);
  12. var userNameSpan = document.getElementById("userName");
  13. var lineYfontSize = document.getElementById("lineYfontSize");
  14. userNameSpan.textContent = usernameEmail;
  15. var inputField = document.getElementById("keyword_data");
  16. var inputField_compare = document.getElementById("keyword_data_compare");
  17. var compare_box = document.getElementById("compare");
  18. var sendButton = document.getElementById("send_data");
  19. var send_data_compare = document.getElementById("data_compare");
  20. var canvasPng = document.getElementById("textToChart");
  21. var img_box = document.getElementById("img_box");
  22. var sidebar = document.getElementById('style_setting');
  23. var input_text_value;
  24. var chartType = 'line';
  25. var unit = '';
  26. var myChart = null;
  27. var chartColor = '#912B2B';
  28. var chartColorBar = '#'
  29. var displayXaxes = true;
  30. var ctx;
  31. var chartlabels;
  32. var chartdata;
  33. var XfontSizeValue = 18;
  34. var YfontSizeValue = 18;
  35. var TitlefontSizeValue = 32;
  36. var pieFontSize = 14;
  37. var PieMaxWidth = 100;
  38. var chart_bgimg_url = "url(./img/bg06.webp)";
  39. var vocab = [];
  40. var chartDiv = document.getElementById('chartdiv');
  41. var dataFirstValue;
  42. var dataLastValue;
  43. let cancelToken;
  44. let source;
  45. $('#chartdiv').hide();
  46. var clickExample = document.getElementById('example_box')
  47. document.addEventListener('DOMContentLoaded', function () {
  48. axios.get("https://cmm.ai:8080/vocab")
  49. .then(response => {
  50. // apiHideLoading();
  51. console.log(response);
  52. vocab = response.data;
  53. })
  54. .catch(error => {
  55. console.error('發生錯誤:', error);
  56. });
  57. });
  58. inputField.addEventListener('click', function () {
  59. // 確保輸入框處於焦點狀態
  60. inputField.focus();
  61. // 在控制台中顯示焦點狀態
  62. console.log('Input field focused');
  63. });
  64. document.addEventListener('DOMContentLoaded', function () {
  65. // const input = document.getElementById('stockInput');
  66. const suggestions = document.getElementById('suggestions');
  67. inputField.addEventListener('input', function () {
  68. const query = this.value.trim();
  69. suggestions.innerHTML = ''; // 清空之前的建議
  70. console.log('query', query);
  71. if (query) {
  72. // const filteredVocab = vocab.filter(item => item.toLowerCase().includes(query));
  73. const queryTerms = query.split(/\s+/); // 分割輸入的內容
  74. const lastQueryTerm = queryTerms[queryTerms.length - 1];
  75. const filteredVocab = vocab.filter(item => {
  76. // 對每個分割後的單詞進行匹配,只要其中有一個匹配成功就返回 true
  77. return item.toLowerCase().includes(lastQueryTerm.toLowerCase());
  78. });
  79. if (filteredVocab.length > 0) {
  80. suggestions.style.border = '1px solid #ccc';
  81. suggestions.style.display = 'block'; // 顯示建議容器
  82. } else {
  83. suggestions.style.border = 'none';
  84. suggestions.style.display = 'none'; // 隱藏建議容器
  85. }
  86. console.log(queryTerms[queryTerms.length - 1])
  87. filteredVocab.forEach(item => {
  88. const div = document.createElement('div');
  89. div.classList.add('autocomplete-suggestion');
  90. div.textContent = item;
  91. // div.addEventListener('click', function () {
  92. // inputField.value = item;
  93. // suggestions.innerHTML = ''; // 清空建議
  94. // suggestions.style.border = 'none';
  95. // suggestions.style.display = 'none'; // 隱藏建議容器
  96. // });
  97. // console.log('queryTerms', queryTerms);
  98. // console.log('filteredVocab', filteredVocab);
  99. div.addEventListener('click', function () {
  100. queryTerms.forEach((term, index) => {
  101. const regex = new RegExp(term, 'gi');
  102. const match = regex.exec(inputField.value);
  103. // console.log(queryTerms[queryTerms.length - 1]);
  104. // console.log(filteredVocab, queryTerms[queryTerms.length - 1])
  105. if (index === queryTerms.length - 1) {
  106. if (match) {
  107. var start = match.index;
  108. var end = start + match[0].length;
  109. console.log(start, end)
  110. const textBefore = inputField.value.substring(0, start);
  111. const textAfter = inputField.value.substring(end, inputField.value.length);
  112. console.log('start', start, 'end', end, 'textBefore', textBefore, 'textAfter', textAfter);
  113. // 捕獲被選中的部分並替換它
  114. const selectedText = inputField.value.substring(start, end);
  115. console.log('selectedText', selectedText);
  116. const newText = textBefore + item + textAfter.replace(selectedText, '');
  117. console.log('newText', newText);
  118. inputField.value = newText;
  119. // inputField.value = textBefore + item.replace(selectedText, '') + textAfter;
  120. suggestions.innerHTML = ''; // 清空建議
  121. suggestions.style.border = 'none';
  122. }
  123. }
  124. });
  125. // const start = inputField.selectionStart;
  126. // const end = inputField.selectionEnd;
  127. });
  128. suggestions.appendChild(div);
  129. });
  130. } else {
  131. suggestions.style.border = 'none';
  132. suggestions.style.display = 'none'; // 隱藏建議容器
  133. }
  134. });
  135. });
  136. document.addEventListener('DOMContentLoaded', function () {
  137. // const input = document.getElementById('stockInput');
  138. const suggestions_compare = document.getElementById('suggestions_compare');
  139. inputField_compare.addEventListener('input', function () {
  140. const query = this.value.trim();
  141. suggestions_compare.innerHTML = ''; // 清空之前的建議
  142. console.log('query', query);
  143. if (query) {
  144. // const filteredVocab = vocab.filter(item => item.toLowerCase().includes(query));
  145. const queryTerms = query.split(/\s+/); // 分割輸入的內容
  146. const lastQueryTerm = queryTerms[queryTerms.length - 1];
  147. const filteredVocab = vocab.filter(item => {
  148. // 對每個分割後的單詞進行匹配,只要其中有一個匹配成功就返回 true
  149. return item.toLowerCase().includes(lastQueryTerm.toLowerCase());
  150. });
  151. if (filteredVocab.length > 0) {
  152. suggestions_compare.style.border = '1px solid #ccc';
  153. suggestions_compare.style.display = 'block'; // 顯示建議容器
  154. } else {
  155. suggestions_compare.style.border = 'none';
  156. suggestions_compare.style.display = 'none'; // 隱藏建議容器
  157. }
  158. console.log(queryTerms[queryTerms.length - 1])
  159. filteredVocab.forEach(item => {
  160. const div = document.createElement('div');
  161. div.classList.add('autocomplete-suggestion');
  162. div.textContent = item;
  163. // div.addEventListener('click', function () {
  164. // inputField.value = item;
  165. // suggestions.innerHTML = ''; // 清空建議
  166. // suggestions.style.border = 'none';
  167. // suggestions.style.display = 'none'; // 隱藏建議容器
  168. // });
  169. // console.log('queryTerms', queryTerms);
  170. // console.log('filteredVocab', filteredVocab);
  171. div.addEventListener('click', function () {
  172. queryTerms.forEach((term, index) => {
  173. const regex = new RegExp(term, 'gi');
  174. const match = regex.exec(inputField_compare.value);
  175. // console.log(queryTerms[queryTerms.length - 1]);
  176. // console.log(filteredVocab, queryTerms[queryTerms.length - 1])
  177. if (index === queryTerms.length - 1) {
  178. if (match) {
  179. var start = match.index;
  180. var end = start + match[0].length;
  181. console.log(start, end)
  182. const textBefore = inputField_compare.value.substring(0, start);
  183. const textAfter = inputField_compare.value.substring(end, inputField_compare.value.length);
  184. console.log('start', start, 'end', end, 'textBefore', textBefore, 'textAfter', textAfter);
  185. // 捕獲被選中的部分並替換它
  186. const selectedText = inputField_compare.value.substring(start, end);
  187. console.log('selectedText', selectedText);
  188. const newText = textBefore + item + textAfter.replace(selectedText, '');
  189. console.log('newText', newText);
  190. inputField_compare.value = newText;
  191. // inputField.value = textBefore + item.replace(selectedText, '') + textAfter;
  192. suggestions_compare.innerHTML = ''; // 清空建議
  193. suggestions_compare.style.border = 'none';
  194. }
  195. }
  196. });
  197. // const start = inputField.selectionStart;
  198. // const end = inputField.selectionEnd;
  199. });
  200. suggestions_compare.appendChild(div);
  201. });
  202. } else {
  203. suggestions_compare.style.border = 'none';
  204. suggestions_compare.style.display = 'none'; // 隱藏建議容器
  205. }
  206. });
  207. });
  208. // 監聽輸入框的鍵盤事件
  209. // document.getElementById("keyword_data").addEventListener("keyup", function (event) {
  210. // // 判斷是否按下 Enter 鍵 (key code: 13)
  211. // if (event.keyCode === 13) {
  212. // // 觸發送出按鈕的點擊事件
  213. // document.getElementById("send_data").click();
  214. // }
  215. // });
  216. // 定義按鈕點擊事件處理函數
  217. function sendButtonClickHandler() {
  218. // inputField.value = "";
  219. console.log(inputField.value);
  220. var input_text_value = inputField.value;
  221. compare_box.style.display = "none";
  222. $('#chartdiv').hide();
  223. sidebar.classList.remove('show');
  224. sidebar.classList.add('hidden');
  225. // 在這裡添加你希望在按下按鈕時執行的其他代碼
  226. get_data(input_text_value);
  227. }
  228. sendButton.addEventListener("click", function () {
  229. sendButtonClickHandler();
  230. inputField.value = ''
  231. chartTypeBtn.style.display = "none";
  232. });
  233. let labels2 = [];
  234. let data2 = [];
  235. send_data_compare.addEventListener("click", function () {
  236. console.log('比較', inputField_compare.value);
  237. const stockName = inputField_compare.value;
  238. axios
  239. .get(`https://cmm.ai:8080/get_data_from_date?start_date=${dataFirstValue}&end_date=${dataLastValue}&stock_name=${inputField_compare.value}`)
  240. .then((response) => {
  241. console.log(response);
  242. var compare_data = response.data.data;
  243. labels2 = []; // Clear previous labels
  244. data2 = []; // Clear previous data
  245. // console.log('比較送出後', chartType)
  246. if (chartType === 'line') {
  247. const colors = [
  248. 'rgba(130, 163, 63, 1)',
  249. 'rgba(47, 72, 123, 1)',
  250. '#df8c49',
  251. '#72598f',
  252. '#489fb6',
  253. '#99b0d5'
  254. ];
  255. let colorIndex = 0;
  256. for (var i = 0; i < compare_data.length; i++) {
  257. var item = compare_data[i];
  258. // 遍历当前项的属性
  259. for (var key in item) {
  260. // 如果属性名不在 labels 数组中,并且属性值不是对象,则将属性名添加到 labels 数组中
  261. if (typeof item[key] === 'string') {
  262. labels2.push(item[key]);
  263. }
  264. // 如果属性值是数值类型,则将其添加到 data 数组中
  265. if (typeof item[key] === 'number') {
  266. data2.push(item[key]);
  267. }
  268. }
  269. }
  270. function getRandomColor() {
  271. const randomIndex = Math.floor(Math.random() * colors.length);
  272. const selectedColor = colors[randomIndex];
  273. colors.splice(randomIndex, 1); // 从数组中移除已选颜色
  274. return selectedColor;
  275. }
  276. const normalize = (prices) => {
  277. const initialPrice = prices[0];
  278. return prices.map(price => (price - initialPrice) / initialPrice * 100);
  279. };
  280. const stock2Normalized = normalize(data2);
  281. const stock1Normalized = normalize(data);
  282. const color = getRandomColor();
  283. const newDataset = {
  284. label: stockName,
  285. backgroundColor: colors,
  286. pointRadius: 0,
  287. pointHoverRadius: 0,
  288. borderColor: colors,
  289. data: stock2Normalized,
  290. fill: false
  291. };
  292. colorIndex = (colorIndex + 1) % colors.length;
  293. myChart.data.datasets.push(newDataset);
  294. myChart.data.datasets[0].data = stock1Normalized;
  295. console.log('多筆資料', myChart.data.datasets);
  296. // console.log('比較', myChart.options.plugins.legend);
  297. myChart.options.plugins.legend.display = true;
  298. // myChart.defaults.global.legend = {
  299. // display: true,
  300. // position: 'top', // 默认图例位置为顶部
  301. // labels: {
  302. // fontColor: 'rgb(255, 99, 132)', // 默认图例标签颜色
  303. // fontSize: 14 // 默认图例标签字体大小
  304. // }
  305. // };
  306. myChart.update();
  307. inputField_compare.value = '';
  308. unitInput.value = '%';
  309. unit_value.textContent = '單位:' + '%'
  310. } else if (chartType === 'bar') {
  311. }
  312. })
  313. .catch((error) =>
  314. console.log(error)
  315. );
  316. });
  317. // sendButton.addEventListener("click", function () {
  318. // console.log(inputField.value);
  319. // input_text_value = inputField.value;
  320. // // if (myChart) {
  321. // // console.log('已存在')
  322. // // data = [];
  323. // // labels = [];
  324. // // myChart.removePlugin(Chart.pluginService.getPlugin('afterDraw'));
  325. // // myChart.destroy();
  326. // // }
  327. // get_data(input_text_value);
  328. // });
  329. var lastKeyPressTime = 0;
  330. var enterCount = 0;
  331. var ENTER_THRESHOLD = 500; // 設定連續按下 Enter 的時間閾值(毫秒)
  332. inputField.addEventListener("keyup", function (event) {
  333. // 判斷是否按下 Enter 鍵 (key code: 13)
  334. if (event.key === "Enter") {
  335. var currentTime = new Date().getTime();
  336. // 計算與上一次按鍵按下時間的差值
  337. var timeDiff = currentTime - lastKeyPressTime;
  338. lastKeyPressTime = currentTime;
  339. // 如果兩次 Enter 鍵按下的時間差小於閾值,則增加計數器
  340. if (timeDiff <= ENTER_THRESHOLD) {
  341. enterCount++;
  342. // 如果計數器為2,則觸發 API 請求並重置計數器
  343. if (enterCount === 2) {
  344. sendButtonClickHandler();
  345. enterCount = 0;
  346. }
  347. } else {
  348. // 如果時間差大於閾值,則重置計數器
  349. enterCount = 0;
  350. }
  351. } else {
  352. // 如果按下的不是 Enter 鍵,則重置計數器
  353. enterCount = 0;
  354. }
  355. });
  356. function number_format(number, decimals, dec_point, thousands_sep) {
  357. // * example: number_format(1234.56, 2, ',', ' ');
  358. // * return: '1 234,56'
  359. number = (number + '').replace(',', '').replace(' ', '');
  360. var n = !isFinite(+number) ? 0 : +number,
  361. prec = !isFinite(+decimals) ? 0 : Math.abs(decimals),
  362. sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep,
  363. dec = (typeof dec_point === 'undefined') ? '.' : dec_point,
  364. s = '',
  365. toFixedFix = function (n, prec) {
  366. var k = Math.pow(10, prec);
  367. return '' + Math.round(n * k) / k;
  368. };
  369. // Fix for IE parseFloat(0.55).toFixed(0) = 0;
  370. s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.');
  371. if (s[0].length > 3) {
  372. s[0] = s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, sep);
  373. }
  374. if ((s[1] || '').length < prec) {
  375. s[1] = s[1] || '';
  376. s[1] += new Array(prec - s[1].length + 1).join('0');
  377. }
  378. return s.join(dec);
  379. }
  380. var labels = [];
  381. var data = [];
  382. function apiLoading() {
  383. document.getElementById('chartDataLoading').style.display = 'block';
  384. }
  385. function apiHideLoading() {
  386. document.getElementById('chartDataLoading').style.display = 'none';
  387. }
  388. const DISPLAY = true;
  389. const BORDER = true;
  390. const CHART_AREA = true;
  391. const TICKS = true;
  392. var labels = [];
  393. var data = [];
  394. var dataArray;
  395. function generateChart(dataArray) {
  396. if (dataArray.length > 10) {
  397. lineYfontSize.style.display = 'none'
  398. } else {
  399. lineYfontSize.style.display = 'block'
  400. }
  401. // 创建一个空数组来存储 labels 和 data
  402. console.log(dataArray)
  403. // 遍历数据数组
  404. for (var i = 0; i < dataArray.length; i++) {
  405. var item = dataArray[i];
  406. // 遍历当前项的属性
  407. for (var key in item) {
  408. // 如果属性名不在 labels 数组中,并且属性值不是对象,则将属性名添加到 labels 数组中
  409. if (typeof item[key] === 'string') {
  410. labels.push(item[key]);
  411. } else {
  412. if (key === 'x') {
  413. labels.push(String(item[key]));
  414. }
  415. }
  416. if (key === 'y') {
  417. data.push(item[key]);
  418. }
  419. // 如果属性值是数值类型,则将其添加到 data 数组中
  420. // if (typeof item[key] === 'number') {
  421. // data.push(item[key]);
  422. // }
  423. }
  424. }
  425. console.log(data);
  426. dataFirstValue = labels[0];
  427. dataLastValue = labels[labels.length - 1]
  428. console.log('dataFirstValue', dataFirstValue);
  429. console.log('dataLastValue', dataLastValue);
  430. if (myChart) {
  431. console.log('已存在')
  432. myChart.destroy();
  433. }
  434. if (chartType === "doughnut") {
  435. // createChartDoughnut(chartType, data, labels);
  436. // createChartDoughnut2(data, labels)
  437. } else {
  438. createChart(chartType, data, labels);
  439. }
  440. // console.log(data);
  441. console.log(labels);
  442. }
  443. var amChartInstance;
  444. function extractAndGenerateChart(dataArray) {
  445. for (var i = 0; i < dataArray.length; i++) {
  446. var item = dataArray[i];
  447. // 遍历当前项的属性
  448. for (var key in item) {
  449. // 如果属性名不在 labels 数组中,并且属性值不是对象,则将属性名添加到 labels 数组中
  450. if (typeof item[key] === 'string') {
  451. labels.push(item[key]);
  452. }
  453. // 如果属性值是数值类型,则将其添加到 data 数组中
  454. if (typeof item[key] === 'number') {
  455. data.push(item[key]);
  456. }
  457. }
  458. }
  459. // console.log('key', key);
  460. generateBarChart(key, dataArray);
  461. }
  462. // 圓餅圖
  463. function generatePieChart(dataArray, pieFontSize, PieMaxWidth) {
  464. compare_box.style.display = "none";
  465. $('#chartdiv').show();
  466. bgImgelement.style.backgroundImage = chart_bgimg_url;
  467. // chartDiv.style.width = "100%"
  468. chartWhitelement.style.background = "rgba(255,255,255,0.5)"
  469. // Themes begin
  470. am4core.useTheme(am4themes_animated);
  471. // Themes end
  472. // Create chart instance
  473. var chart = am4core.create("chartdiv", am4charts.PieChart);
  474. chart.data = dataArray;
  475. chart.innerRadius = am4core.percent(50);
  476. // Add and configure Series
  477. var pieSeries = chart.series.push(new am4charts.PieSeries());
  478. pieSeries.dataFields.value = "y";
  479. pieSeries.dataFields.category = "x";
  480. pieSeries.slices.template.stroke = am4core.color("#fff");
  481. pieSeries.slices.template.strokeWidth = 2;
  482. pieSeries.slices.template.strokeOpacity = 1;
  483. // Configure labels
  484. pieSeries.labels.template.wrap = true;
  485. console.log('PieMaxWidth', PieMaxWidth);
  486. pieSeries.labels.template.maxWidth = PieMaxWidth;
  487. pieSeries.labels.template.truncate = false;
  488. pieSeries.labels.template.fontSize = 14;
  489. if (typeof PieMaxWidth === 'string') {
  490. console.log('The variable is a string.');
  491. } else {
  492. console.log('The variable is a number.');
  493. }
  494. // Configure label text to wrap and show percentages
  495. // pieSeries.labels.template.adapter.add("textOutput", function (text, target) {
  496. // if (target.dataItem && target.dataItem.values.value.percent) {
  497. // return "[font-size: 14px]" + target.dataItem.category + ": " + target.dataItem.values.value.percent.toFixed(1) + "%";
  498. // }
  499. // return text;
  500. // });
  501. pieSeries.labels.template.adapter.add("textOutput", function (text, target) {
  502. if (target.dataItem && target.dataItem.values.value.percent) {
  503. return "[font-size: " + pieFontSize + "px]" + target.dataItem.category + ": " + target.dataItem.values.value.percent.toFixed(1) + "%";
  504. }
  505. return text;
  506. });
  507. pieSeries.colors.list = [
  508. am4core.color('rgb(171, 51, 49)'),
  509. am4core.color('rgb(34, 83, 149)'),
  510. am4core.color('rgb(79, 148, 65)'),
  511. am4core.color('rgb(217, 195, 105)'),
  512. am4core.color('rgb(142, 124, 180)'),
  513. am4core.color('rgb(211, 183, 144)'),
  514. am4core.color('rgb(83, 84, 84)'),
  515. am4core.color('rgb(229, 147, 152)')
  516. ];
  517. // Ensure labels have background
  518. // pieSeries.labels.template.background.fillOpacity = 1;
  519. console.log(pieSeries.labels.template)
  520. // Set label background color to match corresponding slice color
  521. pieSeries.labels.template.adapter.add("background.fill", function (fill, target) {
  522. return target.dataItem.slice.fill;
  523. });
  524. // This creates initial animation
  525. pieSeries.hiddenState.properties.opacity = 1;
  526. pieSeries.hiddenState.properties.endAngle = -90;
  527. pieSeries.hiddenState.properties.startAngle = -90;
  528. // console.log('調位置')
  529. downloadButton.style.display = "inline-block";
  530. chartTypeBtn.style.display = "inline-block";
  531. }
  532. // var colorEven='#288D97';
  533. // var colorOdd='#427D7E'
  534. function adjustColorBrightness(color, amount) {
  535. let usePound = false;
  536. if (color[0] == "#") {
  537. color = color.slice(1);
  538. usePound = true;
  539. }
  540. let num = parseInt(color, 16);
  541. let r = (num >> 16) + amount;
  542. let g = ((num >> 8) & 0x00FF) + amount;
  543. let b = (num & 0x0000FF) + amount;
  544. if (r > 255) r = 255;
  545. else if (r < 0) r = 0;
  546. if (g > 255) g = 255;
  547. else if (g < 0) g = 0;
  548. if (b > 255) b = 255;
  549. else if (b < 0) b = 0;
  550. return (usePound ? "#" : "") + (r << 16 | g << 8 | b).toString(16).padStart(6, '0');
  551. }
  552. // 柱狀圖
  553. function generateBarChart(key, dataArray) {
  554. console.log('generateBarChart', dataArray)
  555. chartTypeBtn.style.display = "inline-block";
  556. compare_box.style.display = "none";
  557. $('#chartdiv').show();
  558. // var colorEven = document.getElementById('colorEven').value;
  559. // var colorOdd = document.getElementById('colorOdd').value;
  560. var baseColor = document.getElementById('borderColorInputBar').value;
  561. var categoryAxisFzValue = document.getElementById('XfontSizeBar').value;
  562. var valueAxisFzValue = document.getElementById('YfontSizeBar').value;
  563. var colorEven = am4core.color(baseColor);
  564. var colorOdd = adjustColorBrightness(baseColor, -20);
  565. chartDiv.style.fontFamily = "Arial, sans-serif";
  566. chartDiv.style.fontWeight = "900";
  567. bgImgelement.style.backgroundImage = chart_bgimg_url;
  568. chartWhitelement.style.background = "rgba(255,255,255,0.5)"
  569. console.log('labelDependent', labelDependent);
  570. // Themes begin
  571. am4core.useTheme(am4themes_animated);
  572. // Themes end
  573. // Create chart instance
  574. var chart = am4core.create("chartdiv", am4charts.XYChart3D);
  575. chart.data = dataArray;
  576. chart.angle = 30; // 圖表角度
  577. chart.depth = 25; // 圖表深度
  578. let categoryAxis = chart.xAxes.push(new am4charts.CategoryAxis());
  579. categoryAxis.dataFields.category = "x";
  580. categoryAxis.renderer.labels.template.rotation = 0;
  581. categoryAxis.renderer.labels.template.hideOversized = false;
  582. categoryAxis.renderer.minGridDistance = 20; // 間距
  583. // categoryAxis.renderer.labels.template.horizontalCenter = "left";
  584. // categoryAxis.renderer.labels.template.verticalCenter = "middle";
  585. // categoryAxis.tooltip.label.rotation = 90;
  586. // categoryAxis.tooltip.label.horizontalCenter = "right";
  587. // categoryAxis.tooltip.label.verticalCenter = "middle";
  588. // label 換行
  589. let label = categoryAxis.renderer.labels.template;
  590. label.wrap = true;
  591. if (dataArray.length > 5) {
  592. console.log('資料長度5')
  593. label.maxWidth = 60;
  594. } else if (dataArray.length < 7) {
  595. label.maxWidth = 70;
  596. } else {
  597. label.maxWidth = 100;
  598. console.log('資料長度<5')
  599. }
  600. // x軸字體大小
  601. categoryAxis.renderer.labels.template.fontSize = categoryAxisFzValue;
  602. categoryAxis.renderer.cellEndLocation = 0.5; // 減少值可以增加間距
  603. let valueAxis = chart.yAxes.push(new am4charts.ValueAxis());
  604. valueAxis.title.text = labelDependent; // Y軸
  605. valueAxis.title.fontWeight = "bold";
  606. // y軸字體大小
  607. valueAxis.renderer.labels.template.fontSize = valueAxisFzValue;
  608. // Create series
  609. var series = chart.series.push(new am4charts.ColumnSeries3D());
  610. series.dataFields.valueY = 'y';
  611. series.dataFields.categoryX = "x";
  612. series.name = "y";
  613. series.tooltipText = "{categoryX}: [bold]{valueY}[/]";
  614. series.columns.template.fillOpacity = .8;
  615. let columnTemplate = series.columns.template;
  616. columnTemplate.strokeWidth = 2;
  617. columnTemplate.strokeOpacity = 1;
  618. columnTemplate.stroke = am4core.color("#FFFFFF");
  619. // columnTemplate.adapter.add("fill", function (fill, target) {
  620. // return chart.colors.getIndex(target.dataItem.index);
  621. // })
  622. // 設置基數和偶數顏色
  623. columnTemplate.adapter.add("fill", function (fill, target) {
  624. return target.dataItem.index % 2 === 0 ? am4core.color(colorEven) : am4core.color(colorOdd);
  625. });
  626. columnTemplate.adapter.add("stroke", function (stroke, target) {
  627. return chart.colors.getIndex(target.dataItem.index);
  628. })
  629. // // 加上白色線條
  630. // series.columns.template.events.on("validated", function (event) {
  631. // let column = event.target;
  632. // let whiteLine = column.createChild(am4core.Line);
  633. // whiteLine.stroke = am4core.color("#ffffff");
  634. // whiteLine.strokeWidth = 1.3; // 線條寬度
  635. // whiteLine.strokeOpacity = 0.5;// 透明度
  636. // whiteLine.x1 = column.pixelWidth / 1;
  637. // whiteLine.y1 = 0;
  638. // whiteLine.x2 = column.pixelWidth / 1;
  639. // whiteLine.y2 = column.pixelHeight;
  640. // });
  641. chart.cursor = new am4charts.XYCursor();
  642. chart.cursor.lineX.strokeOpacity = 0;
  643. chart.cursor.lineY.strokeOpacity = 0;
  644. categoryAxis.renderer.grid.template.strokeOpacity = 0; // 隱藏 X 軸
  645. // valueAxis.renderer.grid.template.strokeOpacity = 0; // 隱藏 Y 軸
  646. // valueAxis.renderer.line.strokeOpacity = 0;
  647. // LineSeries 底部線條
  648. var lineSeries = chart.series.push(new am4charts.LineSeries());
  649. lineSeries.dataFields.valueY = "bottom";
  650. lineSeries.dataFields.categoryX = "0";
  651. lineSeries.stroke = am4core.color("#FFFFFF")
  652. lineSeries.strokeWidth = 2;
  653. lineSeries.strokeOpacity = 1
  654. var bottomData = [];
  655. for (var i = 0; i < dataArray.length; i++) {
  656. bottomData.push({ "x": dataArray[i].x, "bottom": 0 });
  657. }
  658. lineSeries.data = bottomData;
  659. downloadButton.style.display = "inline-block";
  660. chartTypeBtn.style.display = "inline-block";
  661. chartTypeBtn.style.opacity = "1";
  662. // 底部線條
  663. // let rectElements = document.querySelectorAll("rect");
  664. // // let widthValue = 0;
  665. // let fifthRectElement = rectElements[3];
  666. // // fifthRectElement.style.position = "relative";
  667. // setTimeout(() => {
  668. // let width = fifthRectElement.getAttribute("width");
  669. // // widthValue = parseFloat(width);
  670. // console.log('rectElements', rectElements);
  671. // console.log('fifthRectElement', fifthRectElement);
  672. // console.log('width', width);
  673. // let line = document.createElement("div");
  674. // line.style.position = "absolute";
  675. // line.style.bottom = "162px";
  676. // line.style.right = "40px";
  677. // line.style.width = `${parseFloat(width)}px`;
  678. // line.style.height = "2px";
  679. // line.style.backgroundColor = "#000000";
  680. // document.getElementById("chartdiv").appendChild(line);
  681. // }, 10)
  682. // end am4core.ready()
  683. }
  684. function handleClick(element) {
  685. const Clickvalue = element.dataset.value;
  686. console.log(Clickvalue); // 123
  687. get_data(Clickvalue);
  688. }
  689. // 圖表類型
  690. var chartTypeBtn = document.getElementById("chartType");
  691. chartTypeBtn.addEventListener('change', function () {
  692. const selectedValue = this.value;
  693. console.log('選擇的圖表類型:', selectedValue);
  694. // 在此处添加处理选定图表类型的代码
  695. if (selectedValue === 'line') {
  696. // 处理折线图
  697. console.log('處理折線圖', dataArray);
  698. $('#chartdiv').hide();
  699. chartType = 'line';
  700. if (myChart) {
  701. data = [];
  702. labels = [];
  703. myChart.destroy();
  704. }
  705. generateChart(dataArray);
  706. } else if (selectedValue === 'bar') {
  707. chartType = 'bar';
  708. $('#textToChart').hide();
  709. // 处理柱状图
  710. console.log('處理柱狀圖', dataArray);
  711. extractAndGenerateChart(dataArray);
  712. } else if (selectedValue === 'doughnut') {
  713. chartType = 'doughnut';
  714. console.log('處理圓餅圖', dataArray);
  715. unit_value.textContent = "";
  716. $('#textToChart').hide();
  717. generatePieChart(dataArray, pieFontSize, PieMaxWidth)
  718. // 处理圆饼图
  719. }
  720. });
  721. var downloadButton = document.getElementById("downloadButton");
  722. // downloadButton.style.display = 'none';
  723. // 添加點擊事件監聽器
  724. downloadButton.addEventListener('click', function () {
  725. setTimeout(function () {
  726. html2canvas(document.getElementById('data_chart_box')).then(function (canvas) {
  727. // // 獲取圖片資料 URL
  728. // var imageData = canvasPng.toDataURL("image/png");
  729. // // 創建下載連結
  730. // var link = document.createElement('a');
  731. // link.download = 'chart.png'; // 下載的檔案名稱
  732. // link.href = imageData; // 圖片資料 URL
  733. // // 模擬點擊下載連結
  734. // link.click();
  735. // 創建一個&lt;a&gt;元素
  736. const link = document.createElement('a');
  737. // 將 Canvas 轉換為 Data URL
  738. link.href = canvas.toDataURL('image/png');
  739. // 設置下載文件名
  740. link.download = 'chart.png';
  741. // 模擬點擊下載
  742. link.click();
  743. });
  744. }, 1000); // 等待 1 秒钟
  745. });
  746. var pieChartColors = [
  747. 'rgb(171, 51, 49)',
  748. 'rgb(34, 83, 149)',
  749. 'rgb(79, 148, 65)',
  750. 'rgb(217, 195, 105)',
  751. 'rgb(142, 124, 180)',
  752. 'rgb(211, 183, 144)',
  753. 'rgb(83, 84, 84)',
  754. 'rgb(229, 147, 152)'
  755. ];
  756. function createChartDoughnut2(data, labels) {
  757. const chartData = {
  758. type: 'outlabeledPie',
  759. data: {
  760. labels: labels,
  761. datasets: [
  762. {
  763. data: data,
  764. borderWidth: borderWidthValue,
  765. fill: false,
  766. backgroundColor: pieChartColors,
  767. },
  768. ],
  769. },
  770. options: {
  771. plugins: {
  772. legend: false,
  773. outlabels: {
  774. text: '%l %p',
  775. color: 'white',
  776. stretch: 35,
  777. font: {
  778. resizable: true,
  779. family: 'Arial',
  780. size: 48,
  781. weight: 'bold',
  782. style: 'italic',
  783. },
  784. },
  785. },
  786. },
  787. };
  788. const devicePixelRatio = 4;
  789. var chartUrl = `https://quickchart.io/chart?c=${encodeURIComponent(JSON.stringify(chartData))}&devicePixelRatio=${devicePixelRatio}&f=png&fontsize=20`;
  790. // 获取目标 div 元素
  791. const targetDiv = document.getElementById('data_chartJs_box');
  792. // 创建一个 img 元素来显示图表
  793. const chartImg = document.createElement('img');
  794. chartImg.src = chartUrl;
  795. chartImg.classList.add('outlabeled_img');
  796. // 清空目标 div 元素
  797. targetDiv.innerHTML = '';
  798. // 将图表 img 元素插入到目标 div 中
  799. targetDiv.appendChild(chartImg);
  800. console.log(chart_bgimg_url);
  801. bgImgelement.style.backgroundImage = chart_bgimg_url;
  802. chartWhitelement.style.background = "rgba(255,255,255,0.5)"
  803. }
  804. // 版型二源餅圖
  805. // // 创建 Chart.js 图表
  806. function createChartDoughnut(chartType, data, labels) {
  807. $('#textToChart').show();
  808. canvasPng.style.maxWidth = '450px';
  809. canvasPng.style.maxHeight = '450px';
  810. var windowWidth = window.innerWidth || document.documentElement.clientWidth;
  811. var canvasWidth = Math.min(500, windowWidth); // 限制最大宽度为 500px
  812. canvasPng.style.width = canvasWidth + 'px'; // 设置 canvas 宽度
  813. canvasPng.style.marginLeft = 'auto'; // 左外边距自动计算
  814. canvasPng.style.marginRight = 'auto'; // 右外边距自动计算
  815. var ctx = document.getElementById("textToChart").getContext('2d');
  816. myChart = new Chart(ctx, {
  817. type: chartType,
  818. data: {
  819. labels: labels,
  820. datasets: [{
  821. strokeColor: "rgba(220,220,220,1)",
  822. StrokeWidth: 5,
  823. data: data,
  824. borderWidth: borderWidthValue,
  825. pointRadius: 0,
  826. pointBorderColor: '#fff',
  827. pointBorderWidth: 3,
  828. pointHoverRadius: 0,
  829. fill: false,
  830. backgroundColor: pieChartColors,
  831. // barPercentage: 0.5,
  832. // categoryPercentage: 0.5
  833. }]
  834. },
  835. options: {
  836. // responsive: true, // 啟用響應式
  837. maintainAspectRatio: true,
  838. responsive: true,
  839. aspectRatio: 1,
  840. plugins: {
  841. legend: {
  842. display: false,
  843. },
  844. datalabels: {
  845. color: '#fff', // 数据标签的颜色
  846. anchor: 'end', // 数据标签的位置
  847. align: 'start', // 数据标签的对齐方式
  848. font: {
  849. size: 14, // 数据标签的字体大小
  850. },
  851. }
  852. },
  853. scales: {
  854. x: {
  855. display: false, // 显示 x 轴
  856. grid: {
  857. display: false,
  858. lineWidth: 5,
  859. color: '#584B3D'
  860. },
  861. ticks: {
  862. textStrokeColor: '#fff',
  863. textStrokeWidth: 5,
  864. font: {
  865. display: false,
  866. family: 'Arial', // 设置字体
  867. size: XfontSizeValue, // 设置字体大小
  868. weight: 'bold', // 设置字体粗细
  869. fontColor: 'rgba(255,255,255,0.8)', // X-axis font color
  870. shadowColor: 'rgba(0, 0, 0, 0.5)', // Shadow color
  871. shadowBlur: 10, // Shadow blur level
  872. shadowOffsetX: 5, // Horizontal shadow offset
  873. shadowOffsetY: 5
  874. },
  875. },
  876. },
  877. y: {
  878. display: false,
  879. beginAtZero: false,
  880. grid: {
  881. display: false,
  882. lineWidth: 5,
  883. color: '#584B3D'
  884. },
  885. ticks: {
  886. textStrokeColor: '#fff',
  887. textStrokeWidth: 5,
  888. font: {
  889. family: 'Arial', // 設置字體
  890. size: XfontSizeValue, // 設置字體大小
  891. weight: 'bold', // 設置字體粗細
  892. color: 'rgba(255,255,255,0.8)', // Y-axis 字體顏色
  893. shadowColor: 'rgba(0, 0, 0, 0.5)', // 陰影顏色
  894. shadowBlur: 10, // 陰影模糊級別
  895. shadowOffsetX: 5, // 水平陰影偏移
  896. shadowOffsetY: 5 // 垂直陰影偏移
  897. },
  898. }
  899. }
  900. },
  901. layout: {
  902. padding: {
  903. left: 50, // 调整图表左边距
  904. right: 50, // 调整图表右边距
  905. top: 10,
  906. bottom: 10,
  907. }
  908. },
  909. },
  910. });
  911. console.log(chart_bgimg_url);
  912. bgImgelement.style.backgroundImage = chart_bgimg_url;
  913. chartWhitelement.style.background = "rgba(255,255,255,0.5)"
  914. }
  915. var chartJsBox = document.getElementById('data_chartJs_box');
  916. function createTable(dataArray, unit, Label_dependent_variable, Label_independent_variable,) {
  917. $('#chartdiv').hide();
  918. $('#textToChart').hide();
  919. chartTitle.style.padding = "0px 0px 0px 30px";
  920. bgImgelement.style.paddingTop = "10px";
  921. var table = document.createElement('table');
  922. table.classList.add('table', 'table_template', 'dynamic-table'); // 添加 Bootstrap 的 table 样式,如果你在使用 Bootstrap
  923. // 创建表头
  924. var thead = table.createTHead();
  925. var headerRow = thead.insertRow();
  926. // Object.keys(dataArray[0]).forEach(function (key) {
  927. // var header = headerRow.insertCell();
  928. // header.textContent = key;
  929. // });
  930. var yearHeader = headerRow.insertCell();
  931. yearHeader.textContent = Label_independent_variable;
  932. var avgPriceHeader = headerRow.insertCell();
  933. avgPriceHeader.textContent = Label_dependent_variable;
  934. // 创建表格主体
  935. var tbody = table.createTBody();
  936. dataArray.forEach(function (item) {
  937. console.log(item)
  938. var row = tbody.insertRow();
  939. // var cell1 = row.insertCell();
  940. // cell1.textContent = item.year;
  941. // cell1.classList.add('year-class'); // 为年份单元格添加类
  942. // var cell2 = row.insertCell();
  943. Object.keys(item).forEach(function (key, index) {
  944. var cell = row.insertCell();
  945. if (index === 0) { // If it's the first cell, add 'year-class'
  946. cell.textContent = item[key];
  947. cell.classList.add('year-class');
  948. } else { // Otherwise, add 'average-class'
  949. if (key === 'Average_Close') {
  950. // cell.textContent = item[key].toFixed(2) + unit;
  951. cell.innerHTML = item[key].toFixed(2) + '<span class="unit_table">' + unit + '</span>';
  952. } else {
  953. // cell.textContent = item[key];
  954. // cell.textContent = item[key].toFixed(2) + unit;
  955. cell.innerHTML = item[key].toFixed(2) + '<span class="unit_table">' + unit + '</span>';
  956. }
  957. cell.classList.add('average-class');
  958. }
  959. });
  960. // console.log(item.avg_price.toFixed(2))
  961. // cell.textContent = item[key].toFixed(2) + unit;
  962. // cell2.classList.add('average-class'); // 为年份单元格添加类
  963. });
  964. // 获取包含表格的 div 元素
  965. bgImgelement.style.backgroundImage = chart_bgimg_url;
  966. img_box.style.bottom = '60px';
  967. img_box.style.right = '5px';
  968. document.getElementById('img_box_url').style.width = "180px";
  969. // chartWhitelement.style.background = "rgba(255,255,255,0.5)"
  970. // 将表格添加到指定的 div 元素中
  971. chartJsBox.appendChild(table);
  972. unit_table_value = document.querySelectorAll('.unit_table');
  973. downloadButton.style.display = "inline-block";
  974. chartTypeBtn.style.display = "inline-block";
  975. chartTypeBtn.style.opacity = "0";
  976. }
  977. function getDatalabelsConfig(dataLength) {
  978. if (dataLength < 10) {
  979. return {
  980. formatter: function (value, context) {
  981. return value + ' unit'; // Add unit if data length is less than 10
  982. },
  983. textStrokeColor: '#fff',
  984. textStrokeWidth: 5,
  985. color: '#584B3D',
  986. font: {
  987. size: YfontSizeValue,
  988. },
  989. anchor: 'end',
  990. align: 'end',
  991. };
  992. } else {
  993. return null; // No datalabels if data length is 10 or more
  994. }
  995. }
  996. var pointRadiusValue = 0;
  997. var pointHoverRadiusValue = 0;
  998. // 版型一折線圖
  999. // // 创建 Chart.js 图表
  1000. function createChart(chartType, data, labels) {
  1001. $('#textToChart').show();
  1002. canvasPng.style.maxWidth = '';
  1003. canvasPng.style.maxHeight = '';
  1004. console.log('繪製圖表', data, labels);
  1005. if (data.length < 15) {
  1006. pointRadiusValue = 5;
  1007. pointHoverRadiusValue = 8;
  1008. togglePoints.checked = true;
  1009. }
  1010. const datalabelsConfig = data.length <= 15 ? {
  1011. formatter: function (value, context) {
  1012. // if (context.dataIndex === 0) {
  1013. // return '';
  1014. // }
  1015. // if (typeof value === 'number' && value.toString().includes('.')) {
  1016. // value = value.toFixed(4);
  1017. // }
  1018. // return value;
  1019. return value;
  1020. },
  1021. textStrokeColor: '#fff',
  1022. textStrokeWidth: 5,
  1023. color: '#584B3D',
  1024. font: {
  1025. size: YfontSizeValue,
  1026. },
  1027. anchor: 'end',
  1028. align: 'top'
  1029. } : null;
  1030. ctx = document.getElementById("textToChart");
  1031. myChart = new Chart(ctx, {
  1032. type: chartType,
  1033. data: {
  1034. labels: labels,
  1035. datasets: [{
  1036. label: stocknumber,
  1037. strokeColor: "rgba(220,220,220,1)",
  1038. StrokeWidth: 5,
  1039. data: data,
  1040. borderWidth: borderWidthValue,
  1041. pointRadius: pointRadiusValue,
  1042. pointBorderColor: '#fff',
  1043. pointBorderWidth: 3,
  1044. pointHoverRadius: pointHoverRadiusValue,
  1045. fill: false,
  1046. backgroundColor: chartColor,
  1047. borderColor: chartColor,
  1048. // barPercentage: 0.5,
  1049. // categoryPercentage: 0.5
  1050. }]
  1051. },
  1052. options: {
  1053. // responsive: true, // 啟用響應式
  1054. maintainAspectRatio: false,
  1055. plugins: {
  1056. chart3d: {
  1057. enabled: true, // 啟用 3D 插件
  1058. alpha: 25, // 圖表繞 x 軸的旋轉角度
  1059. beta: 25, // 圖表繞 y 軸的旋轉角度
  1060. depth: 15 // 圖表的深度
  1061. },
  1062. datalabels: datalabelsConfig,
  1063. // datalabels: {
  1064. // formatter: function (value, context) {
  1065. // // 添加单位
  1066. // return value;
  1067. // },
  1068. // textStrokeColor: '#fff',
  1069. // textStrokeWidth: 5,
  1070. // color: '#584B3D',
  1071. // font: {
  1072. // size: YfontSizeValue,
  1073. // },
  1074. // anchor: 'end',
  1075. // align: 'end',
  1076. // },
  1077. // datalabels: null,
  1078. // datalabels: data.length <= 10 ? {
  1079. // formatter: function (value, context) {
  1080. // // 添加单位
  1081. // return value + ' ' + unit;
  1082. // },
  1083. // textStrokeColor: '#fff',
  1084. // textStrokeWidth: 5,
  1085. // color: '#584B3D',
  1086. // font: {
  1087. // size: YfontSizeValue,
  1088. // },
  1089. // anchor: 'end',
  1090. // align: 'end',
  1091. // } : null,
  1092. customLabels: null,
  1093. legend: {
  1094. display: false,
  1095. },
  1096. // subtitle: {
  1097. // display: true,
  1098. // align: 'left',
  1099. // position: 'top',
  1100. // text: 'Custom Chart Subtitle'
  1101. // },
  1102. // afterDatasetsDraw(chart) {
  1103. // var ctx = chart.ctx;
  1104. // var xAxis = chart.scales.x;
  1105. // var yAxis = chart.scales.y;
  1106. // var dataj = myChart.data.datasets[0].data;
  1107. // console.log('after', dataj)
  1108. // ctx.save();
  1109. // ctx.strokeStyle = '#000'; // 虚线颜色
  1110. // ctx.lineWidth = 1; // 虚线宽度
  1111. // ctx.setLineDash([5, 5]); // 设置虚线样式,[虚线段长度, 间隔长度]
  1112. // dataj.forEach(function (value, index) {
  1113. // var xPos = xAxis.getPixelForValue(labels[index]); // 获取 x 轴位置
  1114. // var yPos = yAxis.getPixelForValue(value); // 获取 y 轴位置
  1115. // // console.log(xPos)
  1116. // // 绘制虚线
  1117. // // ctx.beginPath();
  1118. // // ctx.moveTo(xPos, yPos);
  1119. // // ctx.lineTo(xPos, xAxis.bottom);
  1120. // // ctx.stroke();
  1121. // var xLineEnd = Math.min(yPos, yAxis.bottom);
  1122. // // console.log('第' + index + '條線', xPos, yPos, 'xLineEnd', xLineEnd, 'yAxis.getPixelForValue(value)', yAxis.getPixelForValue(value));
  1123. // // console.log('yAxis.getPixelForValue(value)', yAxis.getPixelForValue(value))
  1124. // // 绘制虚线
  1125. // ctx.beginPath();
  1126. // ctx.moveTo(xPos, yAxis.getPixelForValue(value));
  1127. // ctx.lineTo(xPos, xAxis.top);
  1128. // ctx.stroke();
  1129. // // 添加日期标签
  1130. // ctx.fillStyle = '#000'; // 文字颜色
  1131. // ctx.textAlign = 'center';
  1132. // // ctx.fillText(labels[index], xPos, yAxis.bottom + 20); // 将日期标签绘制在虚线下方
  1133. // });
  1134. // ctx.restore();
  1135. // }
  1136. },
  1137. scales: {
  1138. x: {
  1139. display: displayXaxes, // 显示 x 轴
  1140. grid: {
  1141. display: false,
  1142. lineWidth: 5,
  1143. color: '#584B3D'
  1144. },
  1145. ticks: {
  1146. textStrokeColor: '#fff',
  1147. textStrokeWidth: 5,
  1148. font: {
  1149. display: false,
  1150. family: 'Arial', // 设置字体
  1151. size: XfontSizeValue, // 设置字体大小
  1152. weight: 'bold', // 设置字体粗细
  1153. fontColor: 'rgba(255,255,255,0.8)', // X-axis font color
  1154. shadowColor: 'rgba(0, 0, 0, 0.5)', // Shadow color
  1155. shadowBlur: 10, // Shadow blur level
  1156. shadowOffsetX: 5, // Horizontal shadow offset
  1157. shadowOffsetY: 5
  1158. },
  1159. },
  1160. },
  1161. y: {
  1162. display: true,
  1163. beginAtZero: false,
  1164. grid: {
  1165. grid: {
  1166. display: true, // 显示 y 轴网格线
  1167. lineWidth: 1, // 网格线宽度
  1168. color: '#C0C5CC' // 网格线颜色
  1169. },
  1170. },
  1171. ticks: {
  1172. textStrokeColor: '#fff',
  1173. textStrokeWidth: 5,
  1174. font: {
  1175. family: 'Arial', // 設置字體
  1176. size: XfontSizeValue, // 設置字體大小
  1177. weight: 'bold', // 設置字體粗細
  1178. color: 'rgba(255,255,255,0.8)', // Y-axis 字體顏色
  1179. shadowColor: 'rgba(0, 0, 0, 0.5)', // 陰影顏色
  1180. shadowBlur: 10, // 陰影模糊級別
  1181. shadowOffsetX: 5, // 水平陰影偏移
  1182. shadowOffsetY: 5 // 垂直陰影偏移
  1183. },
  1184. }
  1185. }
  1186. },
  1187. layout: {
  1188. padding: {
  1189. left: 50, // 调整图表左边距
  1190. right: 50, // 调整图表右边距
  1191. top: 40,
  1192. bottom: 10,
  1193. }
  1194. },
  1195. },
  1196. });
  1197. console.log('第一次', myChart.options.legend)
  1198. // 注册 afterDraw 事件
  1199. // Chart.register({
  1200. // id: 'afterDraw',
  1201. // afterDraw: function (chart) {
  1202. // // console.log('處發', chart)
  1203. // // 在这里添加你的绘制代码
  1204. // var ctx = chart.ctx;
  1205. // var xAxis = chart.scales.x;
  1206. // var yAxis = chart.scales.y;
  1207. // var dataj = myChart.data.datasets[0].data;
  1208. // console.log('after', dataj)
  1209. // ctx.save();
  1210. // ctx.strokeStyle = '#000'; // 虚线颜色
  1211. // ctx.lineWidth = 1; // 虚线宽度
  1212. // ctx.setLineDash([5, 5]); // 设置虚线样式,[虚线段长度, 间隔长度]
  1213. // dataj.forEach(function (value, index) {
  1214. // var xPos = xAxis.getPixelForValue(labels[index]); // 获取 x 轴位置
  1215. // var yPos = yAxis.getPixelForValue(value); // 获取 y 轴位置
  1216. // // console.log(xPos)
  1217. // // 绘制虚线
  1218. // // ctx.beginPath();
  1219. // // ctx.moveTo(xPos, yPos);
  1220. // // ctx.lineTo(xPos, xAxis.bottom);
  1221. // // ctx.stroke();
  1222. // var xLineEnd = Math.min(yPos, yAxis.bottom);
  1223. // // console.log('第' + index + '條線', xPos, yPos, 'xLineEnd', xLineEnd, 'yAxis.getPixelForValue(value)', yAxis.getPixelForValue(value));
  1224. // // console.log('yAxis.getPixelForValue(value)', yAxis.getPixelForValue(value))
  1225. // // 绘制虚线
  1226. // ctx.beginPath();
  1227. // ctx.moveTo(xPos, yAxis.getPixelForValue(value));
  1228. // ctx.lineTo(xPos, xAxis.top);
  1229. // ctx.stroke();
  1230. // // 添加日期标签
  1231. // ctx.fillStyle = '#000'; // 文字颜色
  1232. // ctx.textAlign = 'center';
  1233. // // ctx.fillText(labels[index], xPos, yAxis.bottom + 20); // 将日期标签绘制在虚线下方
  1234. // });
  1235. // ctx.restore();
  1236. // }
  1237. // });
  1238. console.log(chart_bgimg_url);
  1239. bgImgelement.style.backgroundImage = chart_bgimg_url;
  1240. chartWhitelement.style.background = "rgba(255,255,255,0.5)";
  1241. downloadButton.style.display = "inline-block";
  1242. chartTypeBtn.style.display = "inline-block";
  1243. chartTypeBtn.style.opacity = "1";
  1244. compare_box.style.display = "flex";
  1245. }
  1246. // createChart(chartType);
  1247. // createChart(chartType)
  1248. const ChartOptions = document.querySelectorAll('input[name="ChartOptions"]');
  1249. ChartOptions.forEach(button => {
  1250. button.addEventListener('click', function () {
  1251. // console.log(this.value);
  1252. chartType = this.value;
  1253. console.log(chartType);
  1254. if (myChart !== null) {
  1255. myChart.destroy();
  1256. data = [];
  1257. labels = [];
  1258. }
  1259. if (chartType === 'line') {
  1260. $('#chartdiv').hide();
  1261. generateChart(dataArray);
  1262. } else {
  1263. $('#textToChart').hide();
  1264. extractAndGenerateChart(dataArray);
  1265. }
  1266. // createChart(chartType, data, labels);
  1267. });
  1268. });
  1269. // 表格字體
  1270. var fontSizeInput = document.getElementById('table_fontSize');
  1271. // 添加事件监听器
  1272. fontSizeInput.addEventListener('input', function () {
  1273. // 获取输入框的值
  1274. var fontSize = fontSizeInput.value;
  1275. // 获取动态创建的表格元素
  1276. var dynamicTable = document.querySelector('.dynamic-table');
  1277. // 如果表格存在,则调整其字体大小
  1278. if (dynamicTable) {
  1279. dynamicTable.style.fontSize = fontSize + 'px';
  1280. }
  1281. });
  1282. // 圓餅圖字體
  1283. var pieFontSizeInput = document.getElementById('pie_fontSize');
  1284. // 添加事件监听器
  1285. pieFontSizeInput.addEventListener('input', function () {
  1286. // 获取输入框的值
  1287. pieFontSize = pieFontSizeInput.value;
  1288. console.log('圓餅圖字體', pieFontSize);
  1289. if (pieFontSize) {
  1290. generatePieChart(dataArray, pieFontSize, PieMaxWidth);
  1291. } else {
  1292. alert("Please enter a valid font size.");
  1293. }
  1294. // 如果表格存在,则调整其字体大小
  1295. // if (dynamicTable) {
  1296. // dynamicTable.style.fontSize = fontSize + 'px';
  1297. // }
  1298. });
  1299. document.getElementById('PieMaxWidthRange').addEventListener('input', function () {
  1300. PieMaxWidth = Number(document.getElementById('PieMaxWidthRange').value);
  1301. console.log('圓餅圖', PieMaxWidth)
  1302. generatePieChart(dataArray, pieFontSize, PieMaxWidth);
  1303. });
  1304. // 是否顯示point
  1305. var togglePoints = document.getElementById('togglePoints');
  1306. togglePoints.addEventListener('change', function () {
  1307. console.log('checked', "change")
  1308. if (this.checked) {
  1309. myChart.data.datasets[0].pointRadius = 5;
  1310. myChart.data.datasets[0].pointHoverRadius = 8;
  1311. } else {
  1312. myChart.data.datasets[0].pointRadius = 0;
  1313. myChart.data.datasets[0].pointHoverRadius = 0;
  1314. }
  1315. myChart.update();
  1316. });
  1317. // 單位
  1318. // =========================
  1319. var unitInput = document.getElementById('unit_data');
  1320. var unit_value = document.querySelector('.unit');
  1321. // console.log('單位', unitInput)
  1322. unitInput.addEventListener('input', function () {
  1323. // unitInput.value = unit_value.textContent;
  1324. if (chartType === 'table') {
  1325. // unit_table_value.textContent = this.value;
  1326. unit_table_value.forEach(span => {
  1327. span.textContent = this.value;
  1328. });
  1329. } else {
  1330. unit_value.textContent = '單位:' + this.value;
  1331. }
  1332. });
  1333. // ==========================
  1334. // y軸字體大小-折線圖
  1335. // ==========================
  1336. var YfontSize = document.getElementById('YfontSize');
  1337. YfontSize.addEventListener('input', function () {
  1338. YfontSizeValue = YfontSize.value;
  1339. if (myChart) {
  1340. myChart.destroy();
  1341. }
  1342. createChart(chartType, data, labels);
  1343. });
  1344. // ==========================
  1345. // x軸字體大小-折線圖
  1346. // ==========================
  1347. var XfontSize = document.getElementById('XfontSize');
  1348. XfontSize.addEventListener('input', function () {
  1349. XfontSizeValue = XfontSize.value;
  1350. console.log(XfontSizeValue)
  1351. if (myChart) {
  1352. myChart.destroy();
  1353. }
  1354. createChart(chartType, data, labels);
  1355. });
  1356. // ==========================
  1357. // x軸字體大小-柱狀圖
  1358. // ==========================
  1359. var XfontSizeBar = document.getElementById('XfontSizeBar');
  1360. XfontSizeBar.addEventListener('input', function () {
  1361. extractAndGenerateChart(dataArray);
  1362. });
  1363. // ==========================
  1364. // y軸字體大小-柱狀圖
  1365. // ==========================
  1366. var YfontSizeBar = document.getElementById('YfontSizeBar');
  1367. YfontSizeBar.addEventListener('input', function () {
  1368. extractAndGenerateChart(dataArray);
  1369. });
  1370. // ==========================
  1371. // 線條顏色-柱狀圖
  1372. // =========================
  1373. const colorInputBar = document.getElementById('borderColorInputBar');
  1374. // 添加事件监听器,当颜色选择发生变化时触发
  1375. colorInputBar.addEventListener('input', function () {
  1376. extractAndGenerateChart(dataArray);
  1377. });
  1378. // =========================
  1379. // 線條粗細
  1380. // =========================
  1381. var rangeInput = document.getElementById('borderWidthRange');
  1382. var rangeInputSpan = document.getElementById('borderWidthRangeValue');
  1383. var borderWidthValue;
  1384. rangeInputSpan.textContent = rangeInput.value;
  1385. // 添加事件监听器,当滑动条的值发生改变时更新显示的值
  1386. rangeInput.addEventListener('input', function () {
  1387. // 获取滑动条的当前值
  1388. borderWidthValue = rangeInput.value;
  1389. console.log(borderWidthValue);
  1390. rangeInputSpan.textContent = borderWidthValue;
  1391. if (myChart) {
  1392. myChart.destroy();
  1393. }
  1394. createChart(chartType, data, labels);
  1395. // myChart.data.datasets[0].borderWidth = borderWidthValue;
  1396. });
  1397. // =========================
  1398. // 線條顏色-折線圖
  1399. // =========================
  1400. const colorInput = document.getElementById('borderColorInput');
  1401. // 添加事件监听器,当颜色选择发生变化时触发
  1402. colorInput.addEventListener('input', function () {
  1403. // 获取当前选择的颜色值
  1404. chartColor = colorInput.value;
  1405. if (myChart) {
  1406. myChart.destroy();
  1407. }
  1408. console.log(chartColor);
  1409. createChart(chartType, data, labels);
  1410. });
  1411. // =========================
  1412. // 模板樣式
  1413. // =========================
  1414. // JavaScript
  1415. document.addEventListener("DOMContentLoaded", function () {
  1416. // 獲取所有帶有 templateImg class 的圖像元素
  1417. var templateImgs = document.querySelectorAll('.templateImg');
  1418. // 為每個圖像元素添加點擊事件監聽器
  1419. templateImgs.forEach(function (img) {
  1420. img.addEventListener('click', function () {
  1421. // 在點擊時印出圖像元素的 value 屬性值
  1422. console.log(this.getAttribute('value'));
  1423. });
  1424. });
  1425. });
  1426. // =========================
  1427. var bgImgelement = document.getElementById('data_chart_box');
  1428. var chartWhitelement = document.getElementById('data_chartJs_box');
  1429. // 背景樣式
  1430. // =========================
  1431. // JavaScript
  1432. document.addEventListener("DOMContentLoaded", function () {
  1433. // 獲取所有帶有 templateImg class 的圖像元素
  1434. var bgImgs = document.querySelectorAll('.bgImg');
  1435. // 為每個圖像元素添加點擊事件監聽器
  1436. bgImgs.forEach(function (img) {
  1437. img.addEventListener('click', function () {
  1438. // 在點擊時印出圖像元素的 value 屬性值
  1439. console.log(this.getAttribute('value'));
  1440. var bgImgUrl = this.getAttribute('value');
  1441. chart_bgimg_url = 'url(' + bgImgUrl + ')';
  1442. if (bgImgUrl === './img/bg07.webp') {
  1443. chartTitle.style.color = "#ffff";
  1444. chartTitle.style.padding = '0px'
  1445. } else {
  1446. chartTitle.style.color = "#1c2d6d";
  1447. }
  1448. bgImgelement.style.backgroundImage = chart_bgimg_url;
  1449. // bgImgelement.style.backgroundSize = 'cover'; // 調整背景圖片大小
  1450. // bgImgelement.style.backgroundPosition = 'center'; // 調整背景圖片位置
  1451. // bgImgelement.style.backgroundRepeat = 'no-repeat'; // 調整背景圖片重複
  1452. });
  1453. });
  1454. });
  1455. // =========================
  1456. const radioButtons = document.querySelectorAll('input[name="inlineRadioOptions"]');
  1457. var chartTitle = document.querySelector('.chart_title');
  1458. radioButtons.forEach(button => {
  1459. button.addEventListener('click', function () {
  1460. if (this.value === '0') {
  1461. chartTitle.style.textAlign = 'left';
  1462. } else if (this.value === '1') {
  1463. chartTitle.style.textAlign = 'center';
  1464. } else if (this.value === '2') {
  1465. chartTitle.style.textAlign = 'right';
  1466. }
  1467. });
  1468. });
  1469. // 圖表標題
  1470. var keywordInput = document.getElementById('title_data');
  1471. // 初始时将输入框的值设置为标题的文本内容
  1472. keywordInput.value = chartTitle.textContent;
  1473. // 监听输入框的输入事件,实现内容同步更新
  1474. keywordInput.addEventListener('input', function () {
  1475. chartTitle.textContent = this.value;
  1476. });
  1477. // 標題字體大小
  1478. // ==========================
  1479. var TitlefontSize = document.getElementById('TitlefontSize');
  1480. TitlefontSize.addEventListener('input', function () {
  1481. var TitlefontSizeValue = TitlefontSize.value;
  1482. chartTitle.style.fontSize = TitlefontSizeValue + 'px';;
  1483. });
  1484. // 標題字體顏色
  1485. var stocknumber;
  1486. // ==========================
  1487. let labelDependent = ""; // 圖表左側 Label
  1488. function get_data(input_text_value) {
  1489. clickExample.style.display = 'none'
  1490. // 重新创建取消令牌和源
  1491. cancelToken = axios.CancelToken;
  1492. source = cancelToken.source();
  1493. // inputField.value = "";
  1494. apiLoading();
  1495. var existingTable = chartJsBox.querySelector('table');
  1496. downloadButton.style.display = "none";
  1497. if (chartDiv.childElementCount != 0) {
  1498. data = [];
  1499. labels = [];
  1500. console.log('已存在')
  1501. chartTitle.textContent = "";
  1502. unit_value.textContent = "";
  1503. bgImgelement.style.backgroundImage = "";
  1504. chartWhitelement.style.background = "";
  1505. document.getElementById('img_box_url').src = "";
  1506. }
  1507. if (existingTable) {
  1508. unit_value.textContent = "";
  1509. chartJsBox.removeChild(existingTable);
  1510. chartTitle.textContent = "";
  1511. bgImgelement.style.backgroundImage = "";
  1512. chartWhitelement.style.background = "";
  1513. document.getElementById('img_box_url').src = "";
  1514. }
  1515. if (myChart) {
  1516. unit_value.textContent = "";
  1517. data = [];
  1518. labels = [];
  1519. chartTitle.textContent = "";
  1520. bgImgelement.style.backgroundImage = "";
  1521. chartWhitelement.style.background = "";
  1522. myChart.destroy();
  1523. document.getElementById('img_box_url').src = "";
  1524. }
  1525. const apiUrl = `https://cmm.ai:8080/answer_with_token?token=${accessToken}&question=${input_text_value}`;
  1526. axios.get(apiUrl, {
  1527. cancelToken: source.token // 将取消令牌传递给 Axios 请求
  1528. })
  1529. .then(response => {
  1530. apiHideLoading();
  1531. console.log(response);
  1532. if (response.data.data == "Failed to generate chart!") {
  1533. alert('無法生成圖表')
  1534. return
  1535. } else {
  1536. var chart_info = response.data.chart_info.Title;
  1537. chartType = response.data.chart_info.Chart_type;
  1538. var finance_img_url = response.data.imageUrl_info.imageUrl;
  1539. if (response.data.imageUrl_info != null) {
  1540. console.log(finance_img_url);
  1541. document.getElementById('img_box_url').src = finance_img_url;
  1542. }
  1543. keywordInput.value = chart_info;
  1544. chartTitle.textContent = chart_info;
  1545. unit = response.data.chart_info.Unit_of_dependent_variable;
  1546. var Label_dependent_variable = response.data.chart_info.Label_dependent_variable;
  1547. var Label_independent_variable = response.data.chart_info.Label_independent_variable;
  1548. stocknumber = response.data.chart_info.args;
  1549. chartTypeBtn.value = chartType;
  1550. unit_data.value = response.data.chart_info.Unit_of_dependent_variable;
  1551. if (response.data.chart_info.Unit_of_dependent_variable == "") {
  1552. unit_value.textContent = ""
  1553. } else {
  1554. unit_value.textContent = '單位:' + response.data.chart_info.Unit_of_dependent_variable;
  1555. }
  1556. dataArray = response.data.data;
  1557. if (chartType === "table") {
  1558. unit_value.textContent = "";
  1559. createTable(dataArray, unit, Label_dependent_variable, Label_independent_variable);
  1560. // document.getElementById('img_box_url').src = "";
  1561. } else if (chartType === "bar") {
  1562. console.log('圖表類型bar')
  1563. $('#textToChart').hide();
  1564. extractAndGenerateChart(dataArray);
  1565. } else if (chartType === "doughnut") {
  1566. unit_value.textContent = "";
  1567. $('#textToChart').hide();
  1568. generatePieChart(dataArray, pieFontSize, PieMaxWidth)
  1569. } else {
  1570. $('#chartdiv').hide();
  1571. generateChart(dataArray);
  1572. }
  1573. // }
  1574. // 在這裡處理成功獲取 JSON 的情況
  1575. // console.log(response);
  1576. // switch (chartType) {
  1577. // case "line":
  1578. // document.getElementById("inlineRadio4").checked = true; // 折线图
  1579. // break;
  1580. // case "bar":
  1581. // document.getElementById("inlineRadio5").checked = true; // 柱状图
  1582. // labelDependent = response.data.chart_info.Label_dependent_variable;
  1583. // break;
  1584. // case "pie":
  1585. // document.getElementById("inlineRadio6").checked = true; // 圆饼图
  1586. // break;
  1587. // case "table":
  1588. // document.getElementById("inlineRadio7").checked = true; // 表格
  1589. // break;
  1590. // default:
  1591. // // 默认情况
  1592. }
  1593. // generateChart(dataArray);
  1594. })
  1595. .catch(error => {
  1596. // 错误处理逻辑,包括取消请求的情况
  1597. apiHideLoading();
  1598. if (axios.isCancel(error)) {
  1599. console.log('请求被取消:', error.message);
  1600. } else {
  1601. console.error('发生错误:', error);
  1602. }
  1603. });
  1604. }
  1605. // 取消请求的函数
  1606. function cancelRequest() {
  1607. if (source) {
  1608. source.cancel('取消了 API 请求');
  1609. apiHideLoading(); // 隐藏加载状态
  1610. }
  1611. }
  1612. document.getElementById('cancel_send_data').addEventListener('click', cancelRequest);
  1613. $(document).ready(function () {
  1614. $('#dataTable').DataTable();
  1615. });
  1616. function resizeChart() {
  1617. console.log(myChart)
  1618. if (myChart != null) {
  1619. myChart.resize();
  1620. }
  1621. }
  1622. document.addEventListener('visibilitychange', function () {
  1623. console.log('Visibility changed:', document.visibilityState);
  1624. if (document.visibilityState === 'visible') {
  1625. resizeChart();
  1626. }
  1627. });
  1628. // 监听窗口resize事件
  1629. window.addEventListener('resize', resizeChart);
  1630. var setting_button = document.getElementById('chart_seeting_button');
  1631. var closeButton = document.getElementById('style_setting_close');
  1632. var closeButton_table = document.getElementById('style_setting_close_table');
  1633. // var borderSetting = document.getElementById('borderSetting');
  1634. var lineChartSetting = document.getElementById('lineChartSetting');
  1635. var barChartSetting = document.getElementById('barChartSetting');
  1636. var table_setting = document.getElementById('table_setting');
  1637. var chart_category = document.getElementById('chart_category');
  1638. var pie_setting = document.getElementById('pie_setting');
  1639. // 获取 chartDiv 元素
  1640. setting_button.addEventListener('click', () => {
  1641. console.log('setting_button')
  1642. if (myChart === null && !chartJsBox.querySelector('table') && chartDiv.childElementCount === 0) {
  1643. alert('請先生成圖表');
  1644. return
  1645. }
  1646. if (chartType === 'table') {
  1647. console.log('表格');
  1648. sidebar.classList.toggle('show');
  1649. sidebar.classList.toggle('hidden');
  1650. barChartSetting.style.display = 'none';
  1651. lineChartSetting.style.display = 'none';
  1652. table_setting.style.display = 'block';
  1653. chart_category.style.display = 'none';
  1654. pie_setting.style.display = 'none';
  1655. } else if (chartType === "bar") {
  1656. console.log('柱狀圖')
  1657. sidebar.classList.toggle('show');
  1658. sidebar.classList.toggle('hidden');
  1659. barChartSetting.style.display = 'block';
  1660. lineChartSetting.style.display = 'none';
  1661. table_setting.style.display = 'none';
  1662. pie_setting.style.display = 'none';
  1663. } else if (chartType === "doughnut") {
  1664. console.log('快捷功能圓餅圖')
  1665. sidebar.classList.toggle('show');
  1666. sidebar.classList.toggle('hidden');
  1667. barChartSetting.style.display = 'none';
  1668. lineChartSetting.style.display = 'none';
  1669. pie_setting.style.display = 'block';
  1670. table_setting.style.display = 'none';
  1671. chart_category.style.display = 'none';
  1672. document.getElementById('unit_input').style.display = 'none';
  1673. } else {
  1674. sidebar.classList.toggle('show');
  1675. sidebar.classList.toggle('hidden');
  1676. table_setting.style.display = 'none';
  1677. barChartSetting.style.display = 'none';
  1678. lineChartSetting.style.display = 'block';
  1679. pie_setting.style.display = 'none';
  1680. }
  1681. });
  1682. closeButton.addEventListener('click', () => {
  1683. sidebar.classList.remove('show');
  1684. sidebar.classList.add('hidden');
  1685. });
  1686. const finance_options = [
  1687. { name: "原油油桶", imageUrl: "./img/finance/01.webp" },
  1688. { name: "黃金", imageUrl: "./img/finance/02.webp" },
  1689. { name: "房屋", imageUrl: "./img/finance/03.webp" },
  1690. { name: "車", imageUrl: "./img/finance/04.webp" },
  1691. { name: "股市", imageUrl: "./img/finance/05.webp" },
  1692. { name: "晶圓", imageUrl: "./img/finance/06.webp" },
  1693. { name: "TSMC 台積電", imageUrl: "./img/finance/07.webp" },
  1694. { name: "台幣", imageUrl: "./img/finance/08.webp" },
  1695. { name: "美金", imageUrl: "./img/finance/09.webp" },
  1696. { name: "購物車", imageUrl: "./img/finance/10.webp" },
  1697. { name: "美中貿易", imageUrl: "./img/finance/11.webp" },
  1698. { name: "世界地圖", imageUrl: "./img/finance/12.webp" },
  1699. { name: "小麥", imageUrl: "./img/finance/13.webp" },
  1700. { name: "玉米", imageUrl: "./img/finance/14.webp" },
  1701. { name: "智慧產線", imageUrl: "./img/finance/15.webp" }
  1702. ];
  1703. const selectOptions = document.getElementById('finance_options');
  1704. const selectOptions_table = document.getElementById('finance_options_table');
  1705. finance_options.forEach((option, index) => {
  1706. const optionElement = document.createElement('option');
  1707. optionElement.value = index + 1; // 值从 1 开始
  1708. optionElement.textContent = option.name;
  1709. optionElement.setAttribute('data-image-url', option.imageUrl); // 存储图片 URL
  1710. selectOptions.appendChild(optionElement);
  1711. });
  1712. selectOptions.addEventListener('change', function () {
  1713. const selectedOption = selectOptions.options[selectOptions.selectedIndex];
  1714. const imageUrl = selectedOption.getAttribute('data-image-url');
  1715. document.getElementById('img_box_url').src = imageUrl;
  1716. });
  1717. // finance_options.forEach((option, index) => {
  1718. // const optionElement = document.createElement('option');
  1719. // optionElement.value = index + 1; // 值从 1 开始
  1720. // optionElement.textContent = option.name;
  1721. // optionElement.setAttribute('data-image-url', option.imageUrl); // 存储图片 URL
  1722. // selectOptions_table.appendChild(optionElement);
  1723. // });
  1724. // selectOptions_table.addEventListener('change', function () {
  1725. // const selectedOption = selectOptions_table.options[selectOptions_table.selectedIndex];
  1726. // const imageUrl = selectedOption.getAttribute('data-image-url');
  1727. // document.getElementById('img_box_url').src = imageUrl;
  1728. // });
  1729. document.querySelectorAll('input[name="ChartOptions"]').forEach(function (radio) {
  1730. radio.addEventListener('change', function () {
  1731. // 檢查哪個單選按鈕被選中
  1732. if (this.value === 'line') {
  1733. // 如果選擇了折線圖,執行相應的操作
  1734. console.log("選擇了折線圖");
  1735. // 在這裡執行顯示折線圖的相關代碼
  1736. } else if (this.value === 'doughnut') {
  1737. // 如果選擇了柱狀圖,執行相應的操作
  1738. console.log("選擇了柱狀圖");
  1739. // 在這裡執行顯示柱狀圖的相關代碼
  1740. }
  1741. });
  1742. });
  1743. function tokencheck() {
  1744. if (!localStorage.getItem("access_token")) {
  1745. window.location.href = "./login.html";
  1746. } else {
  1747. console.log("存在");
  1748. }
  1749. }
  1750. tokencheck();
  1751. function logout() {
  1752. localStorage.removeItem("access_token");
  1753. }
  1754. $(document).on("click", "#logout", function (event) {
  1755. alert("登出成功");
  1756. logout();
  1757. location.reload();
  1758. });
  1759. // speech_to_text
  1760. var closeRecord = document.getElementById('recording_block_close');
  1761. var recording_block = document.getElementById('recording_block');
  1762. var PageLM = "2024-05-07 18:33";
  1763. var recording_button = document.getElementById('recording_button');
  1764. var stopButton = document.getElementById('stop');
  1765. var audio = document.getElementById('audio');
  1766. var recorder, audioBlob;
  1767. closeRecord.addEventListener('click', () => {
  1768. recPause();
  1769. console.log('record-click')
  1770. recording_block.classList.remove('show');
  1771. recording_block.classList.add('hidden');
  1772. });
  1773. function reclog(s, color) {
  1774. var now = new Date();
  1775. var t = ("0" + now.getHours()).substr(-2)
  1776. + ":" + ("0" + now.getMinutes()).substr(-2)
  1777. + ":" + ("0" + now.getSeconds()).substr(-2);
  1778. var div = document.createElement("div");
  1779. var elem = document.querySelector(".reclog");
  1780. elem.insertBefore(div, elem.firstChild);
  1781. div.innerHTML = '<div style="color:' + (!color ? "" : color == 1 ? "red" : color == 2 ? "#0b1" : color) + '">[' + t + ']' + s + '</div>';
  1782. };
  1783. window.onerror = function (message, url, lineNo, columnNo, error) {
  1784. //https://www.cnblogs.com/xianyulaodi/p/6201829.html
  1785. reclog('<span style="color:red">【Uncaught Error】' + message + '<pre>' + "at:" + lineNo + ":" + columnNo + " url:" + url + "\n" + (error && error.stack || Html_$T("kBaF::不能获得错误堆栈")) + '</pre></span>');
  1786. };
  1787. if (!window.Html_$T) {//没有提供本页面用的国际化多语言支持时 返回中文文本
  1788. window.Html_$T = function () {
  1789. var a = arguments, txt = a[0].replace(/^.+?::/, ""), n = 0;
  1790. for (var i = 0; i < a.length; i++) { if (typeof a[i] == "number") { n = i; break } }
  1791. txt = txt.replace(/\{(\d+)\}/g, function (v, f) { v = a[+f + n]; return v == null ? "" : v });
  1792. return txt;
  1793. }
  1794. window.Html_xT = function (v) { return v }
  1795. }
  1796. if (window.Recorder) {
  1797. // reclog(Html_$T('BL9u::頁面已準備好,請先點擊打開錄音,然後點擊錄製'), 2);
  1798. alert('錄音已準備好,請先點擊右下角打開錄音,即可開始錄製')
  1799. } else {
  1800. reclog(Html_$T("YzPd::js文件加载失败,请刷新重试!"), "#f00;font-size:50px");
  1801. console.log('js文件加载失敗,请刷新重试!')
  1802. }
  1803. recording_button.addEventListener('click', async () => {
  1804. recording_block.classList.toggle('show');
  1805. recording_block.classList.toggle('hidden');
  1806. recStart();
  1807. });
  1808. function recStart() {//打开了录音后才能进行start、stop调用
  1809. rec.start();
  1810. };
  1811. stopButton.addEventListener('click', async () => {
  1812. // recorder.stop();
  1813. // uploadAudio(audioBlob);
  1814. recStop();
  1815. });
  1816. window.onload = function () {
  1817. recOpen();
  1818. };
  1819. // 錄音程式
  1820. // =======================
  1821. var rec, wave, recBlob;
  1822. /**调用open打开录音请求好录音权限 Call open to open the recording and request the recording permission**/
  1823. var recOpen = function () {//一般在显示出录音按钮或相关的录音界面时进行此方法调用,后面用户点击开始录音时就能畅通无阻了
  1824. rec = null;
  1825. wave = null;
  1826. recBlob = null;
  1827. var newRec = Recorder({
  1828. type: "mp3", sampleRate: 16000, bitRate: 16 //mp3格式,指定采样率hz、比特率kbps,其他参数使用默认配置;注意:是数字的参数必须提供数字,不要用字符串;需要使用的type类型,需提前把格式支持文件加载进来,比如使用wav格式需要提前加载wav.js编码引擎
  1829. , onProcess: function (buffers, powerLevel, bufferDuration, bufferSampleRate, newBufferIdx, asyncEnd) {
  1830. // // //录音实时回调,大约1秒调用12次本回调
  1831. document.querySelector(".recpowerx").style.width = powerLevel + "%";
  1832. document.querySelector(".recpowert").innerText = formatMs(bufferDuration, 1) + " / " + powerLevel;
  1833. // //可视化图形绘制
  1834. // wave.input(buffers[buffers.length - 1], powerLevel, bufferSampleRate);
  1835. }
  1836. });
  1837. newRec.open(function () {//打开麦克风授权获得相关资源
  1838. rec = newRec;
  1839. //此处创建这些音频可视化图形绘制浏览器支持妥妥的
  1840. // wave = Recorder.FrequencyHistogramView({ elem: ".recwave" });
  1841. reclog(Html_$T("GVCa::已打開錄音,可以點擊錄制開始錄音"), 2);
  1842. }, function (msg, isUserNotAllow) {//用户拒绝未授权或不支持
  1843. reclog((isUserNotAllow ? "UserNotAllow, " : "") + Html_$T("TOOV::打開錄音失敗:") + msg, 1);
  1844. });
  1845. };
  1846. /**关闭录音,释放资源 Close recording, release resources**/
  1847. function recClose() {
  1848. if (rec) {
  1849. rec.close();
  1850. reclog(Html_$T("jqOs::已关闭"));
  1851. } else {
  1852. reclog(Html_$T("VOOw::未打开录音"), 1);
  1853. };
  1854. };
  1855. /**开始录音 Start recording**/
  1856. function recStart() {//打开了录音后才能进行start、stop调用
  1857. if (rec && Recorder.IsOpen()) {
  1858. recBlob = null;
  1859. rec.start();
  1860. reclog(Html_$T("CGdy::已經開始錄音...") + " " + rec.set.type + " " + rec.set.sampleRate + " " + rec.set.bitRate + "kbps");
  1861. } else {
  1862. reclog(Html_$T("ajKR::未打开錄音"), 1);
  1863. };
  1864. };
  1865. /**暂停录音 Passing recording**/
  1866. function recPause() {
  1867. if (rec && Recorder.IsOpen()) {
  1868. rec.pause();
  1869. reclog(Html_$T("GvCy::已暂停"));
  1870. } else {
  1871. reclog(Html_$T("gCAR::未打開錄音"), 1);
  1872. };
  1873. };
  1874. /**恢复录音 Resume recording**/
  1875. function recResume() {
  1876. if (rec && Recorder.IsOpen()) {
  1877. rec.resume();
  1878. reclog(Html_$T("5q1K::继续录音中..."));
  1879. } else {
  1880. reclog(Html_$T("Ob6S::未打开录音"), 1);
  1881. };
  1882. };
  1883. /**结束录音,得到音频文件 Stop recording and get audio files**/
  1884. function recStop() {
  1885. if (!(rec && Recorder.IsOpen())) {
  1886. reclog(Html_$T("5JuL::未打開錄音"), 1);
  1887. return;
  1888. };
  1889. rec.stop(function (blob, duration) {
  1890. console.log(blob, (window.URL || webkitURL).createObjectURL(blob), Html_xT(Html_$T("gOix::時長:{1}ms", 0, duration)));
  1891. recBlob = blob;
  1892. var file = new File([blob], "recording.mp3", { type: "audio/mp3" });
  1893. // console.log(file);
  1894. handleAudioToText(file);
  1895. reclog(Html_$T("0LHf::已錄製mp3:{1}ms {2}字節,可以點擊播放、上傳、本地下载了", 0, formatMs(duration), blob.size), 2);
  1896. }, function (msg) {
  1897. reclog(Html_$T("kGZO::錄音失敗:") + msg, 1);
  1898. });
  1899. };
  1900. /**播放 Play**/
  1901. function recPlay() {
  1902. if (!recBlob) {
  1903. reclog(Html_$T("tIke::请先錄音,然后停止後再播放"), 1);
  1904. return;
  1905. };
  1906. var cls = ("a" + Math.random()).replace(".", "");
  1907. reclog(Html_$T('GlWb::播放中: ') + '<span class="' + cls + '"></span>');
  1908. var audio = document.createElement("audio");
  1909. audio.controls = true;
  1910. document.querySelector("." + cls).appendChild(audio);
  1911. //简单利用URL生成播放地址,注意不用了时需要revokeObjectURL,否则霸占内存
  1912. audio.src = (window.URL || webkitURL).createObjectURL(recBlob);
  1913. audio.play();
  1914. setTimeout(function () {
  1915. (window.URL || webkitURL).revokeObjectURL(audio.src);
  1916. }, 5000);
  1917. };
  1918. /**上传 Upload**/
  1919. function recUpload() {
  1920. var blob = recBlob;
  1921. if (!blob) {
  1922. reclog(Html_$T("DUTn::请先录音,然后停止后再上传"), 1);
  1923. return;
  1924. };
  1925. //本例子假设使用原始XMLHttpRequest请求方式,实际使用中自行调整为自己的请求方式
  1926. //录音结束时拿到了blob文件对象,可以用FileReader读取出内容,或者用FormData上传
  1927. var api = "http://127.0.0.1:9528";
  1928. var onreadystatechange = function (xhr, title) {
  1929. return function () {
  1930. if (xhr.readyState == 4) {
  1931. if (xhr.status == 200) {
  1932. reclog(title + Html_$T("G2MU::上传成功") + ' <span style="color:#999">response: ' + xhr.responseText + '</span>', 2);
  1933. } else {
  1934. reclog(title + Html_$T("TUdi::没有完成上传,演示上传地址无需关注上传结果,只要浏览器控制台内Network面板内看到的请求数据结构是预期的就ok了。"), "#d8c1a0");
  1935. console.error(Html_xT(title + Html_$T("HjDi::上传失败")), xhr.status, xhr.responseText);
  1936. };
  1937. };
  1938. };
  1939. };
  1940. reclog(Html_$T("QnSI::开始上传到{1},请稍候... (你可以先到源码 /assets/node-localServer 目录内执行 npm run start 来运行本地测试服务器)", 0, api));
  1941. /***方式一:将blob文件转成base64纯文本编码,使用普通application/x-www-form-urlencoded表单上传***/
  1942. var reader = new FileReader();
  1943. reader.onloadend = function () {
  1944. var postData = "";
  1945. postData += "mime=" + encodeURIComponent(blob.type);//告诉后端,这个录音是什么格式的,可能前后端都固定的mp3可以不用写
  1946. postData += "&upfile_b64=" + encodeURIComponent((/.+;\s*base64\s*,\s*(.+)$/i.exec(reader.result) || [])[1]) //录音文件内容,后端进行base64解码成二进制
  1947. //...其他表单参数
  1948. var xhr = new XMLHttpRequest();
  1949. xhr.open("POST", api + "/uploadBase64");
  1950. xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
  1951. xhr.onreadystatechange = onreadystatechange(xhr, Html_$T("gG1f::上传方式一【Base64】"));
  1952. xhr.send(postData);
  1953. };
  1954. reader.readAsDataURL(blob);
  1955. /***方式二:使用FormData用multipart/form-data表单上传文件***/
  1956. var form = new FormData();
  1957. form.append("upfile", blob, "recorder.mp3"); //和普通form表单并无二致,后端接收到upfile参数的文件,文件名为recorder.mp3
  1958. //...其他表单参数
  1959. var xhr = new XMLHttpRequest();
  1960. xhr.open("POST", api + "/upload");
  1961. xhr.onreadystatechange = onreadystatechange(xhr, Html_$T("vDzB::上传方式二【FormData】"));
  1962. xhr.send(form);
  1963. };
  1964. /**本地下载 Local download**/
  1965. function recLocalDown() {
  1966. if (!recBlob) {
  1967. reclog(Html_$T("M86h::请先录音,然后停止后再下载"), 1);
  1968. return;
  1969. };
  1970. var cls = ("a" + Math.random()).replace(".", "");
  1971. recdown64.lastCls = cls;
  1972. reclog(Html_$T('vJPl::点击 ') + '<span class="' + cls + '"></span>' + Html_$T('Whtc:: 下载,或复制文本')
  1973. + '<button onclick="recdown64(\'' + cls + '\')">' + Html_$T('XK4l::生成Base64文本') + '</button><span class="' + cls + '_b64"></span>');
  1974. var fileName = "recorder-" + Date.now() + ".mp3";
  1975. var downA = document.createElement("A");
  1976. downA.innerHTML = Html_$T("g8Fy::下载 ") + fileName;
  1977. downA.href = (window.URL || webkitURL).createObjectURL(recBlob);
  1978. downA.download = fileName;
  1979. document.querySelector("." + cls).appendChild(downA);
  1980. if (/mobile/i.test(navigator.userAgent)) {
  1981. alert(Html_xT(Html_$T("DIEK::因移动端绝大部分国产浏览器未适配Blob Url的下载,所以本demo代码在移动端未调用downA.click()。请尝试点击日志中显示的下载链接下载")));
  1982. } else {
  1983. downA.click();
  1984. }
  1985. //不用了时需要revokeObjectURL,否则霸占内存
  1986. //(window.URL||webkitURL).revokeObjectURL(downA.href);
  1987. };
  1988. function recdown64(cls) {
  1989. var el = document.querySelector("." + cls + "_b64");
  1990. if (recdown64.lastCls != cls) {
  1991. el.innerHTML = '<span style="color:red">' + Html_$T("eKKx::老的数据没有保存,只支持最新的一条") + '</span>';
  1992. return;
  1993. }
  1994. var reader = new FileReader();
  1995. reader.onloadend = function () {
  1996. el.innerHTML = '<textarea></textarea>';
  1997. el.querySelector("textarea").value = reader.result;
  1998. };
  1999. reader.readAsDataURL(recBlob);
  2000. };
  2001. var formatMs = function (ms, all) {
  2002. var ss = ms % 1000; ms = (ms - ss) / 1000;
  2003. var s = ms % 60; ms = (ms - s) / 60;
  2004. var m = ms % 60; ms = (ms - m) / 60;
  2005. var h = ms;
  2006. var t = (h ? h + ":" : "")
  2007. + (all || h + m ? ("0" + m).substr(-2) + ":" : "")
  2008. + (all || h + m + s ? ("0" + s).substr(-2) + "″" : "")
  2009. + ("00" + ss).substr(-3);
  2010. return t;
  2011. };
  2012. // =======================
  2013. let mediaRecorder;
  2014. let audioChunks = [];
  2015. var recordText = document.getElementById('record_text');
  2016. async function handleAudioToText(file) {
  2017. console.log('tts')
  2018. let audioLang = "cmn-Hant-TW"; // 音訊語言
  2019. // let lang = localStorage.getItem("lang");
  2020. let lang = "zh-tw";
  2021. console.log("lang", lang);
  2022. switch (lang) {
  2023. case "zh-tw":
  2024. audioLang = "cmn-Hant-TW";
  2025. break;
  2026. case "en-us":
  2027. audioLang = "en-US";
  2028. break;
  2029. case "ja-jp":
  2030. audioLang = "ja-JP";
  2031. break;
  2032. case "ko-kr":
  2033. audioLang = "ko-KR";
  2034. break;
  2035. default:
  2036. break;
  2037. }
  2038. let url = `https://cmm.ai:9001/gcp/speech-to-text?language_code=${audioLang}`;
  2039. const formData = new FormData();
  2040. formData.append("file", file);
  2041. try {
  2042. const response = await axios.post(url, formData);
  2043. console.log("response", response);
  2044. input_text_value = response.data;
  2045. recording_block.classList.remove('show');
  2046. recording_block.classList.add('hidden');
  2047. if (input_text_value.length === 0) {
  2048. alert('請再說一次')
  2049. return
  2050. }
  2051. console.log(input_text_value[0]);
  2052. inputField.value = input_text_value[0];
  2053. // Show the result for a short time before executing get_data
  2054. get_data(input_text_value);
  2055. // get_data(input_text_value);
  2056. } catch (error) {
  2057. console.log("error", error);
  2058. }
  2059. }