<!DOCTYPE html>
<html>

<head>
  <title>钜星应用程序管理工具</title>
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
  <link href="../../node_modules/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet"/>
  <script src="../../node_modules/bootstrap/dist/js/bootstrap.min.js"></script>
  <link href="../css/set.css" rel="stylesheet">
</head>
<body>
<div class="container-fluid" id="div">
  <table class="table table-striped " style="text-align: center">
    <tr>
      <th>编号</th>
      <th>端口</th>
      <th>快捷地址</th>
      <th>缓存文件夹</th>
      <th colspan="2">操作</th>
    </tr>
  </table>
</div>
<div id="cover"></div>
<div id="box">
  <select id="weburl" class="form-control" onchange="clientChange()">
  </select><br/>
  <label style="color: red;">注意：以下项不允许与其它快捷方式一致！！</label>
  <input id="lnkName" placeholder="快捷名称(必填,不能与其它快捷方式名称一致)" class="form-control"/>
  <br/>
  <input id="cachePath" placeholder="缓存名称(必填,不能与其它缓存位置一致)" class="form-control"/>
  <br/>
  <div style="margin-left: 20%;padding-top: 2em">
    <input type="button" onclick="createInk()" class="btn  btn-success" value="生成"/>
    <input type="button" onclick="exit()" class="btn  btn-danger" value="退出" style="margin-left: 30%;"/>
  </div>
</div>
<!--确认提示框-->
<div id="box1">
  <div class="panel panel-default">
    <div class="panel-heading">
      <h5>删除提示</h5>
      <hr/>
    </div>
    <div class="panel-body">
      <span>是否删除此条桌面快捷方式？</span>
      <div style="margin-left: 20%;padding-top: 2em">
        <input type="button" onclick="deleteConfirm()" class="btn  btn-success" value="确认"/>
        <input type="button" onclick="exit1()" class="btn  btn-danger" value="取消" style="margin-left: 30%;"/>
      </div>
    </div>
  </div>
</div>
<!--更新进度展示框-->
<div id="box2">
  <!-- 更新信息提示-->
  <div id="update_label"></div>
  <!--更新进度条-->
  <div class="progress">
    <div class="progress-bar progress-bar-success" role="progressbar" aria-valuenow="60"
         aria-valuemin="0" aria-valuemax="100" style="width: 0%;">
      <span class="sr-only"></span>
    </div>
  </div>
</div>
<!--确认更新提示框-->
<div id="box3">
  <div class="panel panel-default">
    <div class="panel-heading" id="update_confirm_header" style="margin-left: 29%"></div>
    <hr/>
    <div class="panel-body" style="width: 100%;height: 25rem">
      <ul class="list-group" id="update_confirm_content" style="text-align: center"></ul>
      <div style="padding-left: 20%;height: 5rem">
        <div class="checkbox">
          <label style="font-size: 12px">
            <input type="checkbox" class="is_restart" value="1">
            更新后是否重新启动程序？
          </label>
        </div>
        <div>
          <input type="button" onclick="updateConfirm()" class="btn  btn-success" value="立即升级"/>
          <input type="button" onclick="exit2()" class="btn  btn-danger" value="取消" style="margin-left: 30%;"/>
        </div>
      </div>
    </div>
  </div>

</div>
<input type="button" id="create" class="btn btn-success floating-button" value="创建">


