text-to-chart.js 91 KB

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