<template>
  <div class="detail_contain">
    <p class="now_page_title">
      我的应用 / 部署的应用 / 应用详情 /
      <span>应用调试</span>
    </p>
    <div class="search_list">
      <div class="list_header">
        <span></span>
        <span>{{ $route.query.content == 1 ? "命令行" : "容器日志" }}</span>
        <el-select v-model="pod" placeholder="请选择">
          <el-option
            v-for="(item,index) in pod_arr"
            :key="index+60000"
            :label="item"
            :value="item"
          >
          </el-option>
        </el-select>
        <span v-if="$route.query.content == 0">位于</span>
        <el-select
          v-model="pod_group"
          placeholder="请选择"
          v-if="$route.query.content == 0"
        >
          <el-option
            v-for="(item,index) in pod_group_arr"
            :key="index+80000"
            :label="item"
            :value="item"
          >
          </el-option>
        </el-select>
        <span v-if="$route.query.content == 1">在 {{now_app}}</span>
        <div v-if="$route.query.content == 0" style="float:right;">
            <el-tooltip class="item" effect="dark" content="显示时间戳" placement="top">
                <div class="time" @click="change_contl(0)" :style="control_arr[0]?{backgroundImage:'url('+require('../../../assets/imgs/rqrz_btn_time_sel.png')+')'}:''"></div>
            </el-tooltip>
            <el-tooltip class="item" effect="dark" content="自动刷新（每10s）" placement="top">
                <div class="restart" @click="change_contl(1)" :style="control_arr[1]?{backgroundImage:'url('+require('../../../assets/imgs/rqrz_btn_refresh_sel.png')+')'}:''"></div>
            </el-tooltip>
            <el-tooltip class="item" effect="dark" content="显示以前的日志" placement="top">
                <div class="recode" @click="change_contl(2)" :style="control_arr[2]?{backgroundImage:'url('+require('../../../assets/imgs/rqrz_btn_look_sel.png')+')'}:''"></div>
            </el-tooltip>
            <el-tooltip class="item" effect="dark" content="下载" placement="top">
                <div class="download" @click="download"></div>
            </el-tooltip>
        </div>
      </div>
      <el-scrollbar class="record_contain" v-if="$route.query.content == 0">
        <p
          v-for="(item, index) in data_arr"
          :key="index + 89000"
          v-html="(control_arr[0]?item.timestamp:'')+item.content"
        ></p>
      </el-scrollbar>
      <div id="xterm_contain" v-if="$route.query.content == 1"></div>
      <p class="code" v-if="$route.query.content == 0">
        <span>日志范围从 {{from_log}} 到 {{to_log}}</span>
        <img
          :src="item[logFilePosition=='end'&&(index==0||index==1)?1:logFilePosition=='beginning'&&(index==2||index==3)?1:0]"
          alt=""
          v-for="(item, index) in image_arr"
          @click="page(3-index,logFilePosition=='end'&&(index==0||index==1)?1:logFilePosition=='beginning'&&(index==2||index==3)?1:0)"
          :style="logFilePosition=='end'&&(index==0||index==1)?{cursor:'not-allowed'}:logFilePosition=='beginning'&&(index==2||index==3)?{cursor:'not-allowed'}:0"
          :key="index + 12000"
        />
      </p>
      <div class="back" @click="$router.back(-1)">返回</div>
    </div>
    <apass-dialog
      ref="actiondialog"
      title="下载日志文件"
      sunbmitText="保存"
      :submitDisable="download_flag"
      @submit="save_file"
    >
      <template slot="content">
        <div>
          <div style="margin:20px 0;line-height:30px;">
            <p>请等待下载完成</p>
            <p>已下载： {{process}}</p>
          </div>
          <el-progress :percentage="process" :format="format"></el-progress>
        </div>
      </template>
    </apass-dialog>
  </div>
</template>

