<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" />
  <title>医德帮-医保上传平台</title>
  <link th:href="@{css/bootstrap.min.css}" rel="stylesheet" media="all">
  <link th:href="@{css/materialdesignicons.min.css}" rel="stylesheet" media="all">
  <link th:href="@{css/style.min.css}" rel="stylesheet" media="all">
</head>

<body>
<div class="lyear-layout-web" id="export">
  <input type="hidden" id="userId"/>
  <div class="lyear-layout-container">
    <!--左侧导航-->
    <aside class="lyear-layout-sidebar">

      <!-- logo -->
      <div class="lyear-layout-sidebar-scroll">

        <nav class="sidebar-main">
          <ul class="nav nav-drawer">
            <li class="nav-item active"> <a href="javascript:void(0)" @click="jumpPage('index')"><i class="mdi mdi-home"></i>医德帮-医保上传平台</a> </li>
            <li class="nav-item nav-item-has-subnav">
              <a href="javascript:void(0)"><i class="mdi mdi-palette"></i>数据查询</a>
              <ul class="nav nav-subnav">
                <li> <a href="javascript:void(0)" @click="jumpPage('uploadInfo')">报文查询</a> </li>
                <li> <a href="javascript:void(0)" @click="jumpPage('uploadHistory')">历史数据查询</a> </li>
              </ul>
            </li>
            <li class="nav-item nav-item-has-subnav active open">
              <a href="javascript:void(0)"><i class="mdi mdi-format-align-justify"></i>数据上传</a>
              <ul class="nav nav-subnav">
                <li> <a href="javascript:void(0)" @click="jumpPage('batchUpload')">批量上传</a> </li>
                <li  class="active"> <a href="javascript:void(0)" @click="jumpPage('export')">数据导出</a> </li>
              </ul>
            </li>
            <li> <a href="javascript:void(0)" @click="jumpPage('uploadInfo')"><i class="mdi mdi-file-outline"></i>定时设置</a> </li>
          </ul>
        </nav>
      </div>

    </aside>
    <!--End 左侧导航-->

    <!--头部信息-->
    <header class="lyear-layout-header">

      <nav class="navbar navbar-default">
        <div class="topbar">

          <div class="topbar-left">
            <div class="lyear-aside-toggler">
              <span class="lyear-toggler-bar"></span>
              <span class="lyear-toggler-bar"></span>
              <span class="lyear-toggler-bar"></span>
            </div>
            <span class="navbar-page-title"></span>
          </div>
        </div>
      </nav>

    </header>
    <!--End 头部信息-->

    <!--页面主要内容-->
    <main class="lyear-layout-content">
      <div class="container-fluid">
        <div class="row">
          <div class="col-lg-12">
            <div class="card">
              <div class="card-header">
                <h4>批量导入导出</h4>
              </div>
              <div class="card-body">
                <div class="form-horizontal" role="form">
                  <fieldset>
                    <div class="form-group">
                      <label class="col-sm-2 control-label">批量上传</label>
                      <div class="col-sm-6">
                        <div class="alert-warning">文件路径D:\upload,格式为csv</div>
                        <input type="file" class="btn btn-primary" name="filePath" ref="filePath" id="filePath" multiple="multiple" @change="getFile"/>
                      </div>
                    </div>
                    <div class="form-group">
                      <label class="col-sm-2 control-label">导出住院数据</label>
                      <div class="col-sm-6">
                        <div class="alert-warning">文件路径D:\upload</div>
                        <button type="button" class="btn btn-primary" @click="exportHos">导出</button>
                      </div>
                    </div>
                    <div class="form-group">
                      <label class="col-sm-2 control-label">导出门诊数据</label>
                      <div class="col-sm-6">
                        <div class="alert-warning">文件路径D:\upload</div>
                        <button type="button" class="btn btn-primary" @click="exportCli">导出</button>
                      </div>
                    </div>
                  </fieldset>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </main>
  </div>
</div>

