<template>
  <div class="panel-tab__content">
    <a-divider orientation="center">按钮设置</a-divider>
    <a-table
      :dataSource="elementButtonList"
      :columns="columns"
      size="small"
      :pagination="false"
      bordered
      :scroll="{ y: 240 }"
    >
      <template #bodyCell="{ column, record, index }">
        <template v-if="column.key === 'index'">
          {{ index + 1 }}
        </template>
        <template v-if="column.key === 'operation'">
          <a-button size="small" type="link" @click="openAttributesForm(record, index)">
            编辑
          </a-button>
          <a-divider type="vertical" />
          <a-button size="small" type="link" danger @click="removeAttributes(record, index)">
            移除
          </a-button>
        </template>
      </template>
    </a-table>
    <div class="element-drawer__button_save">
      <a-button size="small" type="primary" @click="openAttributesForm(null, -1)">
        <template #icon><plus-outlined /></template>
        添加按钮
      </a-button>
    </div>

    <a-modal
      v-model:open="buttonFormModelVisible"
      title="按钮配置"
      width="600px"
      :getContainer="false"
      :destroyOnClose="true"
      @cancel="handleCancel"
      @ok="saveAttribute"
    >
      <a-form
        :model="buttonForm"
        layout="vertical"
        size="small"
        ref="attributeFormRef"
      >
        <a-form-item label="属性名：" name="label">
          <a-input v-model:value="buttonForm.label" allow-clear />
        </a-form-item>
        <a-form-item label="属性值：" name="value">
          <a-input v-model:value="buttonForm.value" allow-clear />
        </a-form-item>
      </a-form>
      <template #footer>
        <a-button size="small" @click="buttonFormModelVisible = false">取 消</a-button>
        <a-button size="small" type="primary" @click="saveAttribute">确 定</a-button>
      </template>
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
import { ref, watch, onMounted, nextTick, reactive } from 'vue'
import { Modal, message } from 'ant-design-vue'
import { PlusOutlined } from '@ant-design/icons-vue'
import { StrUtil } from "../common/StrUtil"

interface ButtonItem {
  name: string
  value: string
  label?: string
}

interface ButtonForm {
  label?: string
  value?: string
}

const props = defineProps<{
  id: string
}>()

// 表格列定义
const columns = [
  {
    title: '序号',
    key: 'index',
    width: '50px'
  },
  {
    title: '属性名',
    dataIndex: 'name',
    key: 'name',
    ellipsis: true,
    width: '100px'
  },
  {
    title: '属性值',
    dataIndex: 'value',
    key: 'value',
    ellipsis: true,
    width: '100px'
  },
  {
    title: '操作',
    key: 'operation',
    width: '90px'
  }
]

// 响应式数据
const elementButtonList = ref<ButtonItem[]>([])
const otherExtensionList = ref<any[]>([])
const buttonForm = reactive<ButtonForm>({})
const editingPropertyIndex = ref(-1)
const buttonFormModelVisible = ref(false)
const attributeFormRef = ref()

// 假设这是从其他地方引入的 store
const modelerStore = {
  element: null as any,
  modeling: {
    updateModdleProperties: (element: any, property: any, values: any) => {},
    updateProperties: (element: any, properties: any) => {}
  },
  moddle: {
    create: (type: string, values: any) => ({})
  }
}

// 监听 id 变化
watch(() => props.id, (val) => {
  if (StrUtil.isNotBlank(val)) {
    resetAttributesList()
  }
}, { immediate: true })

// 初始化属性列表
const resetAttributesList = () => {
  const bpmnElement = modelerStore.element
  otherExtensionList.value = [] // 其他扩展配置
  
  const bpmnElementProperties = bpmnElement.businessObject?.extensionElements?.values?.filter((ex: any) => {
    if (ex.$type !== `flowable:Buttons`) {
      otherExtensionList.value.push(ex)
    }
    return ex.$type === `flowable:Buttons`
  }) ?? []

  // 保存所有的扩展属性字段
  const bpmnElementButtonList = bpmnElementProperties.reduce((pre: any[], current: any) => 
    pre.concat(current.values), [])
  
  // 复制显示
  elementButtonList.value = JSON.parse(JSON.stringify(bpmnElementButtonList ?? []))
}

// 打开属性表单
const openAttributesForm = (attr: ButtonItem | null, index: number) => {
  editingPropertyIndex.value = index
  if (index === -1) {
    buttonForm.label = ''
    buttonForm.value = ''
  } else {
    buttonForm.label = attr?.name || ''
    buttonForm.value = attr?.value || ''
  }
  buttonFormModelVisible.value = true
  nextTick(() => {
    if (attributeFormRef.value) {
      attributeFormRef.value.clearValidate()
    }
  })
}

// 移除属性
const removeAttributes = (attr: ButtonItem, index: number) => {
  Modal.confirm({
    title: '提示',
    content: '确认移除该属性吗？',
    okText: '确认',
    cancelText: '取消',
    onOk: () => {
      elementButtonList.value.splice(index, 1)
      // 这里需要根据实际业务逻辑更新 bpmnElementButtonList
      
      // 新建一个属性字段的保存列表
      const propertiesObject = modelerStore.moddle.create(`flowable:Buttons`, {
        values: elementButtonList.value
      })
      updateElementExtensions(propertiesObject)
      resetAttributesList()
      message.success('移除成功')
    },
    onCancel: () => {
      console.info('操作取消')
    }
  })
}

// 保存属性
const saveAttribute = () => {
  const { label, value } = buttonForm
  if (!label || !value) {
    message.warning('请填写完整信息')
    return
  }

  if (editingPropertyIndex.value !== -1) {
    // 编辑现有属性
    modelerStore.modeling.updateModdleProperties(
      modelerStore.element,
      elementButtonList.value[editingPropertyIndex.value],
      { name: label, value }
    )
  } else {
    // 新建属性字段
    const newPropertyObject = modelerStore.moddle.create(`flowable:Button`, { 
      name: label, 
      value 
    })
    
    // 新建一个属性字段的保存列表
    const propertiesObject = modelerStore.moddle.create(`flowable:Buttons`, {
      values: [...elementButtonList.value, newPropertyObject]
    })
    
    updateElementExtensions(propertiesObject)
  }
  
  buttonFormModelVisible.value = false
  resetAttributesList()
  message.success('保存成功')
}

// 更新元素扩展
const updateElementExtensions = (properties: any) => {
  const extensions = modelerStore.moddle.create("bpmn:ExtensionElements", {
    values: [...otherExtensionList.value, properties]
  })

  modelerStore.modeling.updateProperties(modelerStore.element, {
    extensionElements: extensions
  })
}

// 取消操作
const handleCancel = () => {
  buttonFormModelVisible.value = false
}
</script>

<style lang="scss">
.panel-tab__content {
  .element-drawer__button_save {
    margin-top: 10px;
    text-align: center;
  }
}
</style>