<script>
import "xterm/css/xterm.css";
import { Terminal } from "xterm";
import { FitAddon } from 'xterm-addon-fit';
import apassDialog from '@/components/apass-dialog'
import helper from '@/services/helper'
import SockJS from "sockjs-client";
export default {
  props: [],
  components: {
    apassDialog
  },
  data() {
    return {
      pod: "",
      image_arr: [
        [
          require('../../../assets/imgs/btn_last_page.png'),
          require('../../../assets/imgs/btn_last_page_dis.png')
        ],
        [
          require('../../../assets/imgs/btn_next_page.png'),
          require('../../../assets/imgs/btn_next_page_dis.png')
        ],
        [
          require('../../../assets/imgs/btn_previous_page.png'),
          require('../../../assets/imgs/btn_previous_page_dis.png')
        ],
        [
          require('../../../assets/imgs/btn_front_page.png'),
          require('../../../assets/imgs/btn_front_page_dis.png')
        ],
      ],
      control_arr:[0,0,0],
      pod_arr: [],
      pod_group: "",
      from_log:'',
      to_log:'',
      process:0,
      pod_group_arr: [],
      temp_time:'',
      download_flag:true,
      data_arr: [],
      logFilePosition:'',
      referenceTimestamp:'',
      offsetFrom:'',
      offsetTo:'',
      referenceLineNum:'',
      filecontant:'',
      now_app:'',
      term:'',
      conn_: null,
      connected_: false,
      connectSucceed_: false,
      connectSucceedString_: "\u001b[",
      connectionClosed_: false,
      id: "",
      token: ""
    };
  },
  watch: {},
  computed: {},
  created() {
    if (this.$route.query.content == 0) {
      this.get_pod_list()
      this.get_now_pod()
    }else{
      this.get_contain_list()
      this.pod = this.$route.query.container
      this.now_app = this.$route.query.name
    }
  },
  mounted() {
    if (this.$route.query.content == 1) {
      this.initTerm()
      this.setinit()
    }
  },
  methods: {
    setinit: function() {
      var urlParams = {
        namespace: this.$route.params.namespace,
        name: this.$route.params.name,
        containers: this.$route.params.containers
      };
        this.$http
        .get(`/apaas/rest/kubernetes/api/v1/pod/${this.$route.query.namespace}/${this.$route.query.name}/shell/${this.$route.query.container}`)
        .then((response) => {
          this.id = response.data.id;
          if (this.id != undefined && this.id.length > 0) {
            // 建立连接
            this.setupConnection();
          }
          this.token = response.data.id;
        })
    },
    initTerm() {
      this.term = new Terminal({
        // cols: 40,
        // rows: 30,
        fontSize: 14,
        fontFamily: 'Consolas, "Courier New", monospace',
        bellStyle: "sound",
        cursorBlink: true
      });
      const fitAddon = new FitAddon();
      this.term.loadAddon(fitAddon);
      this.term.open(document.getElementById("xterm_contain"));
      fitAddon.fit();

      window.addEventListener("resize", () => {
        fitAddon.fit();
      });

      this.term.onData(this.onTerminalSendString.bind(this));
      //  this.term.write('\u001b[');
      this.term.onResize(this.onTerminalResize.bind(this));
      // this.term.fit();
    },
    onTerminalSendString: function(key) {
      var _this = this;
      if (this.connected_) {
        this.conn_.send(
          JSON.stringify({
            Op: "stdin",
            Data: key,
            Cols: this.term.cols,
            Rows: this.term.rows
          })
        );
      }
    },
    onTerminalResize: function() {
      if (this.connected_) {
        this.conn_.send(
          JSON.stringify({
            Op: "resize",
            Cols: this.term.cols,
            Rows: this.term.rows
          })
        );
      }
    },
    setupConnection: function() {
      var self = this;
      this.conn_ = new SockJS(`/awecloud/proxy/wss/api/sockjs?${self.id}`);
      this.conn_.onopen = function() {
        var startData = { Op: "bind", SessionID: self.id };
        self.conn_.send(JSON.stringify(startData));
        self.connected_ = true;
        // Make sure the terminal is with correct display size.
        self.onTerminalResize();

        // Focus on connection
      };
      this.conn_.onmessage = function(event) {
        const msg = JSON.parse(event.data);
        self.handleConnectionMessage(msg);

        // console.log(msg)
        // self.term.write(msg.Data);
      };
      this.conn_.onclose = this.onConnectionClose.bind(this);
    },

    handleConnectionMessage: function(msg) {
      var self = this;
      if (msg.Op === "stdout") {
        self.term.write(msg.Data);
      }
    },
    onConnectionClose: function(event) {
      if (!this.connected_) {
        return;
      }
      this.conn_.close();
      this.connected_ = false;
      this.connectionClosed_ = true;
      console.log("断开连接", event);
    },
    get_contain_list(){
      this.$http
        .get(`/apaas/rest/kubernetes/api/v1/pod/${this.$route.query.namespace}/${this.$route.query.name}/container`)
        .then((response) => {
          this.pod_arr = response.data.containers;
        })
    },
    page(index,flag) {
      if(flag==1){
        return
      }
      if (index == 0) {
        // 上一页
        this.logFilePosition = "beginning";
        this.referenceTimestamp = "oldest";
        this.referenceLineNum = 0;
        this.offsetFrom = -2000000100;
        this.offsetTo = -2000000000;
        this.get_now_pod({
          logFilePosition: this.logFilePosition,
          referenceTimestamp: this.referenceTimestamp,
          referenceLineNum: this.referenceLineNum,
          offsetFrom: this.offsetFrom,
          offsetTo: this.offsetTo,
          previous: this.control_arr[2]==1
        });
        console.log("0");
      } else if (index == 1) {
        // 上移

        this.referenceLineNum = -1;
        console.log(this.offsetFrom);
        this.offsetFrom = this.offsetFrom - 100;
        this.offsetTo = this.offsetTo - 100;
        console.log(this.offsetFrom);;
        this.get_now_pod({
          logFilePosition: this.logFilePosition,
          referenceTimestamp: this.referenceTimestamp,
          referenceLineNum: this.referenceLineNum,
          offsetFrom: this.offsetFrom,
          offsetTo: this.offsetTo,
          previous: this.control_arr[2]==1
        });
        console.log("1");
      } else if (index == 2) {
        // 下移

        //   现在
        this.referenceLineNum = -1;
        this.offsetFrom = this.offsetFrom + 100;
        this.offsetTo = this.offsetTo + 100;
        this.get_now_pod({
          logFilePosition: this.logFilePosition,
          referenceTimestamp: this.referenceTimestamp,
          referenceLineNum: this.referenceLineNum,
          offsetFrom: this.offsetFrom,
          offsetTo: this.offsetTo,
          previous: this.control_arr[2]==1
        });
        console.log("2");
      } else if (index == 3) {
        // 下一页

        this.logFilePosition = "end";
        this.referenceTimestamp = "newest";
        this.referenceLineNum = 0;
        this.offsetFrom = 2000000000;
        this.offsetTo = 2000000100;;
        this.get_now_pod({
          logFilePosition: this.logFilePosition,
          referenceTimestamp: this.referenceTimestamp,
          referenceLineNum: this.referenceLineNum,
          offsetFrom: this.offsetFrom,
          offsetTo: this.offsetTo,
          previous: this.control_arr[2]==1
        });
        console.log("3");
      }
    },
      get_pod_list(){
        this.$http
        .get(`/apaas/rest/kubernetes/api/v1/log/source/${this.$route.query.namespace}/${this.$route.query.name}/pod`)
        .then((response) => {
          console.log(response);
          this.pod_arr = response.data.containerNames
          this.pod_group_arr = response.data.podNames
        })
      },
      get_now_pod(url){
        var temp_url = `/apaas/rest/kubernetes/api/v1/log/${this.$route.query.namespace}/${this.$route.query.name}/${this.$route.query.container}`
        
        this.$http
        .get(temp_url,{params:url})
        .then((response) => {
          console.log(response);
          this.pod = response.data.info.containerName;
          this.pod_group = response.data.info.podName;
          this.from_log = helper.CreationDateDesc(response.data.info.fromDate);
          this.to_log = helper.CreationDateDesc(response.data.info.toDate);
          this.logFilePosition = response.data.selection.logFilePosition;
          this.referenceTimestamp =
            response.data.selection.referencePoint.timestamp;
          this.offsetFrom = response.data.selection.offsetFrom;
          this.offsetTo = response.data.selection.offsetTo;
          this.data_arr = response.data.logs;
        })
      },
      getdata(){
          return '54555555'
      },
      change_contl(n){
          if(this.control_arr[n]){
              this.$set(this.control_arr,n,0)
          }else{
              this.$set(this.control_arr,n,1)
          }

          if(n==1){
            if(this.control_arr[n]==1){
              this.temp_time=setInterval(()=>{
                this.logFilePosition = "end";
                this.referenceTimestamp = "newest";
                this.referenceLineNum = 0;
                this.offsetFrom = 2000000000;
                this.offsetTo = 2000000100;
                this.get_now_pod({
                  logFilePosition: this.logFilePosition,
                  referenceTimestamp: this.referenceTimestamp,
                  referenceLineNum: this.referenceLineNum,
                  offsetFrom: this.offsetFrom,
                  offsetTo: this.offsetTo,
                  previous: this.control_arr[2]==1
                });
              },10000)
            }else{
              clearInterval(this.temp_time)
            }
          }

          if(n==2){
            if(this.control_arr[n]==1){
              this.logFilePosition = "end";
              this.referenceTimestamp = "newest";
              this.referenceLineNum = 0;
              this.offsetFrom = 2000000000;
              this.offsetTo = 2000000100;

              this.get_now_pod({
                logFilePosition: this.logFilePosition,
                referenceTimestamp: this.referenceTimestamp,
                referenceLineNum: this.referenceLineNum,
                offsetFrom: this.offsetFrom,
                offsetTo: this.offsetTo,
                previous: this.control_arr[2]==1
              });
            }else{
              this.logFilePosition = "end"; 
              this.referenceTimestamp = "newest";
              this.referenceLineNum = 0;
              this.offsetFrom = 2000000000;
              this.offsetTo = 2000000100;
              this.get_now_pod({
                logFilePosition: this.logFilePosition,
                referenceTimestamp: this.referenceTimestamp,
                referenceLineNum: this.referenceLineNum,
                offsetFrom: this.offsetFrom,
                offsetTo: this.offsetTo,
                previous: this.control_arr[2]==1
              });
            }
          }
      },
      download(){
        var temp = setInterval(()=>{
          this.process=this.process+4
            if(this.process>=99){
              clearInterval(temp)
              this.process = 100
              this.download_flag = false
            }
          },100)
        this.$refs.actiondialog.show();
        this.$http
        .get(`/apaas/rest/kubernetes/api/v1/log/file/${this.$route.query.namespace}/${this.$route.query.name}/${this.$route.query.container}?previous=${this.control_arr[2]==1}`)
        .then((response) => {
          if (response.status == 200) {
            this.process = 100;
            this.download_flag = false
            clearInterval(temp)
            this.filecontant = response.data;
          }
        })
      },
      format(n){
        return ''
      },
      save_file(){
        var filename = "logs-form-" + this.pod + "-" + this.pod_group;
        var a = document.createElement("a");
        var blob = new Blob([this.filecontant]);
        a.download = filename;
        a.href = URL.createObjectURL(blob);
        a.click();
        URL.revokeObjectURL(blob);
      }

      
  },
};
</script>