<script type="text/javascript" src="js/vue.js"></script>
<script type="text/javascript" src="js/laydate/laydate.js"></script>
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript" src="js/bootstrap.min.js"></script>
<script type="text/javascript" src="js/perfect-scrollbar.min.js"></script>
<script type="text/javascript" src="js/main.min.js"></script>
<script type="text/javascript" src="js/layer/layer.js"></script>
<script type="text/javascript" src="js/socket.js"></script>
<script>
  const app = new Vue({
    el: '#export',
    data: {
      chars: ['0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'],
      uploadMsg: "开始上传..",
      userId: null
    },
    mounted() {
      // this.userId = this.generateUserId(12)
      // console.log(this.userId)
      // this.openSocket()
    },
    methods: {
      generateUserId(n) {
        let res = "";
        for(let i = 0; i < n ; i ++) {
          let id = Math.ceil(Math.random()*35);
          res += chars[id];
        }
        return res
      },
      openSocket() {
        let socket
        let that = this
        if(typeof(WebSocket) == "undefined") {
          console.log("您的浏览器不支持WebSocket");
        }else{
          //实现化WebSocket对象，指定要连接的服务器地址与端口  建立连接
          // let userId = document.getElementById('userId').value;
          // let socketUrl="ws://127.0.0.1:22599/webSocket/"+userId;
          let socketUrl="ws://localhost:18080/webSocket/" + this.userId;
          console.log(socketUrl);
          if(socket!=null){
            socket.close();
            socket=null;
          }
          socket = new WebSocket(socketUrl);
          //打开事件
          socket.onopen = function() {
            console.log("websocket已打开");
            //socket.send("这是来自客户端的消息" + location.href + new Date());
          };
          //获得消息事件
          socket.onmessage = function(msg) {
            console.log(msg.data)
            this.uploadMsg+= msg.data + '</br>'
            $("#msgInfo").html(this.uploadMsg)
            that.$refs.end.scrollIntoView({
              behavior: "smooth",  // 平滑过渡
              block:    "start"  // 上边框与视窗顶部平齐。默认值
            });
          };
          //关闭事件
          socket.onclose = function() {
            console.log("websocket已关闭");
          };
          //发生了错误事件
          socket.onerror = function() {
            console.log("websocket发生了错误");
          }
        }
      },
      jumpPage(path) {
        window.location.href = path
      },
      dateFormat(fmt, date) {
        let ret;
        const opt = {
          "Y+": date.getFullYear().toString(),        // 年
          "m+": (date.getMonth() + 1).toString(),     // 月
          "d+": date.getDate().toString(),            // 日
          "H+": date.getHours().toString(),           // 时
          "M+": date.getMinutes().toString(),         // 分
          "S+": date.getSeconds().toString()          // 秒
          // 有其他格式化字符需求可以继续添加，必须转化成字符串
        };
        for (let k in opt) {
          ret = new RegExp("(" + k + ")").exec(fmt);
          if (ret) {
            fmt = fmt.replace(ret[1], (ret[1].length == 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, "0")))
          };
        };
        return fmt;
      },
      uploadCsv(fileNames) {
        let load = layer.msg('加载中', {
          icon: 16,
          shade: 0.01,
          time: false
        });
        // layer.open({
        //   type: 1,
        //   title: false, //不显示标题栏
        //   closeBtn: false,
        //   area: '300px;',
        //   shade: 0.8,
        //   id: 'LAY_layuipro',
        //   resize: false,
        //   btnAlign: 'c',
        //   moveType: 1, //拖拽模式，0或者1
        //   content: '<div id="msgInfo" style="overflow-y: auto;padding: 10px; width: 300px;height: 200px;line-height: 22px; background-color: #393D49; color: #fff; font-weight: 300;"></div><div ref="end" style="height:1px; overflow:hidden"></div>',
        //   success: function(layero){
        //     var btn = layero.find('.layui-layer-btn');
        //     btn.find('.layui-layer-btn0').attr({
        //       href: 'http://www.layui.com/'
        //       ,target: '_blank'
        //     });
        //   }
        // });
        $.ajax({
          type : "POST",
          data: {
            fileNames: fileNames,
            sid: this.userId
          },
          dataType: "json",
          traditional: true,
          url : "http://localhost:18080/upload/uploadByFile",
          success : function(res) {
            layer.close(load)
            if(res){
              alert("成功上传" + res + "条记录")
            } else {
              alert("上传失败")
            }
          },
          error : function(e){
            layer.close(load)
          }
        });
      },
      exportHos() {
        let load = layer.msg('加载中', {
          icon: 16,
          shade: 0.01,
          time: false
        });
        $.ajax({
          type : "GET",
          //请求地址
          url : "http://localhost:18080/export/exportHosByDate",
          success : function(res) {
            layer.close(load)
            if(res){
              alert("导出成功,主单数据" + res.preDateCount + "条,状态数据" + res.confDateCount + "条")
            } else {
              alert("导出失败")
            }
          },
          error : function(e){
            layer.close(load)
          }
        });
      },
      exportCli() {
        let load = layer.msg('加载中', {
          icon: 16,
          shade: 0.01,
          time: false
        });
        $.ajax({
          type : "GET",
          //请求地址
          url : "http://localhost:18080/export/exportCliByDate",
          success : function(res) {
            layer.close(load)
            if(res){
              alert("导出成功,主单数据" + res.preDateCount + "条,状态数据" + res.confDateCount + "条")
            } else {
              alert("导出失败")
            }
          },
          error : function(e){
            layer.close(load)
          }
        });
      },
      getFile() {
        let filePaths = this.$refs.filePath.files;
        let fileNames = []
        for(let i = 0; i < filePaths.length; i++) {
          let fileName = filePaths[i].name.replace(/.*(\/|\\)/, "");
          let fileExt = (/[.]/.exec(fileName)) ? /[^.]+$/.exec(fileName.toLowerCase()) : '';
          if(fileExt[0].toLowerCase() != 'csv') {
            alert("请选择csv格式文件")
            $("input[name=filePath]").val("")
            return false
          }
          fileNames.push(fileName)
        }
        this.uploadCsv(fileNames)
      }
    }
  })
</script>
</body>
</html>