<template>
  <div class="panel-tab__content">
    <el-table :data="elementActionList" size="mini" border>
      <el-table-column label="更改表" width="150px" prop="eTableId" />
      <el-table-column label="影响的字段" min-width="100px" prop="eChangeField" />
      <el-table-column label="值" min-width="100px" prop="eValue" />
    </el-table>
    <div class="element-drawer__button">
      <el-button
        size="mini"
        type="primary"
        icon="el-icon-plus"
        @click="openListenerForm(null)"
      >添加执行动作</el-button>
    </div>

    <!-- 监听器 编辑/创建 部分 -->
    <el-drawer
      :visible.sync="listenerFormModelVisible"
      title="执行动作"
      :size="`${width}px`"
      append-to-body
    >
      <p class="listener-filed__title">
        <el-button size="mini" type="primary" @click="openListenerFieldForm(null)">添加数据</el-button>
      </p>
      <el-table
        :data="fieldsListOfListener"
        size="mini"
        border
        fit
        style="flex: none"
      >
        <el-table-column label="更改表" width="150px" type="eTableId">
          <template slot-scope="scope">
            <!-- <el-input v-model="scope.row.eTableId" /> -->
            <formNameSelect
              v-model="scope.row.eTableId"
              filterable
              :selected-ids="selectedIds"
              @change="tableSelectChange($event,scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column label="影响的字段" min-width="100px" prop="eChangeField">
          <template slot-scope="scope">
            <!-- <el-input v-model="scope.row.eChangeField" /> -->
            <FiledsSelect
              ref="filedSelect"
              v-model="scope.row.eChangeField"
              filterable
              clearable
              :options="filedOptions"
              @change="filedSelectChange($event,scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column label="值" min-width="100px" prop="eValue">
          <template slot-scope="scope">
            <DictSelect v-if="scope.row.dictType || scope.row.htmlType === 'radio'" v-model="scope.row.eValue" :dict-type="scope.row.dictType.toUpperCase()" />
            <CurrencySelect
              v-else-if="scope.row.htmlType === 'select'"
              v-model="scope.row.eValue"
              :dict-table="scope.row.dictTable"
              :dict-table-column-code="scope.row.dictTableColumnCode"
              :dict-table-column-name="scope.row.dictTableColumnName"
            />
            <el-date-picker
              v-else-if="scope.row.htmlType === 'datetime'"
              v-model="scope.row.eValue"
              style="width: 100%;"
              type="datetime"
              placeholder="选择日期时间"
            />
            <el-input v-else v-model="scope.row.eValue" />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="100px">
          <template slot-scope="{ row, $index }">
            <el-button
              size="mini"
              type="text"
              style="color: #ff4d4f"
              @click="removeListenerField(row, $index)"
            >移除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="element-drawer__button">
        <el-button size="mini" @click="handleCancel">取 消</el-button>
        <el-button size="mini" type="primary" @click="saveListenerConfig">保 存</el-button>
      </div>
    </el-drawer>
  </div>
</template>
<script>
import { isArray } from 'min-dash'
import { updateElementExtensions } from '../../utils'
import { listenerType, fieldType } from './utilSelf'
import formNameSelect from '@/views/bpm/form/formNameSelect.vue'
import FiledsSelect from '@/views/infra/codegen/components/FiledsSelect.vue'
import { getCodegenDetail } from '@/api/infra/codegen'
import CurrencySelect from '@/views/bpm/model/components/CurrencySelect.vue'
import { queryTaskPage } from '@/api/bpm/model'

