<template>
  <div class="d-flex fullscreen" v-loading="loading">
    <v-card class="width-auto fullHeight">
      <v-banner single-line>
        <div class="py-2 title">流程定义</div>
      </v-banner>
      <div class="pa-3 overflow-y-auto" style="height: calc(100% - 65px);">
        <div class="mb-3">
          <!-- <v-row>
            <v-col cols="12">
              <v-autocomplete
                v-model="changeObj.source_table"
                :items="businessDomain"
                chips
                dense
                small-chips
                outlined
                label="数据输入"
                placeholder="请选择数据输入"
                item-text="name_zh"
                item-value="id"
                multiple
              >
                <template v-slot:item="data">
                  <v-list-item-content>
                    <v-list-item-title>{{ data.item.name_zh }}</v-list-item-title>
                    <v-list-item-subtitle>
                      <v-chip v-for="tag in data.item.tag" :key="tag.id" small class="mr-2" color="success">{{ tag.name_zh }}</v-chip>
                    </v-list-item-subtitle>
                  </v-list-item-content>
                </template>
              </v-autocomplete>
            </v-col>
            <v-col cols="12">
              <v-autocomplete
                v-model="changeObj.target_table"
                label="数据输出"
                placeholder="请选择数据输出"
                :items="businessDomain"
                item-text="label"
                item-value="id"
                outlined
                multiple
                clearable
                dense
                hide-details
                deletable-chips
                chips
                small-chips
              >
              </v-autocomplete>
            </v-col>
          </v-row> -->
          <div v-for="value in ['source_table', 'target_table']" :key="value">
            <div style="color: rgba(0, 0, 0, 0.6); padding: 5px; font-size: 14px;">
              请选择{{ value === 'source_table' ? '数据输入' : '数据输出' }}
            </div>
            <div class="mb-6" style="border: 1px dashed #666; padding: 10px; border-radius: 5px;">
              <v-list dense flat v-if="businessDomain.length">
                <v-list-item-group v-model="changeObj[value]" multiple active-class="">
                  <v-list-item v-for="item in businessDomain" :key="item.id" :value="item.id" three-line>
                    <template v-slot:default="{ active }">
                      <v-list-item-action>
                        <v-checkbox :input-value="active"></v-checkbox>
                      </v-list-item-action>
                      <v-list-item-content>
                        <v-list-item-title>
                          <span>{{ item.name_zh }}</span>
                        </v-list-item-title>
                        <v-list-item-subtitle>
                          <v-chip v-for="tag in item.tag" :key="tag.id" small class="mr-2">{{ tag.name_zh }}</v-chip>
                        </v-list-item-subtitle>
                      </v-list-item-content>
                    </template>
                  </v-list-item>
                </v-list-item-group>
              </v-list>
              <div v-else class="text-center" style="color: #666; padding: 10px;">暂无数据</div>
            </div>
          </div>
        </div>
        <div>
          <v-textarea
            v-model="changeObj.rule"
            outlined
            hide-details
            label="请输入数据规则"
            :rows="10"
            dense
          ></v-textarea>
        </div>
        <div v-if="Object.keys(itemData).length" class="d-flex align-end justify-end mt-3">
          <v-btn color="primary" @click="handleViewCode">查看代码</v-btn>
        </div>
      </div>
    </v-card>
    <v-card style="width: 500px;" class="ml-3 fullHeight d-flex flex-column">
      <v-banner single-line>
        <div class="py-2 title">基础信息</div>
        <template #actions>
          <v-btn
            text
            class="ml-3"
            color="primary"
            @click="handleSubmit"
          >
            <v-icon left>mdi-send-variant</v-icon>
            确认提交
          </v-btn>
        </template>
      </v-banner>
      <div class="pt-3 height-auto overflow-y-auto">
        <EditBase ref="editBaseRefs"></EditBase>
      </div>
    </v-card>
    <v-navigation-drawer
      v-model="drawer"
      fixed
      temporary
      right
      width="800"
    >
      <div class="d-flex flex-column" style="height: 100%;">
        <v-banner single-line>
          <div class="py-2 title">执行代码查看</div>
        </v-banner>
        <div class="pa-3 flex-grow-1 overflow-y-auto">
          <div class="code-preview" v-html="highlightedCode"></div>
        </div>
      </div>
    </v-navigation-drawer>
  </div>
</template>

