<template>
  <div class="content white">
    <v-banner class="mb-3">
      训练数据统计
      <template v-slot:actions>
        <v-btn
          text
          color="primary"
          @click="getStatistics"
        >
          <v-icon left>mdi-refresh</v-icon>
          刷新
        </v-btn>
      </template>
    </v-banner>
    <v-container v-loading="loading">
      <v-row >
        <v-col
          v-for="elevation in elevations"
          :key="elevation.value"
        >
          <v-card
            class="pa-2"
            tile
            height="150"
          >
            <div class="d-flex align-center justify-center flex-column" style="height: 100%;">
              <div class="text-h3" :class="`${elevation.textColor}--text`">{{ itemData[elevation.value] }}</div>
              <div>
                {{ elevation.text }}
                <span class="success--text">
                  {{ itemData.type_percentages?.[elevation.value] ? `( ${itemData.type_percentages?.[elevation.value]}% )` : null }}
                </span>
              </div>
            </div>
          </v-card>
        </v-col>
      </v-row>

    </v-container>
    <v-divider class="my-3"></v-divider>
    <div class="pa-3">
      <MSearch class="mb-3" :option="filter" @search="handleSearch"></MSearch>
      <MTable
        :headers="headers"
        :items="items"
        :loading="tableLoading"
        :total="total"
        :page-info="pageInfo"
        @delete="handleDelete"
        @pageHandleChange="pageHandleChange"
        @sort="handleSort"
        @add="handleAdd"
      >
        <template #navBtn>
          <v-btn color="primary" class="buttons mr-3" rounded elevation="5" @click="handleCombine">
            <v-icon left>mdi-vector-combine</v-icon>
            去重
          </v-btn>
          <v-btn color="primary" class="buttons" rounded elevation="5" @click="handleUpload">
            <v-icon left>mdi-import</v-icon>
            导入
          </v-btn>
        </template>
        <template #question="{ item }">
          <span style="max-width: 300px;" class="d-inline-block text-truncate">{{ item.question }}</span>
        </template>
        <template #content="{ item }">
          <span style="max-width: 300px;" class="d-inline-block text-truncate">{{ item.content }}</span>
        </template>
        <template #actions="{ item }">
          <v-btn text color="primary" @click="handleDetails(item)">查看</v-btn>
          <v-btn text color="primary" @click="handleEdit(item)">编辑</v-btn>
          <v-btn text color="error" @click="handleDelete([item.id])">删除</v-btn>
        </template>
      </MTable>
    </div>
    <ModelTrainManageEdit ref="ModelTrainManageEditRefs" @success="onOpen"></ModelTrainManageEdit>
    <ModelTrainManageCombine ref="modelTrainManageCombineRefs" @success="init"></ModelTrainManageCombine>
    <ModelTrainManageUpload ref="modelTrainManageUploadRefs" @success="init"></ModelTrainManageUpload>
  </div>
</template>

<script>
import {
  getTrainingData,
  getTrainingDataList,
  deleteTrainingData
} from '@/api/dataChart'
import MTable from '@/components/List/table.vue'
import MSearch from '@/components/Filter'
import ModelTrainManageEdit from './modelTrainManageEdit.vue'
import ModelTrainManageCombine from './modelTrainManageCombine.vue'
import ModelTrainManageUpload from './modelTrainManageUpload.vue'
export default {
  name: 'ModelTrain',
  components: {
    MTable,
    MSearch,
    ModelTrainManageEdit,
    ModelTrainManageUpload,
    ModelTrainManageCombine
  },
  data () {
    return {
      searchValues: {},
      filter: {
        list: [
          { type: 'textField', value: null, label: '关键词', key: 'search_keyword', placeholder: '请输入关键词' },
          {
            type: 'autocomplete',
            key: 'training_data_type',
            value: null,
            label: '类型 *',
            placeholder: '请选择类型',
            items: [
              { label: 'sql', value: 'sql' },
              { label: 'documentation', value: 'documentation' },
              { label: 'ddl', value: 'ddl' },
              { label: 'error_sql', value: 'error_sql' }
            ]
          }
        ]
      },
      loading: false,
      elevations: [
        { text: '总数据量', value: 'total_count', textColor: 'primary' },
        { text: 'DDL类型', value: 'ddl', textColor: 'info' },
        { text: 'SQL类型', value: 'sql', textColor: 'info' },
        { text: '文档类型', value: 'documentation', textColor: 'info' },
        { text: '错误SQL类型', value: 'error_sql', textColor: 'error' }
      ],
      itemData: {},
      tableLoading: false,
      headers: [
        { text: 'ID', value: 'id' },
        { text: '问题', value: 'question' },
        { text: '类型', value: 'training_data_type' },
        { text: '内容', value: 'content' },
        { text: '操作', value: 'actions' }
      ],
      items: [],
      total: 0,
      orders: [],
      pageInfo: {
        size: 5,
        current: 1
      }
    }
  },
  created () {
    this.onOpen()
  },
  methods: {
    onOpen () {
      this.init()
      this.getStatistics()
    },
    async getStatistics () {
      this.loading = true
      try {
        const { data } = await getTrainingData()
        this.itemData = {
          ...data,
          ...data.type_breakdown
        }
      } catch (error) {
        this.$snackbar.error(error)
      } finally {
        this.loading = false
      }
    },
    async init () {
      this.tableLoading = true
      const orders = {
        sort_by: undefined,
        sort_order: undefined
      }
      if (this.orders.length) {
        Object.assign(orders, {
          sort_by: this.orders[0].column.replace(/`/g, ''),
          sort_order: this.orders[0].asc ? 'asc' : 'desc'
        })
      }
      try {
        const { data } = await getTrainingDataList({
          page: this.pageInfo.current,
          page_size: this.pageInfo.size,
          ...this.searchValues,
          ...orders
        })
        this.items = data.records
        this.total = data.pagination.total
      } catch (error) {
        this.$snackbar.error(error)
      } finally {
        this.tableLoading = false
      }
    },
    handleSearch (v) {
      this.searchValues = v
      this.pageInfo.current = 1
      this.init()
    },
    handleAdd () {
      this.$refs.ModelTrainManageEditRefs.open()
    },
    handleDetails (item) {
      this.$refs.ModelTrainManageEditRefs.open(item, true)
    },
    handleCombine () {
      this.$refs.modelTrainManageCombineRefs.open()
    },
    async handleUpload (file) {
      this.$refs.modelTrainManageUploadRefs.open()
    },
    pageHandleChange (index) {
      this.pageInfo.current = index
      this.init()
    },
    handleSort (v) {
      this.orders = v
      this.init()
    },
    handleEdit (item) {
      this.$refs.ModelTrainManageEditRefs.open(item)
    },
    handleDelete (ids) {
      if (Array.isArray(ids) && !ids.length) {
        this.$snackbar.warning('请选择要删除的数据')
        return
      }
      this.$confirm('提示', '确定删除吗？').then(async () => {
        try {
          await deleteTrainingData({
            ids,
            confirm: true
          })
          this.$snackbar.success('删除成功')
          this.onOpen()
        } catch (error) {
          this.$snackbar.error(error)
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.content {
  font-size: 16px;
}
</style>
