<template>
  <div class="main pa-3">
    <m-filter :option="filter" @search="handleSearch" />
    <m-table
      class="mt-3"
      :loading="loading"
      :headers="headers"
      :items="items"
      :show-select="false"
      :is-tools="false"
      :disable-sort="true"
      :total="total"
      :page-info="pageInfo"
      @pageHandleChange="pageHandleChange"
    >
      <template #name="{ item }">
        <tool-tip :text="item.name" :width="200"></tool-tip>
      </template>
      <template #remark="{ item }">
        <tool-tip :text="item.remark" :width="200"></tool-tip>
      </template>
      <template #status="{ item }">
        <span :class="statusMsg[item.status] + '--text'">
          {{ taskStatus.find(e => e.value === item.status)?.label }}
        </span>
      </template>
      <template #actions="{ item }">
        <v-btn text color="success" @click="handleSchedule(item)">
          调度
        </v-btn>
        <v-btn :disabled="!+item.status" text color="success" @click="handleRun(item)">
          执行
        </v-btn>
        <v-btn text color="success" @click="handleRunSelf(item)">
          <v-progress-circular
              v-if="item.loading"
              indeterminate
              :size="18"
              width="2"
              style="margin-right: 6px"
            ></v-progress-circular>

          <v-icon v-else left>mdi-play</v-icon>
          手动执行
        </v-btn>
      </template>
    </m-table>
    <m-dialog :visible.sync="showSchedule" title="调度" @submit="handleDispatch" body-style="overflow-y: visible !important">
      <data-dispatch
        ref="dispatch"
        v-if="showSchedule"
        :updater="updater"
      />
    </m-dialog>
  </div>
</template>

<script>
import ToolTip from '@/components/Tooltip'
import MFilter from '@/components/Filter'
import MTable from '@/components/List/table'
import MDialog from '@/components/Dialog'
import DataDispatch from './components/dataDispatch'
import { getDataFactoryList } from '@/api/productionLine'
import {
  // productionLineBasePage,
  // productionLineBaseDetail,
  dataFactoryDictList,
  productionLineBaseStart,
  productionLineBaseDispatch
} from '@/api/dataFactory'

import { api } from '@/api/dataGovernance'
export default {
  name: 'production-line-dispatch',
  components: { MTable, MFilter, ToolTip, MDialog, DataDispatch },
  data () {
    return {
      statusMsg: ['grey', 'blue', 'green', 'orange', 'red'],
      showSchedule: false,
      filter: {
        list: [
          { type: 'textField', value: null, label: '名称', key: 'name' },
          { type: 'autocomplete', value: null, label: '状态', key: 'status', items: [] }
        ]
      },
      show: false,
      loading: false,
      headers: [
        { text: '名称', value: 'name' },
        { text: '英文名', value: 'en_name' },
        { text: '状态', value: 'status' },
        { text: '更新时间', value: 'updateTime' },
        { text: '创建时间', value: 'createTime' },
        { text: '备注', value: 'remark' },
        { text: '操作', value: 'actions' }
      ],
      items: [],
      pageInfo: {
        size: 10,
        current: 1
      },
      total: 0,
      query: {
        name: null
      },
      dispatchData: null,
      taskStatus: [],
      log: {
        info: null,
        drawer: false
      }
    }
  },
  created () {
    this.getDict()
    this.init()
  },
  computed: {
    updater () {
      if (!this.dispatchData) return null
      return this.dispatchData.updater
    }

  },
  methods: {
    async init () {
      this.loading = true
      try {
        const { data } = await getDataFactoryList({ ...this.query, ...this.pageInfo })
        this.items = data.records.map(e => {
          return {
            ...e,
            loading: false
          }
        })
        this.total = data.total
      } catch (error) {
        this.$snackbar.error(error)
      } finally {
        this.loading = false
      }
    },
    async getDict () {
      try {
        const { data } = await dataFactoryDictList({ type: 'production_line_run_status' })
        this.taskStatus = data[0]?.itemList ?? []
        this.filter.list.find(e => e.key === 'status').items = data[0]?.itemList ?? []
      } catch (error) {
        this.$snackbar.error(error)
      }
    },
    handleSearch (val) {
      Object.assign(this.query, val)
      this.pageInfo.current = 1
      this.init()
    },
    // 调度
    async handleSchedule ({ id }) {
      try {
        // const { data } = await productionLineBaseDetail({ id })
        // this.dispatchData = data
        this.showSchedule = true
      } catch (error) {
        this.$snackbar.error(error)
      }
    },
    async handleDispatch () {
      const obj = this.$refs.dispatch.getValue()
      Object.assign(obj, {
        id: this.dispatchData.id
      })
      try {
        await productionLineBaseDispatch(obj)
        this.$snackbar.success('操作成功')
        this.init()
      } catch (error) {
        this.$snackbar.error(error)
      } finally {
        this.showSchedule = false
      }
    },
    async handleRun ({ id }) {
      try {
        await productionLineBaseStart({ id })
        this.$snackbar.success('启动成功')
      } catch (error) {
        this.$snackbar.error(error)
      }
    },
    // 手动执行
    async handleRunSelf (item) {
      if (item.loading === true) {
        return
      }
      if (!item.en_name) return this.$snackbar.warning('目标表名不存在')
      // const { id, type } = Object.values(item.nodeProperty).pop()
      item.loading = true
      await this.handleRunResource({ dependency_level: 'resource', target_table: item.en_name })
      // if (type === 'data_resource') {
      //   await this.handleRunResource(id)
      // }
      // if (type === 'data_model') {
      //   await this.sourceModelTrain(id)
      // }
      // if (type === 'readUnstructuredResource') {
      //   await this.handleRunUnstructuredResource(id)
      // }
      item.loading = false
    },
    // 结构化 运行
    async handleRunResource (query) {
      try {
        await api.productionLineDispatch(query)
        this.$snackbar.success('执行成功')
      } catch (error) {
        this.$snackbar.error(error)
      }
    },
    // 非结构化运行
    async handleRunUnstructuredResource (id) {
      try {
        await api.runUnstructuredMetadata({ id })
        this.$snackbar.success('执行成功')
      } catch (error) {
        this.$snackbar.error(error)
      }
    },
    // 大模型训练
    async sourceModelTrain (id) {
      try {
        const { data } = await api.getResourceDetails({ id })
        // 执行训练
        const { data: ddl } = await api.getDDL({ id })

        if (!ddl.DDL) {
          this.$snackbar.error('不存在DDL，执行尚未结束，请稍后再试')
          return
        }

        await api.setDDLTrain({
          ddl: ddl.DDL.replace(/\n/g, ''),
          documentation: `our definition of ${data.resource_en} is ${data.resource}`
        })
        this.$snackbar.success('操作成功')
      } catch (error) {
        this.$snackbar.error(error)
      }
    },
    pageHandleChange (index) {
      this.pageInfo.current = index
      this.init()
    }
  }
}
</script>

<style lang="scss" scoped>
.main {
  width: 100%;
  height: 100%;
  background: #FFF;
}
</style>
