<template>
  <!-- 元数据 -->
  <div class="pa-3 white">
    <filter-list @search="handleSearch" />
    <table-list
      class="mt-3"
      :loading="loading"
      :headers="headers"
      :items="items"
      :total="total"
      :page-info="pageInfo"
      :is-tools="false"
      :show-select="false"
      @pageHandleChange="pageHandleChange"
      @sort="handleSort"
    >
      <template #status="{ item }">
        <v-chip
          :color="item.status ? 'success' : 'error'"
          small
        >
          {{ item.status ? '已启用' : '已禁用'}}
        </v-chip>
      </template>
      <template #tag="{ item }">
        {{ item.tag.map(e => e.name_zh).join(',') }}
      </template>
      <template v-slot:navBtn>
        <v-btn class="elevation-5 buttons mr-3" color="primary" rounded @click="handleAdd">
          <v-icon left>mdi-plus</v-icon>
          新增元数据
        </v-btn>
      </template>
      <template #actions="{ item }">
        <v-btn
          text
          :disabled="loading"
          color="primary"
          @click="handleEdit(item)"
        >
          编辑
        </v-btn>
        <v-btn
          text
          :disabled="loading"
          color="error"
          @click="handleDelete(item.id)"
        >
          删除
        </v-btn>
        <v-btn
          text
          :disabled="loading"
          :color="item.status ? 'error' : 'success'"
          @click="handleChangeStatus(item)"
        >
          {{ item.status ? '禁用' : '启用' }}
        </v-btn>
        <v-btn
          text
          color="indigo"
          @click="handleAddAudit(item)"
        >
          添加审核
        </v-btn>
      </template>
    </table-list>

    <edit-dialog :visible.sync="show" :title="title" @submit="handleSubmit">
      <edit v-if="show" v-loading="submitLoading" ref="form" class="mt-5" :item-data="itemData"></edit>
    </edit-dialog>

    <edit-dialog
      :visible.sync="showAudit"
      title="创建审核记录"
      width-type="0"
      @submit="handleAuditSubmit"
      @close="handleAuditClose"
    >
      <add-audit v-if="showAudit" ref="formAudit" :item-data="itemDataAudit"></add-audit>
    </edit-dialog>

    <!-- 智能助手 -->
    <!-- <assistant-iframe
      title="元数据智能助手"
      subTitle="我可以帮您管理元数据，支持查询、新增、更新、删除和标签管理"
      inputPlaceholder="请输入您的需求，例如：查看所有元数据"
      iframe-url="http://localhost:5678/webhook/9d5a941e-e1fd-42a3-afb4-ad6249d5f6e6/chat"
    /> -->
  </div>
</template>

<script>
import FilterList from '../components/Filter'
import TableList from '@/components/List/table'
import EditDialog from '@/components/Dialog'
import Edit from './components/edit'
import AddAudit from './components/addAudit'
// import AssistantIframe from '@/components/AssistantIframe'

import { api } from '@/api/dataGovernance'
export default {
  name: 'meta-data',
  components: { FilterList, TableList, EditDialog, Edit, AddAudit },
  data () {
    return {
      submitLoading: false,
      show: false,
      loading: false,
      showAudit: false,
      headers: [
        { text: '中文名', value: 'name_zh' },
        { text: '英文名', value: 'name_en' },
        { text: '分类', value: 'category', sortable: false },
        { text: '描述', value: 'describe', sortable: false },
        { text: '标签', value: 'tag', sortable: false },
        { text: '状态', value: 'status' },
        { text: '血缘关系数量', value: 'blood_count', align: 'center' },
        { text: '创建时间', value: 'create_time' },
        { text: '操作', value: 'actions', sortable: false }
      ],
      items: [],
      total: 0,
      pageInfo: {
        size: 10,
        current: 1
      },
      query: {},
      orders: [],
      itemData: {},
      itemDataAudit: {} // 审核记录信息
    }
  },
  computed: {
    title () {
      return this.itemData.id ? '编辑元数据' : '新增元数据'
    }
  },
  created () {
    this.init()
  },
  methods: {
    async init () {
      this.loading = true
      try {
        const { data } = await api.getMetaDataList({ ...this.pageInfo, ...this.query })
        this.total = data.total
        this.items = data.records
      } catch (error) {
        this.$snackbar.error(error)
      } finally {
        this.loading = false
      }
    },
    handleAdd () {
      this.itemData = {}
      this.show = true
    },
    async handleEdit ({ id }) {
      try {
        const { data } = await api.getMetadataDetails({ id })
        if (!data.length) {
          this.$snackbar.error('找不到元数据信息')
          return
        }
        this.itemData = {
          id,
          ...data.pop()
        }
        this.show = true
      } catch (error) {
        this.$snackbar.error(error)
      }
    },
    handleDelete (id) {
      this.$confirm('提示', '是否确定删除该项元数据').then(async () => {
        try {
          await api.deleteMetadata({ id })
          this.$snackbar.success('删除成功')
          this.init()
        } catch (error) {
          this.$snackbar.error(error)
        }
      })
    },
    async handleChangeStatus (item) {
      this.loading = true
      try {
        const { status, ...obj } = item
        await api.metadataUpdate({
          ...obj,
          status: 1 ^ status
        })
        this.$snackbar.success('操作成功')
        this.init()
      } catch (error) {
        this.loading = false
        this.$snackbar.error(error)
      }
    },
    // 创建/编辑元数据
    async handleSubmit () {
      const obj = this.$refs.form.getValue()
      if (!obj) {
        return
      }
      const apiFn = obj.id ? api.metadataUpdate : api.metadataAdd
      try {
        this.submitLoading = true
        const { message } = await apiFn(obj)
        if (message.includes('重复') || message.includes('疑似重复')) {
          this.show = false
          this.$confirm('系统提示', '当前创建的元数据与已存在的元数据疑似重复，是否前往审核页面？').then(async () => {
            this.$router.push('/dataReview')
          })
          return
        }
        this.$snackbar.success('操作成功')
        this.show = false
        this.init()
      } catch (error) {
        this.$snackbar.error(error)
      } finally {
        this.submitLoading = false
      }
    },
    handleSort (val) {
      this.orders = val
      this.init()
    },
    handleSearch (obj) {
      Object.assign(this.query, obj)
      this.pageInfo.current = 1
      this.init()
    },
    pageHandleChange (index) {
      this.pageInfo.current = index
      this.init()
    },
    // 添加审核
    handleAddAudit (item) {
      this.itemDataAudit = item
      this.showAudit = true
    },
    handleAuditClose () {
      this.showAudit = false
      this.itemDataAudit = {}
    },
    async handleAuditSubmit () {
      const obj = this.$refs.formAudit.getValue()
      if (!obj) {
        return this.$snackbar.warning('请将信息填写完整后再提交')
      }
      if (!obj.meta2 || !Object.keys(obj.meta2).length) {
        return this.$snackbar.warning('请选择候选元数据')
      }
      if (obj.meta1.id === obj.meta2.id) {
        return this.$snackbar.warning('候选元数据不能与主元数据相同')
      }
      try {
        await api.createAuditRecord(obj)
        this.handleAuditClose()
        this.init()
        this.$confirm('提示', '审核记录创建成功，是否前往审核页面').then(async () => {
          this.$router.push('/dataReview')
        })
      } catch (error) {
        this.$snackbar.error(error)
      }
    }
  }
}
</script>

<style lang="scss" scoped>

</style>