<script>
import EditBase from './editBase.vue'
import { api } from '@/api/dataGovernance'
import hljs from 'highlight.js'
import 'highlight.js/styles/monokai.css'

export default {
  name: 'editPage',
  components: {
    EditBase
  },
  props: {
    itemData: {
      type: Object,
      default: () => ({})
    }
  },
  data () {
    return {
      drawer: false,
      loading: false,
      scriptContent: '', // 执行代码
      businessDomain: [], // 业务域列表
      changeObj: {
        // code: null,
        rule: null,
        source_table: [],
        target_table: []
      }
    }
  },
  computed: {
    highlightedCode () {
      if (!this.scriptContent) {
        return ''
      }
      try {
        // highlight.js 高亮代码，尝试自动检测语言
        const result = hljs.highlightAuto(this.scriptContent)
        return `<pre><code class="hljs ${result.language || ''}">${result.value}</code></pre>`
      } catch (error) {
        console.error('代码高亮错误:', error)
        // 如果高亮失败，返回转义后的纯文本
        return `<pre><code>${this.escapeHtml(this.scriptContent)}</code></pre>`
      }
    }
  },
  async created () {
    this.loading = true
    await this.getList()
    if (Object.keys(this.itemData).length) {
      await this.getDetails()
    }
    this.loading = false
  },
  methods: {
    // 获取业务域列表
    async getList () {
      try {
        const { data } = await api.getBusinessDomainList2()
        if (!data || !data?.length) {
          this.businessDomain = []
          return
        }
        this.businessDomain = data.map(e => {
          return {
            ...e,
            label: `${e.tag}：${e.name_zh}`
          }
        })
      } catch (error) {
        this.$snackbar.error(error)
      }
    },
    // 详情
    async getDetails () {
      try {
        const { data } = await api.getDataFlowDetails(this.itemData.id)
        this.$nextTick(() => {
          this.$refs.editBaseRefs.setValues(data)
        })
        this.changeObj = data.script_requirement || {}
      } catch (error) {
        this.$snackbar.error(error)
      }
    },
    // 查看执行代码
    async handleViewCode () {
      if (!this.itemData || !this.itemData.id) {
        this.$snackbar.error('缺少数据流ID')
        return
      }

      this.scriptContent = ''
      this.loading = true
      try {
        const { data } = await api.getDataFlowScriptContent(this.itemData.id)
        if (!data?.script_content) {
          this.$snackbar.warning('脚本内容为空')
          return
        }
        this.scriptContent = data?.script_content || ''
        this.drawer = true
      } catch (error) {
        this.$snackbar.error(error.message || '获取脚本失败')
      } finally {
        this.loading = false
      }
    },
    async handleSubmit () {
      const params = this.$refs.editBaseRefs.getValue()
      if (!params) {
        return
      }
      const query = {
        ...params,
        script_requirement: this.changeObj
      }
      const isEdit = Object.keys(this.itemData).length > 0
      try {
        if (isEdit) {
          await api.updateDataFlow(this.itemData.id, query)
        } else {
          await api.addDataFlow(query)
        }
        this.$snackbar.success(isEdit ? '更新成功' : '新增成功')
        this.$emit('success')
      } catch (error) {
        this.$snackbar.error(error)
      }
    },
    escapeHtml (text) {
      const div = document.createElement('div')
      div.textContent = text
      return div.innerHTML
    }
  }
}
</script>

<style lang="scss" scoped>
.title {
  color: #1976D2;
  font-weight: 600;
}
.fullscreen {
  height: 100%;
  width: 100%;
}
.fullHeight {
  height: 100%;
}
.width-auto {
  width: 0;
  flex: 1;
}
.height-auto {
  height: 0;
  flex: 1;
}
::v-deep ul {
  padding-left: 0;
}
.code-preview {
  width: 100%;
  height: 100%;
  overflow: auto;
  padding: 16px;
  font-family: 'Courier New', Courier, monospace;
  font-size: 14px;
  line-height: 1.5;

  ::v-deep pre {
    margin: 0;
    padding: 0;
    background: transparent;
    border: none;
    font-family: inherit;
    font-size: inherit;
    line-height: inherit;
    height: 100%;
  }

  ::v-deep code {
    display: block;
    width: 100%;
    padding: 0;
    margin: 0;
    background: transparent;
    border: none;
    font-family: inherit;
    font-size: inherit;
    line-height: inherit;
    white-space: pre;
    overflow-wrap: normal;
    overflow-x: auto;
  }
}
</style>
