<!doctype html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no">
<title>點餐系統</title>
<link id="marqueeCSS" href="/style/marquee.css" rel="stylesheet" type="text/css" media="all">
<link id="shakeCSS" href="/style/shake.css" rel="stylesheet" type="text/css" media="all">
<link id="deleteCSS" href="/style/delete.css" rel="stylesheet" type="text/css" media="all">
<link id="returnCSS" href="/style/return.css" rel="stylesheet" type="text/css" media="all">
<link id="updateCSS" href="/style/update.css" rel="stylesheet" type="text/css" media="all">
<link id="downloadCSS" href="/style/download.css" rel="stylesheet" type="text/css" media="all">
<link id="toastCSS" href="/toast.css" rel="stylesheet" type="text/css" media="all">
<style>
.form{
width: 80%;
height: 800px;
margin: 30px auto;
border:solid 10px #301a04;
overflow: hidden; /* 避免長方框下面顯示不正常 */
transition-duration: 1s;
z-index: 6;
background: -webkit-linear-gradient(to right, #f5f5bf, #fcfc9a, #987654 50%, #fcfc9a, #f5f5bf);
background: -o-linear-gradient(to right, #f5f5bf, #fcfc9a, #987654 50%, #fcfc9a, #f5f5bf);
background: -moz-linear-gradient(to right, #f5f5bf, #fcfc9a, #987654 50%, #fcfc9a, #f5f5bf);
background: linear-gradient(to right, #f5f5bf, #fcfc9a, #987654 50%, #fcfc9a, #f5f5bf);
}
.photo{
float: right; /*圖片在右邊 */
position: relative;
transition-duration: 1s;
overflow:auto;
}
#image{
display: block;
width:500px;
position: relative;
margin: auto;
cursor:zoom-in;
transform-style: preserve-3d;
animation-name: MapLayerpage;
animation-duration: 1s;
animation-timing-function: linear;
}
@keyframes MapLayerpage {
0%{
transform: rotatey(-90deg);
}
100%{
transform: rotatey(0deg);
}
}
.text{
position: relative;
float: left; /* 文字在左邊 */
width: 45%;
padding: 20px 20px 0px 0px;
transition-duration: 1.5s;
text-align: center;
}
.delete {
transform:translateY(10px);
}
h1 {text-align: center;}
h2 {text-align: center}
h3 {text-align: center}
table,
th,
td {
font-size: 30px;
border: 1px solid white;
}
table.center {
margin-left: auto;
margin-right: auto;
}
#showTable {
background:#3B3B3B;
color: #f0ebaa;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="/toast.js"></script>
</head>
<body bgcolor="#3B3B3B" style="cursor:url(/test.png),auto;z-index:5">
<img id="groundPhoto" style="visibility:hidden;position:fixed;left:0;bottom:0;z-index:3;height:20px;transform:translateX(-10px)">
<div style="position:absolute;top:0;right:0;width:300px;text-align:right;font-size:25px;">
<span id="reminder" style="background:#FFCD9B;color:#150000;"></span>
</div>
<h1 style="color:green"><span style="background:#E8D3B9;">歡迎來到John不是Shiny,的點餐網^^</span></h1>
<h2 style="background:yellow;width:384px;position:absolute;left:50%;transform:translate(-50%,-30px);z-index:4"><span id="order-date">點餐日期:</span> <span id="date" style="color:blue;"></span>
<span id="lunch/dinner"></span></h2>
<h3 style="color:white;"><span id="selectDate"></span> <span id="selectTime" style="transform:translateX(50px)"></span>
<button id="defult" style="visibility:hidden;width:50px;height:30px;" onclick="resetDefult()">預設</button></h3>
<div>
<div id="restaurantPhoto"></div>
<div id="photoImageInfo"></div>
<div style="font-size:20px;">
<form action="javascript:postData();" method="post" enctype="multipart/form-data">
<div id="restaurant-select">
請選擇餐廳:
<!-- 下拉框 select 必須要和option使用-->
<select id="Restaurant" style="font-size:20px;cursor:default;background:pink;" required>
<option value="" selected disabled hidden>請選擇餐廳</option>
<option value="manual/Restaurant1:3">餐廳1</option>
<option value="manual/Restaurant2:2">餐廳2</option>
<option value="manual/Restaurant3:1">餐廳3</option>
<option value="manual/Restaurant4:2">餐廳4</option>
<option value="manual/Restaurant5:1">餐廳5</option>
</select>
</div>
<br>
<div id="name-entry">
<!-- {"username":"請輸入姓名"} -->
姓名:<input type="text" id="Name" value="" size="10" style="font-size:20px;cursor:default;background:pink;text-transform:uppercase;" placeholder="請輸入initial" required><br>
</div>
<br>
<div id="food-entry">
食物:<input type="text" id="Food" value="" size="10" style="font-size:20px;cursor:default;background:pink;text-transform:uppercase;" placeholder="請輸入食物" required>
<select id="FoodSpecial" style="font-size:20px;cursor:default;">
<option value=""></option>
<option value="飯">飯</option>
<option value="意粉">意粉</option>
<option value="薯菜">薯菜</option>
<option value="沙律">沙律</option>
<option value="公仔麵">公仔麵</option>
<option value="米粉">米粉</option>
<option value="米線">米線</option>
<option value="河粉">河粉</option>
<option value="撈麵">撈麵</option>
<option value="烏冬">烏冬</option>
</select>
</div>
<br>
<div id="drink-entry" style="cursor:default;">
飲品:
<!-- 單選框 radio name值必須相同-->
<span id="drinkTemp">
<input type="radio" name="cold/hot" id="coldDrink" value="凍" checked>凍
<input type="radio" name="cold/hot" id="hotDrink" value="熱">熱
</span>
<!-- 下拉框 select 必須要和option使用-->
<select id="drink" style="font-size:20px;" onchange="listenDrink(event);">
<option value="不用飲品">不用飲品</option>
<option value="檸檬茶" selected>檸檬茶</option>
<option value="奶茶">奶茶</option>
<option value="檸檬水">檸檬水</option>
<option value="菜蜜">菜蜜</option>
<option value="咖啡">咖啡</option>
<option value="朱古力">朱古力</option>
<option value="阿華田">阿華田</option>
<option value="好立克">好立克</option>
<option value="其他">其他</option>
</select>
<br><input type="text" id="drinkOthers" maxlength="10" size="10" style="font-size:20px;visibility:hidden;cursor:default;background:pink;" value="" placeholder="請註明飲品">
</div>
<br>
<!-- 多選框 checkbox name值必須相同並且加[]-->
<div id="DrinkSpecial" style="cursor:default;visibility:visible;">
特別要求:
<input type="checkbox" name="drinkSpecial[]" value="少甜" id="drinkLessSugar">少甜
<input type="checkbox" name="drinkSpecial[]" value="少冰" id="drinkLessIce">少冰
</div>
<br>
<div>價錢($):<input type="number" id="price" value="" style="font-size:20px;cursor:default;width:120px" placeholder="可選擇不填"></div>
<br>
<!-- 提交按鈕 -->
<input type="reset" style="cursor:pointer;height:40px;width:75px;" value="重置" onclick="return confirmReset(event);"> <input type="submit"
style="height:40px;width:120px;cursor:pointer;background:dodgerblue;color:white;border-radius:6px;" value="確定"><br>
</form>
<br>
<div>
<button id="getData" style="cursor:pointer;background:#e0cbf5;color:red;display:block;text-align:center;font-size:20px;width:100px;height:50px;border:2px solid #8b008b;font-weight:bold;"
onclick="getData2();">取資料</button>
<button style="visibility:hidden;" onclick="deleteData();"><span>刪除記錄</span><span>
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24">
<path d="M24 20.188l-8.315-8.209 8.2-8.282-3.697-3.697-8.212 8.318-8.31-8.203-3.666 3.666 8.321 8.24-8.206 8.313 3.666 3.666 8.237-8.318 8.285 8.203z"></path></svg></span>
</button>
</div>
<br>
<img id="book" style="visibility:hidden;width:384px;height:40px;">
<div id="showImageInfo"></div>
</div>
</div>
<div id="showTable"></div>
<p id="base" style="color:white;text-Align:center;font-size:30px;"></p>
<div id="bottom"></div>
<script>
storageData = {mouseClick: {}, pinchZoomisStart: false, isToast: false,};
document.querySelector('.photo').addEventListener('dragstart',mouseDragStart);
document.querySelector('.photo').addEventListener('dragend',mouseDragEnd);
getOrderDate();
var orderDate = document.querySelector("#date").innerText + document.querySelector("#lunch\\/dinner").innerText;
if(localStorage.getItem("orderDate") === orderDate) document.querySelector(".delete").style.visibility = "visible";
checkDeviceWidth();
/* below is function part */
function mouseDragStart(event) {
storageData.mouseClick.X = event.clientX;
storageData.mouseClick.Y = event.clientY;
}
function mouseDragEnd(event) {
clickX = event.clientX - storageData.mouseClick.X;
clickY = event.clientY - storageData.mouseClick.Y;
$('.form').css('transform', `translate(${clickX}px,${clickY}px)`);
}
function getOrderDate() {
var date = new Date();
var year = date.getFullYear();
var month = date.getMonth() + 1;
var day = date.getDate();
var hours = date.getHours();
document.querySelector("#date").innerText = `${day}/${month}/${year}`;
document.querySelector("#lunch\\/dinner").innerText = hours < 16? "午餐": "晚餐";
}
function checkDeviceWidth() {
document.querySelector('#groundPhoto').style.width = `${window.innerWidth+20}px`;
if(window.innerWidth < 900) {
document.querySelector("head > style").innerHTML =
`
.form{
width: ${screen.width-20}px;
margin: 30px auto;
border:solid 1px gray;
overflow: hidden;
background:#f5f5bf; /*#F5EEF8;*/
}
.photo{
width: ${screen.width-20}px;
overflow: hidden;
background: white;
}
#imgage{
display: block;
width:100%;
}
.text{
width: ${screen.width-20}px;
}
.delete {
transform:translate(110px,-50px);
}
h1 {text-align: center;}
h2 {text-align: center}
h3 {text-align: center}
table,
th,
td {
font-size: ${Math.floor(screen.width/27)}px;
border: 1px solid black;
}
table.center {
margin-left: auto;
margin-right: auto;
}
#showTable {
background: white;
}
`;
var script = document.createElement('script');
script.src = "Pinchzoom_new.js";
document.body.appendChild(script);
try {
document.querySelector("#translate").remove();
} catch (e) {
//pass
}
} else {
if(window.innerWidth < 1300) {
document.querySelector("head > style").innerHTML =
`
.form{
width: 1000px;
height: 850px;
margin: 30px auto;
border:solid 10px #301a04;
overflow: hidden; /* 避免長方框下面顯示不正常 */
background: -webkit-linear-gradient(to right, #f5f5bf, #fcfc9a, #987654 50%, #fcfc9a, #f5f5bf);
background: -o-linear-gradient(to right, #f5f5bf, #fcfc9a, #987654 50%, #fcfc9a, #f5f5bf);
background: -moz-linear-gradient(to right, #f5f5bf, #fcfc9a, #987654 50%, #fcfc9a, #f5f5bf);
background: linear-gradient(to right, #f5f5bf, #fcfc9a, #987654 50%, #fcfc9a, #f5f5bf);
transition-duration: 0.5s;
}
.photo{
position: relative;
width: 500px;
float: right; /*圖片在右邊 */
}
.photo img{
display: block;
width:100%;
position: relative;
margin: auto;
cursor:zoom-in;
transform-style: preserve-3d;
animation-name: MapLayerpage;
animation-duration: 1s;
animation-timing-function: linear;
}
@keyframes MapLayerpage {
0%{
transform: rotatey(-90deg);
}
100%{
transform: rotatey(0deg);
}
}
.text{
position: relative;
float: left; /* 文字在左邊 */
width: 450px;
padding: 20px 20px 0px 0px;
}
.delete {
transform:translateY(10px);
}
h1 {text-align: center;}
h2 {text-align: center}
h3 {text-align: center}
table,
th,
td {
font-size: 30px;
border: 1px solid white;
}
table.center {
margin-left: auto;
margin-right: auto;
}
#showTable {
background:#3B3B3B;
color: #f0ebaa;
}
`
var script = document.createElement('script');
script.src = "snowflake/snow.js";
document.body.appendChild(script);
}
var button = document.createElement('button');
button.innerHTML = '左右轉換';
button.id = "translate";
button.onclick = translate;
button.style.width = "200px";
button.style.height = "35px";
button.style.position = "fixed";
button.style.left = "50%";
button.style.top = "85%";
button.style.transform = "translateX(-50%)";
document.querySelector('body').appendChild(button);
document.querySelector('#groundPhoto').src="/sssss.png";
document.querySelector('#groundPhoto').style.visibility = 'visible';
document.querySelector('#book').src = "open-book-images-png-2.png";
document.querySelector('#book').style.visibility = 'visible';
}
if(window.innerWidth >= 1300) {
var script = document.createElement('script');
script.src = "snowflake/update_snowflake.js";
document.body.appendChild(script);
}
}
function bigimg(e){
var zoom = parseInt(document.querySelector(".form").style.zoom, 10) || 100;
zoom += event.wheelDelta / 12;
if(zoom >= 100 && zoom <= 300) {
document.querySelector(".form").style.zoom = zoom+'%';
}
document.querySelector('.text').style.zoom = "100%";
if(document.querySelector("#getData").getBoundingClientRect().bottom > document.querySelector(".form").getBoundingClientRect().bottom) {
document.querySelector('.text').style.zoom = "70%";
if(!storageData.isToast) {
storageData.isToast = true;
$.toast({
heading: '<h2 style="font-size:16px">提示</h2>',
text: '<p style="font-size:16px">可縮小圖片還原文字大小</p>',
icon: 'info',
loader: true, // Change it to false to disable loader
loaderBg: '#9EC600', // To change the background
position: 'top-center',
hideAfter: 5000,
})
setTimeout(() => storageData.isToast = false, 20000);
}
}
return false;
}
async function translate() {
if(document.querySelector("#back")) return;
document.querySelector('.text').style.zoom = "100%";
var random = Math.round(Math.random());
if(random) {
$('.photo').css('transform', 'translate(0px,1500px)');
$('.text').css('transform', 'translate(0px,-1500px)');
} else {
$('.photo').css('transform', 'translate(0px,-1500px)');
$('.text').css('transform', 'translate(0px,1500px)');
}
if(document.querySelector('.text').style.float == "right") {
document.querySelector('.photo').style.float = "right";
document.querySelector('.text').style.float = "left";
} else {
document.querySelector('.photo').style.float = "left";
document.querySelector('.text').style.float = "right";
}
await sleep(500);
$('.text').css('transform', 'translate(0px,0px)');
$('.photo').css('transform', 'translate(0px,0px)');
do {
document.querySelector('.form').style.zoom = '100%';
await sleep(500);
} while (document.querySelector('.form').style.zoom != '100%');
try {
document.querySelector("#image").style.zoom = '100%';
} catch(e) {
//pass
}
$(".form").css('transform', `translate(0px,0px)`)
if(document.querySelector('.text').style.float == "right") {
var y = document.querySelector(".form").getBoundingClientRect().right - document.querySelector("#getData").getBoundingClientRect().right-10;
document.querySelector("#getData").style.transform = `translate(${y}px,0px)`;
var z = document.querySelector(".form").getBoundingClientRect().right - document.querySelector(".delete").getBoundingClientRect().right-10;
document.querySelector(".delete").style.transform = `translate(${z}px,10px)`;
} else {
document.querySelector("#getData").style.transform = `translate(0px,0px)`;
document.querySelector(".delete").style.transform = `translate(0px,10px)`;
}
}
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
function confirmToExit(e) {
e.returnValue = '......';
}
function listenDrink(e) {
$("#drinkOthers").css('visibility', 'hidden');
$("#drinkOthers").attr('required', false);
$("#drinkTemp").show("normal");
$("#DrinkSpecial").show("fast");
if(e.currentTarget.selectedOptions[0].text == '其他') {
$("#drinkOthers").css('visibility', 'visible');
$("#drinkOthers").attr('required', true);
}
if(e.currentTarget.selectedIndex == 0) {
$("#drinkTemp").hide("normal");
$("#DrinkSpecial").hide("fast");
}
}
function confirmReset(event) {
if(!confirm('確定重置資料?')) return false;
window.removeEventListener('beforeunload', confirmToExit);
document.querySelector("#reminder").innerText = "";
try {
listenDrink(event);
} catch(e) {
document.querySelector('#restaurantPhoto').innerHTML='';
}
return true;
}
document.querySelector("#Restaurant").addEventListener("change", (e) => {
var [restaurant, photoTotal] = e.target.value.split(":");
if(window.innerWidth < 900) {
var image = new Image();
image.addEventListener('load', checkSize, {passive : true});
image.src = `/${restaurant}/1.jpg`;
document.querySelector(".photo").innerHTML = `<img id="image" src="/${restaurant}/1.jpg" width="${window.innerWidth-20}px" alt="1" title="${restaurant}/第1張" onload="startImage()">`;
if(photoTotal != 1) {
document.querySelector("#photoImageInfo").innerHTML = `<p style="font-size:20px">第1/${photoTotal}張 <a href="/${restaurant}/1.jpg" target="_blank">在新分頁打開圖片</a></p>
<button style="width:80px;height:30px;" onclick="nextPhoto(-1)">上一張</button> <button style="width:80px;height:30px;" onclick="nextPhoto()">下一張</button><br><br>`;
} else {
document.querySelector("#photoImageInfo").innerHTML = `<p style="font-size:20px">第1/${photoTotal}張 <a href="/${restaurant}/1.jpg" target="_blank">在新分頁打開圖片</a></p>`;
}
} else {
var d = document.querySelector('.text').style.float == "right"? "right" : "left";
document.querySelector("#restaurantPhoto").innerHTML =
`<img id="image" style="transform-origin:${d}" src="/${restaurant}/1.jpg" alt="1" title="${restaurant}/第1張" onclick="nextPhoto();" onmousewheel="return bigimg(this);">`;
document.querySelector("#showImageInfo").innerHTML = `<p style="font-size:30px">第1/${photoTotal}張 <a href="/${restaurant}/1.jpg" target="_blank">在新分頁打開圖片</a></p>`;
$.toast({
heading: `<h2 style="font-size:16px">${document.querySelector("#Restaurant").selectedOptions[0].text}</h2>`,
text: `<p style="font-size:16px">共有${photoTotal}張餐單。</p>`,
icon: 'info',
loader: true, // Change it to false to disable loader
loaderBg: '#9EC600', // To change the background
position: 'top-center',
hideAfter: 5000,
})
}
});
function nextPhoto(next=1) {
var [restaurant, photoTotal] = $("#Restaurant").val().split(":");
var number = parseInt(document.querySelector("#image").alt);
if(number == 1 && next == -1) number = parseInt(photoTotal)+1;
if(number == photoTotal && next == 1) number = 0;
if(window.innerWidth < 900) {
var image = new Image();
image.addEventListener('load', checkSize, {passive: true});
image.src = `/${restaurant}/${number+next}.jpg`;
document.querySelector(".photo").innerHTML = `<img id="image" src="/${restaurant}/${number+next}.jpg" width="${window.innerWidth-20}px" alt="${number+next}" title="${restaurant}/第${number+next}張">`;
document.querySelector("#photoImageInfo").innerHTML = `<p style="font-size:20px">第${number+next}/${photoTotal}張 <a href="/${restaurant}/${number+next}.jpg" target="_blank">在新分頁打開圖片</a></p>
<button style="width:80px;height:30px;" onclick="nextPhoto(-1)">上一張</button> <button style="width:80px;height:30px;" onclick="nextPhoto()">下一張</button><br><br>`;
} else {
var d = document.querySelector('.text').style.float == "right"? "right" : "left";
document.querySelector("#restaurantPhoto").innerHTML =
`<img id="image" style="transform-origin:${d}" src="/${restaurant}/${number+next}.jpg" alt="${number+next}" title="${restaurant}/第${number+next}張" onclick="nextPhoto();"onmousewheel="return bigimg(this);">`;
document.querySelector("#showImageInfo").innerHTML = `<p style="font-size:30px">第${number+next}/${photoTotal}張 <a href="/${restaurant}/${number+next}.jpg" target="_blank">在新分頁打開圖片</a></p>`;
}
}
function startImage() {
if(storageData.pinchZoomisStart) return;
storageData.pinchZoomisStart = true;
setTimeout(() => {
$(function() {
$('.photo').each(function () {
new RTP.PinchZoom($(this), {});
});
})
}, 0);
}
function checkSize() {
var imageSize = {};
imageSize.width = this.width
imageSize.height = this.height
var screenHeight = ((window.innerWidth-20)/imageSize.width)*imageSize.height
if(screenHeight < 450) {
document.querySelector(".photo").style.height = `${450}px`;
} else {
document.querySelector(".photo").style.height = `${screenHeight+20}px`;
}
}
document.querySelector(".form").addEventListener("change", (e) => {
window.addEventListener('beforeunload', confirmToExit);
document.querySelector("#reminder").innerText = "你所輸入的資料尚未儲存。";
})
</script>
<script>
const url = "https://docs.google.com/spreadsheets/d/1GWNzP2Op2dwAZnrteljxJkf5ZDAKFPhMpx_HyE9U-Tk/edit#gid=0";
const scriptUrl = "https://script.google.com/macros/s/AKfycbyi2z9GGOctuvKBG5v7WiW69_FCpQ6B1ir5QyflBlB3i-epn9hJ8SShZ2q7aXKWB3ff6A/exec";
function getDrinkContent() {
if(document.querySelector("#drink").selectedIndex == 0)
return "不用飲品";
var cold_or_hot = document.querySelector("#coldDrink").checked? "凍":"熱";
var drink = (document.querySelector('#drink').selectedOptions[0].text == "其他")? $("#drinkOthers").val() : $("#drink").val();
var drink_special = [...document.querySelector("#DrinkSpecial").children].map(item => item.checked? item.value : "");
return cold_or_hot + drink + drink_special.join("");
}
function getCurrentTime() {
var date = new Date();
var hours = date.getHours().toString();
var minutes = date.getMinutes().toString();
var seconds = date.getSeconds().toString();
return `${hours}:${minutes}:${seconds}`;
}
async function deleteData() {
var orderDate = document.querySelector("#date").innerText + document.querySelector("#lunch\\/dinner").innerText;
var exists = localStorage.getItem("orderDate") === orderDate;
if(exists) {
if(!confirm("確定刪除寫入資料?")) return;
} else {
alert("沒有資料可刪除。");
return;
}
var parameter = {
url: url,
sheetName: "Sheet1",
method: "delete",
date: document.querySelector("#date").innerText,
lun_or_din : document.querySelector("#lunch\\/dinner").innerText,
id: localStorage.getItem("id"),
}
await $.post(scriptUrl, parameter).done(data => {
document.querySelector(".delete").style.visibility = "hidden";
localStorage.removeItem("orderDate");
setTimeout(() => alert("已刪除。"), 1500);
})
.fail(alert);
}
async function postData() {
var orderDate = document.querySelector("#date").innerText + document.querySelector("#lunch\\/dinner").innerText;
var exists = localStorage.getItem("orderDate") === orderDate;
if(exists) {
if(!confirm("資料已存在,是否確定修改?"))
return;
} else {
if(!confirm("確定提交??"))
return;
}
var id = localStorage.getItem("id") || String(Math.random()).replace("0.","");
localStorage.setItem("id", id);
var parameter = {
url: url,
sheetName: "Sheet1",
method: exists? "modify":"post",
information: JSON.stringify({
name: $('#Name').val().toUpperCase(),
restaurant: document.querySelector("#Restaurant").selectedOptions[0].text,
food: $("#Food").val().toUpperCase() + $("#FoodSpecial").val(),
drink: getDrinkContent(),
date: document.querySelector("#date").innerText,
lun_or_din : document.querySelector("#lunch\\/dinner").innerText,
time: getCurrentTime(),
price: $("#price").val() || "/",
id: id,
}),
};
await $.post(scriptUrl, parameter).done(data => {
localStorage.setItem("orderDate", orderDate);
window.removeEventListener('beforeunload', confirmToExit);
document.querySelector("#reminder").innerText = "";
document.querySelector(".delete").style.visibility = "visible";
alert(data);
})
.fail(alert);
}
async function getData() {
document.querySelector('#getData').style.cursor = 'wait';
var parameter = {
url: url,
sheetName: "Sheet1",
method: "get",
}
await $.get(scriptUrl, parameter).done(sheetData => handleProcess(sheetData)).fail(alert);
document.querySelector('#getData').style.cursor = 'pointer';
}
async function getData2() {
document.querySelector('#getData').style.cursor = 'wait';
await fetch('https://sheets.googleapis.com/v4/spreadsheets/1GWNzP2Op2dwAZnrteljxJkf5ZDAKFPhMpx_HyE9U-Tk/values/Sheet1?alt=json&key=AIzaSyCRidnWxBCPa8o4Bn2g4CRU3NvTwr4KImU')
.then(res => res.json())
.then(res => handleProcess(JSON.stringify(res.values)))
.catch(alert);
document.querySelector('#getData').style.cursor = 'pointer';
}
function handleProcess(sheetData) {
// Parse given JSON and filter match date and time;
var data = convertDatatoJson(JSON.parse(sheetData))
.filter(obj => (obj["日期"] == document.querySelector("#date").innerText) && (obj["午餐/晚餐"] == document.querySelector("#lunch\\/dinner").innerText));
for(var i=0; i<data.length; i++) {
data[i]["No."] = i+1;
}
$('.form').hide(200);
if(data.length) {
CreateTableFromJSON(data);
document.querySelector('#base').innerText = "";
} else {
document.querySelector('#base').innerText = `${document.querySelector("#date").innerText} ${document.querySelector("#lunch\\/dinner").innerText} ...沒有資料。`;
document.querySelector("#showTable").innerHTML = "";
}
document.querySelector("#order-date").innerText = "讀取日期: "
document.querySelector("#selectDate").innerHTML = `<br>日期: <input id="inputDate" type="date" style="font-size:16px;" onchange="changeDate();">`;
document.querySelector("#selectTime").innerHTML = `時間: <select id="inputTime" style="font-size:20px;"><option value="午餐">午餐</option><option value="晚餐">晚餐</option></select>`;
var [day, month, year] = document.querySelector("#date").innerText.split("/");
document.querySelector('input[type="date"]').value = `${year}-${("0"+month).slice(-2)}-${("0"+day).slice(-2)}`;
document.querySelector("#inputTime").selectedIndex = document.querySelector("#lunch\\/dinner").innerText == "午餐"? 0:1;
document.querySelector("#defult").style.visibility = "visible";
document.querySelector("#bottom").innerHTML =
`
<button id="back" onclick="back();" style="transform:translate(${window.innerWidth/2-140}px, 50px);">
<svg height="16" width="16" xmlns="http://www.w3.org/2000/svg" version="1.1" viewBox="0 0 1024 1024"><path d="M874.690416 495.52477c0 11.2973-9.168824 20.466124-20.466124 20.466124l-604.773963 0 188.083679 188.083679c7.992021 7.992021 7.992021 20.947078 0 28.939099-4.001127 3.990894-9.240455 5.996574-14.46955 5.996574-5.239328 0-10.478655-1.995447-14.479783-5.996574l-223.00912-223.00912c-3.837398-3.837398-5.996574-9.046027-5.996574-14.46955 0-5.433756 2.159176-10.632151 5.996574-14.46955l223.019353-223.029586c7.992021-7.992021 20.957311-7.992021 28.949332 0 7.992021 8.002254 7.992021 20.957311 0 28.949332l-188.073446 188.073446 604.753497 0C865.521592 475.058646 874.690416 484.217237 874.690416 495.52477z"></path></svg>
<span>返回</span>
</button>
<a id="update" onclick="javascript:update();" style="transform:translate(${window.innerWidth/2-40}px, 0px);">讀取資料</a>
<div id="download" style="width:120px;height:50px;transform:translate(${window.innerWidth/2+73}px, -50px);" onclick="exportWS();">
<div>
<div style="font-size:16px">下載</div>
<span>
<svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" role="img" width="2em" height="2em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 24 24"><path fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 15V3m0 12l-4-4m4 4l4-4M2 17l.621 2.485A2 2 0 0 0 4.561 21h14.878a2 2 0 0 0 1.94-1.515L22 17"></path></svg>
</span>
</div>
</div>
`;
}
function convertDatatoJson(sheetData) {
var title = sheetData.shift();
return sheetData.map(arr => {
var obj = {}; // create json
arr.forEach((item,i) => obj[title[i]] = item);
return obj;
})
}
function CreateTableFromJSON(data) {
// Get keys (=cells) of each items
var keys = Object.keys(Object.assign({}, ...data));
keys.pop(); //don't show id
// Build the table header
var header = `<tr>` + keys.map(key => `<td>${key}</td>`).join("") + `</tr>`;
// Build the table body
var body =
data.map(row =>
`<tr>${keys.map(key =>
`<td>${row[key]}</td>`).join("")}
</tr>`
).join("");
// Build the final table
var table = `
<table id="data-table">
<tbody>
${header}
${body}
</tbody>
</table>`;
// Append the result into #showTable element
document.querySelector('#showTable').innerHTML = table;
$('#showTable').show(500);
$('td:nth-child(7)').hide();
}
function back() {
$('#showTable').hide(200);
document.querySelector('#update').remove();
document.querySelector('#back').remove();
document.querySelector('#download').remove();
document.querySelector("#order-date").innerText = "點餐日期:"
document.querySelector("#selectDate").innerHTML = ``;
document.querySelector("#selectTime").innerHTML = ``;
document.querySelector("#defult").style.visibility = "hidden";
document.querySelector('#base').innerText = "";
getOrderDate();
$('.form').show(500);
}
async function update() {
document.querySelector('#update').style.cursor = 'wait';
document.querySelector('#update').innerHTML = '讀取中..';
var parameter = {
url: url,
sheetName: "Sheet1",
method: "get",
};
await fetch('https://sheets.googleapis.com/v4/spreadsheets/1GWNzP2Op2dwAZnrteljxJkf5ZDAKFPhMpx_HyE9U-Tk/values/Sheet1?alt=json&key=AIzaSyCRidnWxBCPa8o4Bn2g4CRU3NvTwr4KImU')
.then(res => res.json())
.then(res => {
var [year, month, day] = document.querySelector("#inputDate").value.split("-");
var data = convertDatatoJson(res.values).filter(obj => obj["日期"] == `${Number(day)}/${Number(month)}/${Number(year)}` && obj["午餐/晚餐"] == document.querySelector("#inputTime").value);
document.querySelector("#date").innerText = `${Number(day)}/${Number(month)}/${Number(year)}`;
document.querySelector("#lunch\\/dinner").innerText = document.querySelector("#inputTime").value;
/*
var data = convertDatatoJson(res.values).filter(obj => (obj["日期"] == document.querySelector("#date").innerText) && (obj["午餐/晚餐"] == document.querySelector("#lunch\\/dinner").innerText));
await $.get(scriptUrl, parameter).done(sheetData => {
// Parse given JSON and filter match date and time;
var data = convertDatatoJson(JSON.parse(sheetData))
.filter(obj => (obj["日期"] == document.querySelector("#date").innerText) && (obj["午餐/晚餐"] == document.querySelector("#lunch\\/dinner").innerText));
*/
for(var i=0; i<data.length; i++) {
data[i]["No."] = i+1;
}
if(data.length) {
CreateTableFromJSON(data);
document.querySelector('#base').innerText = "";
} else {
document.querySelector('#base').innerText = `${document.querySelector("#date").innerText} ${document.querySelector("#lunch\\/dinner").innerText} ...沒有資料。`;
document.querySelector("#showTable").innerHTML = "";
}
})
document.querySelector('#update').style.cursor = 'default';
document.querySelector('#update').innerHTML = '讀取資料';
$.toast({
heading: `<h2 style="font-size:16px">訊息</h2>`,
text: `<p style="font-size:16px">已讀取資料</p>`,
icon: 'info',
loader: false, // Change it to false to disable loader
loaderBg: '#9EC600', // To change the background
position: 'top-center',
hideAfter: 3000,
})
}
function exportWS() {
$.toast({
heading: `<h2 style="font-size:16px">訊息</h2>`,
text: `<p style="font-size:16px">下載中...</p>`,
icon: 'info',
loader: false, // Change it to false to disable loader
loaderBg: '#9EC600', // To change the background
position: 'top-center',
hideAfter: 3000,
})
var fileName = `${document.querySelector("#date").innerText}-${document.querySelector("#lunch\\/dinner").innerText}.xls`;
try {
doit('biff8', fileName);
} catch (e) {
getExternalScript()
.then(done => doit('biff8', fileName))
.catch(alert);
}
}
function getExternalScript() {
return new Promise((resolve,reject) => {
var script_urls = ["https://cdn.jsdelivr.net/npm/file-saver@2.0.2/dist/FileSaver.js",
"https://cdn.sheetjs.com/xlsx-0.18.9/package/dist/xlsx.full.min.js"]
loadScript(script_urls.shift());
function loadScript(script_url) {
var external_script = document.createElement('script');
external_script.src = script_url;
document.querySelector("body").appendChild(external_script);
external_script.onload = function() {
script_urls.length? loadScript(script_urls.shift()) : resolve("done");
}
external_script.onerror = function() {
reject("fail to load script");
}
}
})
}
function doit(type, fn, dl) {
var elt = document.getElementById('data-table');
var wb = XLSX.utils.table_to_book(elt, {sheet:"Sheet JS"});
var range = XLSX.utils.decode_range(wb.Sheets['Sheet JS']['!ref']);
wb.Sheets['Sheet JS']['!cols'] = [{ wpx: 30 }, { wpx: 50 }, { wpx: 70 }, { wpx: 100 }, { wpx: 100 }, { wpx: 60 }, { wpx: 60}, { wpx: 60}, { wpx: 40}];
return dl? XLSX.write(wb, {bookType:type, bookSST:true, type: 'base64'}) : XLSX.writeFile(wb, fn || ('SheetJSTableExport.' + (type || 'xlsx')));
}
function changeDate() {
if(!document.querySelector("#inputDate").value) {
var date = new Date();
var year = String(date.getFullYear());
var month = String(date.getMonth() + 1);
var day = String(date.getDate());
document.querySelector("#inputDate").value = `${year}-${("0"+month).slice(-2)}-${("0"+day).slice(-2)}`;
}
}
function resetDefult() {
var date = new Date();
var year = String(date.getFullYear());
var month = String(date.getMonth() + 1);
var day = String(date.getDate());
var hours = date.getHours();
document.querySelector("#inputDate").value = `${year}-${("0"+month).slice(-2)}-${("0"+day).slice(-2)}`;
document.querySelector("#inputTime").selectedIndex = hours < 16? 0:1;
}
</script>
<div style="height:1200px;position:fixed;left:0px;top:0px;right:0px;bottom:0px;pointer-events:none;z-index:2;">
<canvas id="canvas" style="position:absolute;left:0;top:0;z-index:1"></canvas></div>
</body>
</html>