<%+cbi/valueheader%>
<label class="cbi-value-title"><%= translate("执行") %></label>
<div class="cbi-value-field">
    <input class="btn cbi-button cbi-button-reload" id="update_service" type="button" size="0" onclick="run()" value="<%= translate('手动执行签到') %>" />
</div>

<label class="cbi-value-title"><%= translate("更新脚本") %></label>
<div class="cbi-value-field">
    <input class="btn cbi-button cbi-button-reload" id="update_script" type="button" size="0" onclick="check_version()" data-version="<%= self.version %>" value="<%= translate('手动检查脚本更新，当前版本：v')..self.version %>" />
</div>

<script type="text/javascript">

    const RUN_URL = '<%=luci.dispatcher.build_url("admin", "services", "jd-dailybonus","run")%>';
    const CHECK_URL = '<%=luci.dispatcher.build_url("admin", "services", "jd-dailybonus","check_update")%>';
    const UPDATE_URL = '<%=luci.dispatcher.build_url("admin", "services", "jd-dailybonus","update")%>';
    const LOG_URL = '<%=luci.dispatcher.build_url("admin", "services", "jd-dailybonus","log")%>';
    const CHECKING_TEXT = '<%= translate("正在检查是否存在新的版本 ...") %>';
    const UPDATING_TEXT = '<%= translate("正在更新脚本，请稍候 ...") %>';
    const NEW_VERSION = '<%= translate("当前已是最新版本：") %>';

    //手动执行
    function run() {
        XHR.get(RUN_URL, null, () => {
            setTimeout(() => { window.location = LOG_URL }, 500);
        });
        return false;
    }

    //更新脚本
    function check_version() {
        let btn = document.getElementById("update_script");
        let version = btn.getAttribute("data-version");
        btn.disabled = true;
        btn.value = CHECKING_TEXT;
        XHR.get(CHECK_URL, null, (x,d) => {
            if (d.new_version == 501){
                btn.disabled = false;
                btn.value = "无法获取新版本，请重试！";
            }else if (d.new_version > version) {
                btn.disabled = true;
                btn.value = `${UPDATING_TEXT} v${d.new_version}`;

                XHR.get(UPDATE_URL, {version: version}, (x, r) => {
                    if (r.error == 0) {
                        btn.value = `${NEW_VERSION} v${d.new_version}`;
                        btn.setAttribute("data-version", d.new_version);
                    } else {
                        btn.disabled = false;
                        alert("更新错误请重试");
                    }
                });
                
            }else{
                btn.value = `${NEW_VERSION} v${d.new_version}`;
            }
        });
        return false
    }

</script>
<%+cbi/valuefooter%>
