<template>
  <div>
    <DataView v-bind="vbind" v-if="vbind" @dataevent="dockerEvent"></DataView>
  </div>
</template>
<script>
import DataTable from "@/components/datatable/DataTable"
export default {
  components: {DataTable},
  props: ['curtab', 'ssh', 'notitle', 'vpagename'],
  data() {
    return {
      vbind: undefined
    }
  },
  async created() {
    this.getApi()
  },
  methods: {
    dockerEvent(row, field, event) {
      if(event==='stop') this.doAction(`docker stop ${row.Names}`)
      else if(event==='start') this.doAction(`docker restart ${row.Names}`)
    },
    async getApi() {
      let data = {ssh: this.ssh || 1, path: '', cmd: `docker container ps -a --format "{{json .}}"`, user: this.$store.login.id}
      let arr = (await this.$insertapi('executecommand', data, undefined, false))['output']
      let rows = arr.map(v=>JSON.parse(v))
      this.vbind = undefined
      setTimeout(()=>this.vbind = {pagename: this.vpagename, setting: 'container-fields', data: rows})
    },
    choiceSsh() {
      this.showmodal = {component: 'DataView', title: 'Chọn SSH', width: '40%', height: '400px', 
      vbind: {api: 'ssh', setting: 'ssh-select', component: 'server/NewSsh'}}
    },
    async doAction(cmd) {
      console.log('doAction')
      let data = {ssh: this.ssh || 1, path: null, cmd: cmd, user: this.$store.login.id}
      let rs = (await this.$insertapi('executecommand', data, undefined, false))['output']
      if(rs==='error') return
      let obj = {ssh: this.ssh || 1, path: '', cmd: `docker container ps -a --format "{{json .}}"`, user: this.$store.login.id}
      rs = await this.$insertapi('executecommand', obj, undefined, false)
      let rows = rs.output.map(v=>JSON.parse(v))
      this.vbind = undefined
      setTimeout(() => this.vbind = {pagename: this.vpagename, setting: 'container-fields', data: rows}) 
    },
    async stop(row) {
      this.doAction(`docker stop ${row.Names}`)
    },
    async start(row) {
      this.doAction(`docker restart ${row.Names}`)
    }
  }
}
</script>