<template>
  <div class="panel-tab__content">
    <a-form layout="vertical" @submit.prevent size="small">
      <a-form-item label="参数说明">
        <a-button size="small" type="primary" @click="dialogVisible = true">查看</a-button>
      </a-form-item>
      <a-form-item label="回路特性">
        <a-select v-model:value="loopCharacteristics" @change="changeLoopCharacteristicsType">
          <!--bpmn:MultiInstanceLoopCharacteristics-->
          <a-select-option value="ParallelMultiInstance">并行多重事件</a-select-option>
          <a-select-option value="SequentialMultiInstance">时序多重事件</a-select-option>
          <!--bpmn:StandardLoopCharacteristics-->
          <a-select-option value="StandardLoop">循环事件</a-select-option>
          <a-select-option value="Null">无</a-select-option>
        </a-select>
      </a-form-item>
      <template v-if="loopCharacteristics === 'ParallelMultiInstance' || loopCharacteristics === 'SequentialMultiInstance'">
        <a-form-item label="循环基数" key="loopCardinality">
          <a-input v-model:value="loopInstanceForm.loopCardinality" allow-clear @change="updateLoopCardinality" />
        </a-form-item>
        <a-form-item label="集合" key="collection">
          <a-input v-model:value="loopInstanceForm.collection" allow-clear @change="updateLoopBase" />
        </a-form-item>
        <a-form-item label="元素变量" key="elementVariable">
          <a-input v-model:value="loopInstanceForm.elementVariable" allow-clear @change="updateLoopBase" />
        </a-form-item>
        <a-form-item label="完成条件" key="completionCondition">
          <a-input v-model:value="loopInstanceForm.completionCondition" allow-clear @change="updateLoopCondition" />
        </a-form-item>
        <a-form-item label="异步状态" key="async">
          <a-checkbox v-model:checked="loopInstanceForm.asyncBefore" @change="() => updateLoopAsync('asyncBefore')">
            异步前
          </a-checkbox>
          <a-checkbox v-model:checked="loopInstanceForm.asyncAfter" @change="() => updateLoopAsync('asyncAfter')">
            异步后
          </a-checkbox>
          <a-checkbox
            v-model:checked="loopInstanceForm.exclusive"
            v-if="loopInstanceForm.asyncAfter || loopInstanceForm.asyncBefore"
            @change="() => updateLoopAsync('exclusive')"
          >
            排除
          </a-checkbox>
        </a-form-item>
        <a-form-item 
          label="重试周期" 
          key="timeCycle" 
          v-if="loopInstanceForm.asyncAfter || loopInstanceForm.asyncBefore"
        >
          <a-input v-model:value="loopInstanceForm.timeCycle" allow-clear @change="updateLoopTimeCycle" />
        </a-form-item>
      </template>
    </a-form>

    <!-- 参数说明 -->
    <a-modal
      v-model:open="dialogVisible"
      title="多实例参数"
      width="680px"
      :footer="null"
      @cancel="dialogVisible = false"
    >
      <a-descriptions :column="1" bordered>
        <a-descriptions-item label="使用说明">按照BPMN2.0规范的要求，用于为每个实例创建执行的父执行，会提供下列变量:</a-descriptions-item>
        <a-descriptions-item label="collection(集合变量)">传入List参数, 一般为用户ID集合</a-descriptions-item>
        <a-descriptions-item label="elementVariable(元素变量)">List中单个参数的名称</a-descriptions-item>
        <a-descriptions-item label="loopCardinality(基数)">List循环次数</a-descriptions-item>
        <a-descriptions-item label="isSequential(串并行)">Parallel: 并行多实例，Sequential: 串行多实例</a-descriptions-item>
        <a-descriptions-item label="completionCondition(完成条件)">任务出口条件</a-descriptions-item>
        <a-descriptions-item label="nrOfInstances(实例总数)">实例总数</a-descriptions-item>
        <a-descriptions-item label="nrOfActiveInstances(未完成数)">当前活动的（即未完成的），实例数量。对于顺序多实例，这个值总为1</a-descriptions-item>
        <a-descriptions-item label="nrOfCompletedInstances(已完成数)">已完成的实例数量</a-descriptions-item>
        <a-descriptions-item label="loopCounter">给定实例在for-each循环中的index</a-descriptions-item>
      </a-descriptions>
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
import { ref, watch, reactive } from 'vue'
import { StrUtil } from '../common/StrUtil'

interface LoopInstanceForm {
  completionCondition?: string
  loopCardinality?: string
  collection?: string
  elementVariable?: string
  asyncAfter?: boolean
  asyncBefore?: boolean
  exclusive?: boolean
  timeCycle?: string
  extensionElements?: any[]
  [key: string]: any
}

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

// 响应式数据
const dialogVisible = ref(false)
const loopCharacteristics = ref("")
const loopInstanceForm = reactive<LoopInstanceForm>({})
const multiLoopInstance = ref<any>(null)

const defaultLoopInstanceForm: LoopInstanceForm = {
  completionCondition: "",
  loopCardinality: "",
  extensionElements: [],
  asyncAfter: false,
  asyncBefore: false,
  exclusive: false
}

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

