<template>
  <section class="list">
    <ai-list>
      <ai-title slot="title" title="定制方案" isShowBottomBorder/>
      <template #content>
        <ai-search-bar>
          <template #left>
            <el-button type="primary" icon="iconfont iconAdd" @click="handleAdd()">添加</el-button>
          </template>
          <template #right>
            <el-input size="small" placeholder="搜索" v-model="search.name" clearable @change="page.current=1,getTableData()"/>
          </template>
        </ai-search-bar>
        <ai-table :tableData="tableData" :total="page.total" :current.sync="page.current" :size.sync="page.size"
                  @getList="getTableData" :col-configs="colConfigs" :dict="dict">
          <el-table-column label="打包进度" slot="process">
            <template slot-scope="{row}">
              <span v-if="row.count==0" v-text="getProcessMsg(row)"/>
              <el-progress v-else :percentage="row.count"/>
            </template>
          </el-table-column>
          <el-table-column slot="options" label="操作" fixed="right" width="300" header-align="center">
            <template slot-scope="{row}">
              <el-button type="text" @click="handleAdd(row.id)">编辑</el-button>
              <el-button type="text" @click="handleDelete(row.id)">删除</el-button>
              <template v-if="!!row.dist">
                <el-button type="text" @click="handleUpdate(row)" v-if="row.count==0">打包更新</el-button>
                <el-button type="text" @click="handleCancelUpdate(row)" v-else>停止</el-button>
                <el-button type="text" @click="handleDownload(row)" v-if="row.dist">下载</el-button>
              </template>
            </template>
          </el-table-column>
        </ai-table>
      </template>
    </ai-list>
  </section>
</template>

<script>
export default {
  name: "list",
  props: {
    instance: Function,
    dict: Object,
    permissions: Function
  },
  data() {
    return {
      search: {name: ""},
      page: {current: 1, size: 10, total: 0},
      tableData: [],
      colConfigs: [
        {prop: "name", label: "项目/系统名称", width: 200},
        {prop: "type", label: "系统类型", dict: 'systemType', width: 120},
        {prop: "version", label: "版本号", width: 120},
        {prop: "customPath", label: "库项目根路径", width: 120},
        {prop: "dist", label: "更新路径"},
        {slot: 'process'},
      ],
      timer: {}
    }
  },
  methods: {
    getTableData() {
      this.instance.post("/node/custom/list", null, {
        params: {...this.page, ...this.search}
      }).then(res => {
        if (res?.data) {
          this.tableData = res.data.records.map(e => ({...e, count: 0}))
          this.page.total = res.data.total
        }
      })
    },
    handleAdd(id) {
      this.$router.push({hash: "#add", query: {id}})
    },
    handleDelete(ids) {
      this.$confirm("是否要删除?").then(() => {
        this.instance.post("/node/custom/delete", null, {
          params: {ids}
        }).then(res => {
          if (res?.code == 0) {
            this.$message.success("删除成功")
            this.getTableData()
          }
        })
      }).catch(() => 0)
    },
    handleDownload(row) {
      let {id} = row
      this.instance.post("/node/custom/download", null, {
        params: {id},
        responseType: "blob"
      }).then(res => {
        if (res?.code == 1) {
          this.$message.error(res.err)
        } else {
          const link = document.createElement('a')
          let blob = new Blob([res], {type: 'application/zip'})
          link.style.display = 'none'
          link.href = URL.createObjectURL(blob)
          link.setAttribute('download', row.name + '.zip')
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link)
        }
      })
    },
    handleUpdate(row) {
      let {id} = row, {timer} = this
      this.instance.post("/node/custom/getZip", null, {
        params: {id}
      }).then(res => {
        if (res?.code == 0) {
          row.count = 1
          timer[id] = setInterval(() => {
            if (row.count >= 100) {
              clearInterval(timer[id])
              row.count = 0
              this.$message.error("打包失败!")
            } else if (row.count % 2 == 0 && row.target) {
              row.count++
            } else this.getRowById(row.id).then(v => {
              if (v.error) {
                clearInterval(timer[id])
                this.$message.error("打包失败!")
                this.refreshRow(row, v)
                row.count = 0
              } else if (v.download) {
                clearInterval(timer[id])
                this.refreshRow(row, v)
                row.count = 0
              } else row.count++
            })
          }, 6000)
        }
      })
    },
    refreshRow(row, v) {
      row.error = v.error
      row.download = v.download
      row.zipTime = v.zipTime
    },
    getProcessMsg(row) {
      let time = row.zipTime ? this.$moment(row.download).diff(row.zipTime, 's', true) : ""
      return row.error || (row.download ? `最近打包时间:${row.download}(用时:${time}秒)` :
          row.zipTime ? `正在打包,开始于:${row.zipTime}` : `暂无打包`)
    },
    handleCancelUpdate(row) {
      let {id} = row
      return this.instance.post("/node/custom/cancelZip", null, {
        params: {id}
      }).then(res => {
        if (res?.code == 0) {
          clearInterval(this.timer[id])
          row.count = 0
          this.getRowById(row.id).then(v => this.refreshRow(row, v))
        }
      })
    },
    getRowById(id) {
      return this.instance.post("/node/custom/detail", null, {
        params: {id}
      }).then(res => {
        if (res?.data) return res.data
      })
    }
  },
  created() {
    this.getTableData()
  },
  beforeDestroy() {
    Object.values(this.timer).map(t => clearInterval(t))
  }
}
</script>

<style lang="scss" scoped>
.list {
  height: 100%;
}
</style>