export default {
  name: 'ElementAction',
  components: {
    formNameSelect,
    FiledsSelect,
    CurrencySelect
  },
  props: {
    // eslint-disable-next-line vue/require-default-prop
    id: String,
    // eslint-disable-next-line vue/require-default-prop
    type: String
  },
  inject: {
    prefix: 'prefix',
    width: 'width'
  },
  data() {
    return {
      elementActionList: [], // 监听器列表
      listenerFormModelVisible: false, // 监听器 编辑 侧边栏显示状态
      fieldsListOfListener: [],
      editingListenerIndex: -1, // 监听器所在下标，-1 为新增
      editingListenerFieldIndex: -1, // 字段所在下标，-1 为新增
      listenerTypeObject: listenerType,
      fieldTypeObject: fieldType,
      selectedIds: [],
      filedOptions: [],
      saveData: [],
      allTaskList: []
    }
  },
  watch: {
    id: {
      immediate: true,
      handler(val) {
        val && val.length && this.$nextTick(async() => {
          await this.handleTaskPage()
          this.resetListenersList()
        })
      }
    }
  },
  methods: {
    async handleTaskPage() {
      const params = {
        pageNo: 1,
        pageSize: 1000
      }
      // await queryTaskPage(params).then(res => {
      //   this.allTaskList = res.data.list
      //   console.log('查数据')
      // })
      // const res = await queryTaskPage(params)
      // this.allTaskList = res.data.list
    },
    resetListenersList() {
      this.bpmnElement = window.bpmnInstances.bpmnElement
      this.otherExtensionList = []
      // this.bpmnElementListeners =
      // this.bpmnElement.businessObject?.documentation[0]?.filter(ex => ex.$type === `${this.prefix}:ExecutionAction`) ?? []
      if (this.bpmnElement.businessObject.documentation) {
        const attachList = this.bpmnElement.businessObject?.documentation[0]?.$attrs.allExtensions
        if (isArray(attachList)) {
          const filterList = attachList.filter(item => item.activityId === this.id)
          const dealList = filterList.reduce((result, item) => {
            const { activityId, values } = item
            const uniqueValues = values.map(value => {
              const { value: objValue } = value
              const { eTableId, eChangeField, eValue } = objValue
              // const uniqueIdentifier = `${id}-${eTableId}-${eChangeField}-${eValue}`
              return {
                activityId,
                eTableId,
                eChangeField,
                eValue
              }
            })
            return [...result, ...uniqueValues.filter(obj => !result.some(r => r.id === obj.id))]
          }, [])
          this.elementActionList = dealList
        } else {
          const filterList = this.allTaskList.filter(item => item.activityId === this.id)
          this.elementActionList = filterList || []
        }
      } else {
        const filterList = this.allTaskList.filter(item => item.activityId === this.id)
        this.elementActionList = filterList || []
      }

      // const extensionValues = this.bpmnElement.businessObject?.extensionElements?.values
      // // // 从扩展属性中找到对应类型的扩展元素
      // const yourExtension = extensionValues?.filter(ext => ext.$type === `${this.prefix}:YourExtensionType`) || []

      // const dealList = yourExtension.reduce((acc, item) => {
      //   const { id, values } = item
      //   values.forEach(value => {
      //     const { value: objValue } = value
      //     const { eTableId, eChangeField, eValue } = objValue
      //     const uniqueIdentifier = `${id}-${eTableId}-${eChangeField}-${eValue}`
      //     acc.add(uniqueIdentifier) // 使用 Set 保证唯一性
      //   })
      //   return acc
      // }, new Set())

      // const uniqueItemsArray = Array.from(dealList).map(item => {
      //   const [id, eTableId, eChangeField, eValue] = item.split('-')
      //   return { id, eTableId, eChangeField, eValue }
      // })
      // console.log(this.bpmnElement.businessObject, '查询的')
      // // 转换为数组形式
      // this.elementActionList = uniqueItemsArray
    },
    // 打开 监听器详情 侧边栏
    openListenerForm(listener, index) {
      if (listener) {
        this.editingListenerIndex = index
      } else {
        this.editingListenerIndex = -1 // 标记为新增
      }
      // console.log(listener, index)
      // if (listener && listener.fields) {
      //   this.fieldsListOfListener = listener.fields.map(field => ({ ...field, fieldType: field.string ? 'string' : 'expression' }))
      // } else {
      //   this.fieldsListOfListener = []
      // }
      this.fieldsListOfListener = this.elementActionList

      // 打开侧边栏并清楚验证状态
      this.listenerFormModelVisible = true
    },
    // 打开监听器字段编辑弹窗
    openListenerFieldForm(field, index) {
      this.fieldsListOfListener.push({
        eTableId: '',
        eChangeField: '',
        eValue: ''
      })
    },
    // 移除监听器字段
    removeListenerField(field, index) {
      this.$confirm('确认移除该字段吗？', '提示', {
        confirmButtonText: '确 认',
        cancelButtonText: '取 消'
      })
        .then(() => {
          this.fieldsListOfListener.splice(index, 1)
        })
        .catch(() => console.info('操作取消'))
    },
    // 移除监听器
    removeListener(listener, index) {
      this.$confirm('确认移除该监听器吗？', '提示', {
        confirmButtonText: '确 认',
        cancelButtonText: '取 消'
      })
        .then(() => {
          this.bpmnElementListeners.splice(index, 1)
          this.elementActionList.splice(index, 1)
          updateElementExtensions(this.bpmnElement, this.otherExtensionList.concat(this.bpmnElementListeners))
        })
        .catch(() => console.info('操作取消'))
    },
    // handleMergById(arr, newItem) {
    //   const index = arr.findIndex(item => item.$attrs.allExtensions[0].id === newItem.$attrs.allExtensions[0].id)
    //   console.log(index)
    //   if (index > -1) {
    //     const existingItem = arr[index].$attrs.allExtensions[0]
    //     newItem.$attrs.allExtensions[0].values.forEach(value => {
    //     //   // const isSame = existingItem.values.some(exitVal =>
    //     //   //   exitVal.eTableId === value.eTableId &&
    //     //   //  exitVal.eChangeField === value.eChangeField &&
    //     //   //   exitVal.eValue === value.eValue)
    //       const isSame = existingItem.values.find(exitVal => exitVal.value.eTableId !== value.value.eTableId &&
    //       exitVal.value.eChangeField !== value.value.eChangeField && exitVal.value.eValue !== value.value.eValue
    //       )
    //       console.log(isSame)
    //     //   if (!isSame) {
    //     //     existingItem.values.push(value)
    //     //     console.log(existingItem.values, '存入')
    //     //   }
    //     // existingItem.values.some(exitVal =>
    //     //   exitVal.eTableId === value.eTableId &&
    //     //  exitVal.eValue === value.eChangeField &&
    //     //   exitVal.eValue === value.eValue)
    //     // if (!existingItem.values.some(existingValue => this.compareValues(existingValue, value))) {
    //     //   existingItem.values.push(value)
    //     // }
    //     })
    //   } else {
    //     arr.push(newItem)
    //   }
    // },
    // 保存监听器配置
    saveListenerConfig() {
      const findItem = this.fieldsListOfListener.find(finds => !finds.eTableId && !finds.eChangeField && !finds.eValue)
      console.log(findItem)
      // 利用 Set 来确保唯一值
      const uniqueData = new Set(isArray(this.elementActionList) ? this.elementActionList.map(item => JSON.stringify(item)) : [])
      const newData = this.fieldsListOfListener.filter(item => !uniqueData.has(JSON.stringify(item)))

      newData.forEach(item => {
        uniqueData.add(JSON.stringify(item)) // 将新数据添加到 Set 中
        this.elementActionList.push(item) // 将新数据添加到 this.elementActionList 中
      })
      const newExtension = {
        activityId: this.id,
        $type: `${this.prefix}:YourExtensionType`, // 你的扩展元素类型
        // 假设 this.elementActionList 是一个对象数组
        // 可以根据你的数据结构对这里的 value 进行适当的修改
        values: this.elementActionList.map(item => ({ value: item }))
      }
      const allExtends = []
      allExtends.push(newExtension)
      // if (this.bpmnElement) {
      const documentation = window.bpmnInstances.bpmnFactory.create('bpmn:Documentation', { allExtensions: allExtends })

      window.bpmnInstances.modeling.updateProperties(this.bpmnElement, {
        documentation: [documentation]
      })
      // }
      this.saveData.push(documentation)
      console.log(this.saveData, this.allTaskList)
      // this.handleMergById(this.saveData, documentation)
      this.$emit('elementAction', this.saveData, this.allTaskList)

      // 创建新的扩展元素，将 this.elementActionList 存储其中
      // const newExtension = {
      //   id: this.id,
      //   $type: `${this.prefix}:YourExtensionType`, // 你的扩展元素类型
      //   // 假设 this.elementActionList 是一个对象数组
      //   // 可以根据你的数据结构对这里的 value 进行适当的修改
      //   values: this.elementActionList.map(item => ({ value: item }))
      // }

      // // 将新扩展元素添加到扩展列表中
      // // allExtensions.push(newExtension)
      // allExtensions = [...allExtensions, newExtension]
      // allExtensions.forEach(item => {
      //   updateElementExtensions(this.bpmnElement, item)
      // })

      // // // 4. 隐藏侧边栏
      this.listenerFormModelVisible = false
    },
    getFiledList(tableId) {
      getCodegenDetail(tableId).then(res => {
        this.filedOptions = res.data.columns
      })
    },
    tableSelectChange(v) {
      const { id } = v
      if (v) {
        this.getFiledList(id)
      }
      this.selectedIds = this.fieldsListOfListener.map(item => {
        const { eTableId } = item
        return eTableId
      })
    },
    filedSelectChange(v, row) {
      row.htmlType = v.htmlType
      row.dictType = v.dictType
      row.dictTable = v.dictTable
      row.dictTableColumnCode = v.dictTableColumnCode
      row.dictTableColumnName = v.dictTableColumnName
    },
    // 取消
    handleCancel() {
      this.listenerFormModelVisible = false
      this.fieldsListOfListener = []
    }
  }
}
</script>