// 监听 id 变化
watch(() => props.id, (newVal) => {
  if (StrUtil.isNotBlank(newVal)) {
    getElementLoop(modelerStore.element.businessObject)
  }
}, { immediate: true })

// 获取元素循环配置
const getElementLoop = (businessObject: any) => {
  if (!businessObject.loopCharacteristics) {
    loopCharacteristics.value = "Null"
    Object.assign(loopInstanceForm, {})
    return
  }
  
  if (businessObject.loopCharacteristics.$type === "bpmn:StandardLoopCharacteristics") {
    loopCharacteristics.value = "StandardLoop"
    Object.assign(loopInstanceForm, {})
    return
  }
  
  if (businessObject.loopCharacteristics.isSequential) {
    loopCharacteristics.value = "SequentialMultiInstance"
  } else {
    loopCharacteristics.value = "ParallelMultiInstance"
  }
  
  // 合并配置
  Object.assign(loopInstanceForm, {
    ...defaultLoopInstanceForm,
    ...businessObject.loopCharacteristics,
    completionCondition: businessObject.loopCharacteristics?.completionCondition?.body ?? "",
    loopCardinality: businessObject.loopCharacteristics?.loopCardinality?.body ?? ""
  })
  
  // 保留当前元素 businessObject 上的 loopCharacteristics 实例
  multiLoopInstance.value = businessObject.loopCharacteristics
  
  // 更新表单
  if (
    businessObject.loopCharacteristics.extensionElements &&
    businessObject.loopCharacteristics.extensionElements.values &&
    businessObject.loopCharacteristics.extensionElements.values.length
  ) {
    loopInstanceForm.timeCycle = businessObject.loopCharacteristics.extensionElements.values[0].body
  }
}

// 改变循环特性类型
const changeLoopCharacteristicsType = (type: string) => {
  // 切换类型取消原表单配置
  Object.assign(loopInstanceForm, defaultLoopInstanceForm)
  
  // 取消多实例配置
  if (type === "Null") {
    modelerStore.modeling.updateProperties(modelerStore.element, { loopCharacteristics: null })
    return
  }
  
  // 配置循环
  if (type === "StandardLoop") {
    const loopCharacteristicsObject = modelerStore.moddle.create("bpmn:StandardLoopCharacteristics")
    modelerStore.modeling.updateProperties(modelerStore.element, {
      loopCharacteristics: loopCharacteristicsObject
    })
    multiLoopInstance.value = null
    return
  }
  
  // 时序
  if (type === "SequentialMultiInstance") {
    multiLoopInstance.value = modelerStore.moddle.create("bpmn:MultiInstanceLoopCharacteristics", {
      isSequential: true
    })
  } else {
    multiLoopInstance.value = modelerStore.moddle.create("bpmn:MultiInstanceLoopCharacteristics")
  }
  
  modelerStore.modeling.updateProperties(modelerStore.element, {
    loopCharacteristics: multiLoopInstance.value
  })
}

// 循环基数
const updateLoopCardinality = (cardinality: string) => {
  let loopCardinality = null
  if (cardinality && cardinality.length) {
    loopCardinality = modelerStore.moddle.create("bpmn:FormalExpression", { body: cardinality })
  }
  modelerStore.modeling.updateModdleProperties(modelerStore.element, multiLoopInstance.value, {
    loopCardinality
  })
}

// 完成条件
const updateLoopCondition = (condition: string) => {
  let completionCondition = null
  if (condition && condition.length) {
    completionCondition = modelerStore.moddle.create("bpmn:FormalExpression", { body: condition })
  }
  modelerStore.modeling.updateModdleProperties(modelerStore.element, multiLoopInstance.value, {
    completionCondition
  })
}

// 重试周期
const updateLoopTimeCycle = (timeCycle: string) => {
  const extensionElements = modelerStore.moddle.create("bpmn:ExtensionElements", {
    values: [
      modelerStore.moddle.create(`flowable:FailedJobRetryTimeCycle`, {
        body: timeCycle
      })
    ]
  })
  modelerStore.modeling.updateModdleProperties(modelerStore.element, multiLoopInstance.value, {
    extensionElements
  })
}

// 直接更新的基础信息
const updateLoopBase = () => {
  modelerStore.modeling.updateModdleProperties(modelerStore.element, multiLoopInstance.value, {
    collection: loopInstanceForm.collection || null,
    elementVariable: loopInstanceForm.elementVariable || null
  })
}

// 各异步状态
const updateLoopAsync = (key: string) => {
  const { asyncBefore, asyncAfter } = loopInstanceForm
  let asyncAttr: Record<string, any> = {}
  
  if (!asyncBefore && !asyncAfter) {
    loopInstanceForm.exclusive = false
    asyncAttr = { asyncBefore: false, asyncAfter: false, exclusive: false, extensionElements: null }
  } else {
    asyncAttr[key] = loopInstanceForm[key]
  }
  
  modelerStore.modeling.updateModdleProperties(modelerStore.element, multiLoopInstance.value, asyncAttr)
}
</script>

<style lang="scss">
.panel-tab__content {
  .ant-checkbox-wrapper {
    margin-right: 8px;
  }
}
</style>