<template>
  <div>
    <MForm ref="form" :items="formItems" v-model="formValues">
      <template #tips>
        <v-alert color="primary accent-4" elevation="1" colored-border border="left">
          <span style="color: #777; font-size: 14px;">
            在需求描述框内点击鼠标右键，选择“插入业务域”，即可插入业务域。(提示：鼠标右键仅在需求描述框内有效，插入位置为光标所在位置)
          </span>
        </v-alert>
      </template>
    </MForm>
    <v-menu
      v-model="contextMenuVisible"
      attach
      :position-x="contextMenuX"
      :position-y="contextMenuY"
      absolute
      offset-y
      nudge-top="8"
    >
      <v-list dense>
        <v-list-item @click="handleInsertBusinessDomainClick">
          <v-list-item-title>插入业务域</v-list-item-title>
        </v-list-item>
      </v-list>
    </v-menu>
    <v-dialog v-model="insertDialogVisible" max-width="400" persistent>
      <v-card>
        <v-card-title>选择要插入的业务域</v-card-title>
        <v-card-text>
          <v-autocomplete
            v-model="insertDialogSelected"
            :items="businessDomain"
            item-text="name_zh"
            item-value="name_zh"
            label="请选择业务域"
            outlined
            dense
            hide-details
            clearable
            @change="handleInsertDialogSelect"
          />
        </v-card-text>
        <v-card-actions>
          <v-spacer />
          <v-btn text @click="insertDialogVisible = false">取消</v-btn>
          <v-btn color="primary" text @click="handleInsertDialogConfirm">插入</v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>
  </div>
</template>

<script>
import MForm from '@/components/MForm'
import { api } from '@/api/dataGovernance'
import { getDatasourceList } from '@/api/dataOrigin'

export default {
  name: 'CreateOrderDialog',
  components: {
    MForm
  },
  props: {
    itemData: {
      type: Object,
      default: () => {}
    }
  },
  data () {
    return {
      formValues: {
        title: '',
        description: '',
        data_source: '',
        created_by: this.$store.getters.userInfo?.username || '',
        extracted_domains: [],
        extracted_fields: [],
        extraction_purpose: ''
      },
      dataSourceItems: [],
      businessDomain: [],
      descriptionCursor: { start: 0, end: 0 },
      descriptionCursorTouched: false,
      contextMenuVisible: false,
      contextMenuX: 0,
      contextMenuY: 0,
      insertDialogVisible: false,
      insertDialogSelected: null
    }
  },
  computed: {
    formItems () {
      return [
        {
          type: 'text',
          key: 'title',
          label: '订单标题 *',
          placeholder: '请输入订单标题，例如：员工与部门关联数据',
          rules: [
            v => !!v || '请输入订单标题',
            v => (v && v.length <= 200) || '标题不能超过200个字符'
          ],
          maxlength: 200,
          counter: true,
          outlined: true,
          dense: true,
          hideDetails: 'auto'
        },
        {
          type: 'autocomplete',
          key: 'data_source',
          label: '请选择输出数据源',
          noAttach: true,
          itemText: 'name_zh',
          itemValue: 'id',
          items: this.dataSourceItems
        },
        {
          type: 'text',
          key: 'created_by',
          label: '创建人',
          outlined: true,
          dense: true
        },
        {
          type: 'textarea',
          key: 'description',
          label: '需求描述 *',
          placeholder: '请详细描述需要什么数据，包括： 1. 涉及的业务领域（如员工、部门、项目等） 2. 需要的具体字段 3. 数据用途',
          rules: [
            v => !!v || '请输入需求描述',
            v => (v && v.length >= 10) || '描述至少需要10个字符'
          ],
          maxlength: 2000,
          counter: true,
          outlined: true,
          rows: 8,
          hideDetails: 'auto',
          cursorRef: this.descriptionCursor,
          onCursorSync: () => { this.descriptionCursorTouched = true },
          onContextMenu: this.handleDescriptionContextMenu
        },
        {
          slotName: 'tips'
        }
      ]
    }
  },
  created () {
    this.init()
    this.getBusinessDomainList()
    if (this.itemData && this.itemData.id) {
      this.formValues = {
        title: this.itemData.title || '',
        description: this.itemData.description || '',
        data_source: this.itemData.data_source || '',
        extracted_domains: this.itemData.extracted_domains || [],
        extracted_fields: this.itemData.extracted_fields || [],
        extraction_purpose: this.itemData.extraction_purpose || ''
      }
    }
  },
  methods: {
    async init () {
      try {
        const { data } = await getDatasourceList({})
        this.dataSourceItems = data.data_source
      } catch (error) {
        this.$snackbar.error(error)
      }
    },
    // 获取业务域列表
    async getBusinessDomainList () {
      try {
        const { data } = await api.getBusinessDomainList2()
        if (!data || !data?.length) {
          this.businessDomain = []
          return
        }
        this.businessDomain = data
      } catch (error) {
        this.$snackbar.error(error)
      }
    },
    // 插入业务域
    handleDescriptionContextMenu (item, event) {
      if (!event) return
      const rect = this.$el.getBoundingClientRect()
      this.contextMenuX = event.clientX - rect.left
      this.contextMenuY = event.clientY - rect.top + 110
      this.contextMenuVisible = true
    },
    handleInsertBusinessDomainClick () {
      this.contextMenuVisible = false
      this.insertDialogSelected = null
      this.insertDialogVisible = true
    },
    handleInsertDialogSelect (val) {
      if (val != null && val !== '') {
        this.handleBusinessDomainInsert(val)
        this.insertDialogVisible = false
        this.insertDialogSelected = null
      }
    },
    handleInsertDialogConfirm () {
      if (this.insertDialogSelected != null && this.insertDialogSelected !== '') {
        this.handleBusinessDomainInsert(this.insertDialogSelected)
      }
      this.insertDialogVisible = false
      this.insertDialogSelected = null
    },
    handleBusinessDomainInsert (val) {
      const { start, end } = this.descriptionCursor
      const desc = this.formValues.description || ''
      const useAppend = !this.descriptionCursorTouched && desc.length > 0
      const insertStart = useAppend ? desc.length : start
      const insertEnd = useAppend ? desc.length : end
      this.formValues.description = desc.slice(0, insertStart) + val + desc.slice(insertEnd)
      this.descriptionCursor.start = this.descriptionCursor.end = insertStart + val.length
    },
    getValue () {
      if (!this.$refs.form.validate()) {
        return
      }
      const params = {
        title: this.formValues.title,
        description: this.formValues.description,
        created_by: this.formValues.created_by,
        data_source: this.formValues.data_source
      }
      return this.itemData.id ? this.formValues : params
    }
  }
}
</script>