<style>
.search_list .el-scrollbar__wrap {
  overflow-x: hidden;
}
.search_list .el-scrollbar {
  border-radius: 0px;
}
#xterm_contain ::-webkit-scrollbar {
width: 0px; /*对垂直流动条有效*/
height: 10px; /*对水平流动条有效*/
}

/*定义滚动条的轨道颜色、内阴影及圆角*/
#xterm_contain ::-webkit-scrollbar-track{
background-color: rosybrown;
border-radius: 3px;
}


/*定义滑块颜色、内阴影及圆角*/
#xterm_contain ::-webkit-scrollbar-thumb{
border-radius: 7px;
background-color: #E8E8E8;
}

/*定义两端按钮的样式*/
#xterm_contain ::-webkit-scrollbar-button {
background-color:cyan;
}

/*定义右下角汇合处的样式*/
#xterm_contain ::-webkit-scrollbar-corner {
background:khaki;
}
</style>
<style scoped>

.detail_contain {
  width: 100%;
  padding: 0 20px;
  height: calc(100% - 25px);
}
.now_page_title {
  margin: 15px 0;
  color: #898d9e;
}
.now_page_title span {
  color: #242c43;
}
.search_list {
  width: 100%;
  height: calc(100% - 45px);
  margin-top: 20px;
  background-color: #ffffff;
  box-shadow: 0px 3px 6px 0px #f4f7fc;
  border-radius: 12px;
}
.list_header {
  height: 80px;
  padding: 20px;
}
.list_header span:nth-of-type(1) {
  width: 4px;
  height: 16px;
  background-color: #515fe7;
  border-radius: 2px;
  display: inline-block;
  margin-right: 10px;
  margin-top: 10px;
  vertical-align: -2px;
}
.list_header span:nth-of-type(2) {
  font-size: 16px;
  font-weight: 600;
  margin-right: 50px;
}
.list_header span:nth-of-type(3) {
  margin-left: 10px;
  margin-right: 10px;
}
.record_contain {
  width: 100%;
  height: calc(100% - 200px);
  background-color: #1d1e20;
  padding: 30px;
  padding-right: 0;
}
.record_contain p {
  font-size: 14px;
  color: #e3e5ef;
}
#xterm_contain{
    height: calc(100% - 200px);
}
.code {
  margin-left: 32px;
  margin-top: 15px;
}
.code span {
  color: #1a2236;
}
.code img {
  float: right;
  margin-right: 35px;
  cursor: pointer;
}
.back {
  width: 124px;
  height: 44px;
  line-height: 44px;
  text-align: center;
  background-color: #0f2683;
  border-radius: 8px;
  font-size: 16px;
  margin-left: 32px;
  color: #f8f9fd;
  cursor: pointer;
  margin-top: 15px;
}
.time,.restart,.recode,.download{
    width: 18px;
    height: 18px;
    background-size: contain;
    margin-top: 10px;
    margin-right: 40px;
    float: left;
    cursor: pointer;
}
.time{
    background-image: url('../../../assets/imgs/rqrz_btn_time.png');
}
.time:hover{
    background-image: url('../../../assets/imgs/rqrz_btn_time_sel.png');
}
.restart{
    background-image: url('../../../assets/imgs/rqrz_btn_refresh.png');
}
.restart:hover{
    background-image: url('../../../assets/imgs/rqrz_btn_refresh_sel.png');
}
.recode{
    background-image: url('../../../assets/imgs/rqrz_btn_look.png');
}
.recode:hover{
    background-image: url('../../../assets/imgs/rqrz_btn_look_sel.png');
}
.download{
    background-image: url('../../../assets/imgs/rqrz_btn_download.png');
}
</style>