<script type="text/javascript">
  const dpth=require('path');
  const log = require(".."+dpth.sep+"js"+dpth.sep+"setting"+dpth.sep+"set_log").clog;
  const fs = require("fs");
  const ws = require('windows-shortcuts');
  const os=require('os');
  const process = require('child_process');
  const iconv = require('iconv-lite');
  const encoding = 'cp936';
  const binaryEncoding = 'binary';
  const keyPath = 'HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders';//选择要修改或者保存或者删除的路径（操作路径）
  let desktop;
  let ele = require('electron');
  let ipcRenderer = ele.ipcRenderer;
  window.$ = window.jquery = require('jquery');
  let update_info = {};
  process.exec(`REG QUERY "${keyPath}" /v Desktop`, {encoding: binaryEncoding}, function (error, stdout, stderr) {
    if (error != null) {
      console.log('获取注册表桌面路径失败,异常如下：' + error);
    } else {
      let value = iconv.decode(new Buffer(stdout, binaryEncoding), encoding);
      value = value.substring(value.indexOf(":") - 1);
      desktop = value.replace(/^\s*|\s*$/g, ""); //获取注册表实际值并去除首尾空格
    }
  });
  if (!desktop) {
    desktop = dpth.join(os.homedir(), 'Desktop');
  }

  log.info("-->进入配置页面...");
  //进行程序检查更新
  ipcRenderer.send("checkForUpdate");
  //程序更新信息监听
  ipcRenderer.on("message", (event, args) => {
    if (args[0] == -1) {
      $("#update_label").html("<span style='color:#ff0000'>" + args[1] + "</span>");
      setTimeout(function () {
        $("#box2").hide();
        if (!$("#box1").is(":visible") && !$("#box").is(":visible") && !$("#box3").is(":visible")) {
          $("#cover").css("cssText", "background:");
          $("#create").removeAttr("disabled");
          $(".delete").removeAttr("disabled");
        }
      }, 1500)
    } else if (args[0] == 2) {
      log.info(args[1]);
      $("#update_label").html(args[1]);
      update_info = args[2];
      //检查到可用更新弹出下载进度弹框
      $("#box2").show();
      $("#cover").css("cssText", "background:#aaa");
      //禁用创建和删除按钮
      $("#create").attr("disabled", "disabled");
      $(".delete").attr("disabled", "disabled");
    } else {
      log.info(args[1]);
    }
  });
  //下载进度条实时更新
  ipcRenderer.on("downloadProgress", (event, progressObj) => {
    let downloadPercent = progressObj.percent || 0;
    log.info("传过来的数据百分数样式:" + progressObj.percent);
    $(".progress-bar").css("cssText", "width:" + downloadPercent + "%");
    $(".sr-only").html(downloadPercent + "%");
  });
  //下载完成立即进行重启安装
  ipcRenderer.on("isQuitAndInstall", () => {
    $("#box2").hide();
    $("#update_confirm_header").html("<h5>" + update_info.version + "版本说明</h5>");
    $("#update_confirm_content").html(update_info.updateInfo);
    $("#box3").show();
  });

  //更新确认提示框
  function updateConfirm() {
    let is_restart = $(".is_restart").val();
    $("#box3").hide();
    $("#cover").css("cssText", "background:");
    $("#create").removeAttr("disabled");
    $(".delete").removeAttr("disabled");

    if (is_restart == "1") {
      ipcRenderer.send("isQuitAndInstall", [true]);
    } else {
      ipcRenderer.send("isQuitAndInstall", [false]);
    }
  }

  function exit2() {
    $("#box3").hide();
    $("#cover").css("cssText", "background:");
    $("#create").removeAttr("disabled");
    $(".delete").removeAttr("disabled");
  }

  let respath = null;
  let lnkList = {};
  let lnks_url=null;

  //接收传过来得配置信息
  ipcRenderer.on('toConfig', function (event, data) {
    respath = data[0];
    loadPortSet();
    lnks_url=data[1];
    loadInit(respath,data[1]);
  });

  let j = null;
  let lnk_url = null;

  //删除快捷方式
  function deleteLnk(index, url) {
    $("#box1").show();
    $("#cover").css("cssText", "background:#aaa");
    //禁用创建和删除按钮
    $("#create").attr("disabled", "disabled");
    $(".delete").attr("disabled", "disabled");
    j = index;
    lnk_url = url;
    return;
  }

  function deleteConfirm() {
    let lnks = {};
    $.each(lnkList, function (i, item) {
      if (i != j) {
        lnks[i] = item;
      }
    });
    lnkList=lnks;
    //删除存在的快捷方式
    if (fs.existsSync(desktop+dpth.sep+lnk_url)) {
      fs.unlinkSync(desktop+dpth.sep+lnk_url);
    }
    let jsonstr = JSON.stringify(lnks);
    fs.writeFileSync(lnks_url+dpth.sep+"lnks.json", jsonstr, function (err) {
      log.error("更新应用程序失败!");
    });
    //第四步删除当前页面dom结构
    let list = $(".lnk_code");
    for (let k = 0; k < list.length; k++) {
      if (list[k].innerHTML === j) {
        list[k].parentElement.remove();
      }
    }
    $("#box1").hide();
    $("#cover").css("cssText", "background:");
    $("#create").removeAttr("disabled");
    $(".delete").removeAttr("disabled");
  }

  //选择的客户端变化时
  function clientChange() {
    //获取端口url
    let myselect = document.getElementById("weburl");
    let index = myselect.selectedIndex;
    let weburl = myselect.options[index].value;
    let lastnum = $(".table tr:last").find(".lnk_code").text();
    let ind = 1
    if (lastnum !== '') {
      ind = parseInt(lastnum) + 1;
    }
    if (weburl === "pharmacy") {
      if (ind == 1) {
        $("#lnkName").val("钜星科技便民问诊系统-门店端");
        $("#cachePath").val("default");
      } else {
        $("#lnkName").val("钜星科技便民问诊系统-门店端" + ind);
        $("#cachePath").val("pharmacy-" + ind);
      }
    } else if (weburl === "doctor") {
      $("#lnkName").val("钜星科技便民问诊系统-医生端" + ind);
      $("#cachePath").val("doctor-" + ind);
    } else {
      $("#lnkName").val("钜星科技便民问诊系统-药师端" + ind);
      $("#cachePath").val("pharmacist-" + ind);
    }
  }

  //创建按钮点击事件
  $("#create").click(function () {
    $("#box").show();
    $("#cover").css("cssText", "background:#aaa");
    //禁用创建和删除按钮
    $("#create").attr("disabled", "disabled");
    $(".delete").attr("disabled", "disabled");

    let lastnum = $(".table tr:last").find(".lnk_code").text();
    let ind = 1
    if (lastnum !== '') {
      ind = parseInt(lastnum) + 1;
    }
    if (ind == 1) {
      $("#lnkName").val("钜星科技便民问诊系统-门店端");
      $("#cachePath").val("default");
    } else {
      $("#lnkName").val("钜星科技便民问诊系统-门店端" + ind);
      $("#cachePath").val("pharmacy-" + ind);
    }
    //点击创建按钮首先清楚所有的选项,然后加载端口选项
    $("#weburl").empty();
    loadPortSet();
  });

  //创建快捷方式
  function createInk() {
    //获取端口url
    let myselect = document.getElementById("weburl");
    let index = myselect.selectedIndex;
    let weburl = myselect.options[index].value;

    //获取快捷方式名称
    let InkName = $("#lnkName").val().trim();
    //获取缓存文件夹名称
    let cacheDir = $("#cachePath").val().trim();
    //第一步创建桌面快捷方式
    setlnk(InkName, weburl, cacheDir);
    //第二步将数据添加到setting.json文件中
    let lastnum = $(".table tr:last").find(".lnk_code").text();
    let itemNum = 1;
    if (lastnum != "") {
      itemNum = parseInt(lastnum) + itemNum;
    }
    let thisItem = {};
    if (weburl === "pharmacy") {
      thisItem.client = "门店端";
    } else if (weburl === "doctor") {
      thisItem.client = "医生端";
    } else {
      thisItem.client = "药师端";
    }
    thisItem.lnk_url = desktop + dpth.sep + InkName + ".lnk";
    thisItem.cache_dir = cacheDir;

    lnkList[itemNum] = thisItem;
    let jsonstr = JSON.stringify(lnkList);
    fs.writeFileSync(lnks_url+dpth.sep+"lnks.json", jsonstr, function (err) {
      log.error("创建快捷方式，写入文件失败!" + err);
    });
    $("#box").hide();
    $("#cover").css("cssText", "background:");
    $("#create").removeAttr("disabled");
    $(".delete").removeAttr("disabled");

    let list = $(".lnk_code");
    for (let k = 0; k < list.length; k++) {
        list[k].parentElement.remove();
    }
    loadLnkList(lnkList);
  }

  //
  function setlnk(lnkname, targetUrl, cacheDir) {
    //查看当前文件夹目录
    let thisurl = location.href;
    thisurl = thisurl.substring(8, thisurl.lastIndexOf("resources") - 1);
    if(fs.existsSync(desktop + dpth.sep + lnkname + ".lnk")){
      fs.unlinkSync(desktop + dpth.sep + lnkname + ".lnk");
    }
    //获取当前文件的绝对路径
    ws.create(desktop + dpth.sep + lnkname + ".lnk", {
      args: targetUrl + "--" + cacheDir + " --disable-gpu", //解决Electron app在部分windows7上运行黑屏或者不显示的问题
      //打包时修改exe文件路径
      target: decodeURIComponent(thisurl) + dpth.sep+"钜星科技便民问诊系统.exe",
      runStyle: ws.MIN,
      desc: "钜星科技便民问诊系统"
    }, function (err) {
      if (err) {
        console.log("创建快捷方式出错：" + err);
      }
    });
  }

  function exit() {
    $("#box").hide();
    $("#cover").css("cssText", "background:");
    $("#create").removeAttr("disabled");
    $(".delete").removeAttr("disabled");
  }

  function exit1() {
    $("#box1").hide();
    $("#cover").css("cssText", "background:");
    $("#create").removeAttr("disabled");
    $(".delete").removeAttr("disabled");
  }


  //选择下拉框填充
  function loadPortSet() {
    //加载到下拉框中
    let str = "<option value='pharmacy'>门店端</option>";
    str = str + "<option value='doctor'>医生端</option>"
    str = str + "<option value='pharmacist'>药师端</option>"
    $("#weburl").append(str);
  }

  //加载已创建的程序快捷方式
  function loadInit(respath,lnks_url) {
    log.info("快捷方式数据存放目录:"+lnks_url);
    if(!fs.existsSync(lnks_url)){
      fs.mkdirSync(lnks_url);
      fs.writeFileSync(lnks_url+dpth.sep+"lnks.json", JSON.stringify({}), function (err) {
      });
    }
    $.getJSON(lnks_url+dpth.sep+"lnks.json", function (data) {
      if (!$.isEmptyObject(data)) {
        loadLnkList(data);
        lnkList = data;
      }
    });
  }
  //加载存在快捷方式
  function loadLnkList(data) {
    $.each(data, function (i, item) {
      let str = "<tr>";
      str = str + "<td class='lnk_code'>" + i + "</td>";
      str = str + "<td>" + item.client + "</td>";
      str = str + "<td>" + item.lnk_url + "</td>";
      str = str + "<td>" + item.cache_dir + "</td>";
      let lnk_name=item.lnk_url.substring(item.lnk_url.lastIndexOf(dpth.sep)+1);
      let type=null;
      if(item.client=="门店端"){
        type="pharmacy"
      }else if(item.client=="医生端"){
        type="doctor"
      }else{
        type="pharmacist"
      }
      str = `${str}<td><input type='button' onclick='setlnk("${lnk_name}","${type}","${item.cache_dir}")' class='btn btn-success' value='重创快捷方式'/></td>`;
      str = `${str}<td><input type='button' onclick='deleteLnk("${i}" , "${lnk_name}")' class='btn btn-danger delete' value='删除'/></td>`;
      str = str + "</tr>"
      $(".table").append(str);
    });
  }
</script>
</body>
</html>
