<script setup lang="ts">
import {
  Field as VanField,
  Picker as VanPicker,
  Popup as VanPopup,
  Search as VanSearch,
} from 'vant'
import { computed, inject, onMounted, ref } from 'vue'

const workflowHandleWrap: any = inject('workflowHandleWrap')

const showPicker = ref(false)

const showMultiplePicker = ref(false)

const branchChargePersons = ref({})

const isInit = ref(false)

// 用于 filterOption 的本地输入缓存（vant 不自带 filter）
const filterKeyword = ref('')

const customFieldName = {
  text: 'label',
  value: 'value',
}

const selectedNode = ref(undefined)

const selectedOptions = computed(() => {
  if (!selectedNode.value) {
    return []
  }
  return filterOptions(selectedNode.value.chargePersonOptions)
})

onMounted(() => {
  isInit.value = false
  if (workflowHandleWrap.branchNodes.value) {
    // 初始化初始值
    for (const node of workflowHandleWrap.branchNodes.value) {
      branchChargePersons.value[node.stepId] = {
        handler: '',
        handlerId: '',
      }
    }
  }
  isInit.value = true
})

function setBranchPersonValue(stepId, value, options, selectedOptions) {
  if (!stepId)
    return
  if (!workflowHandleWrap.branchChargePersons.value) {
    workflowHandleWrap.branchChargePersons.value = {}
  }
  if (!workflowHandleWrap.branchChargePersons.value[stepId]) {
    workflowHandleWrap.branchChargePersons.value[stepId] = {}
  }
  if (workflowHandleWrap.branchChargePersons.value[stepId]) {
    branchChargePersons.value[stepId] = {
      handler: options.find(item => item.value === value)?.label,
      handlerId: value,
    }
    Object.assign(workflowHandleWrap.branchChargePersons.value[stepId], branchChargePersons.value[stepId])
  }
  workflowHandleWrap.checkedNextStepPerson.value = selectedOptions[0].value
  workflowHandleWrap.checkedNextStepPersonName.value = selectedOptions[0].label
}

function getBranchSelectionLabel() {
  if (workflowHandleWrap.needMultipleBranchSelection.value) {
    return '分支处理人'
  }
  else if (workflowHandleWrap.calculatedTargetNode.value) {
    return `${workflowHandleWrap.getStepNameByStepId(workflowHandleWrap.calculatedTargetNode.value)}处理人`
  }
  else {
    return '处理人'
  }
}

// vant 没有原生 filter-option，因此需要本地筛选
function filterOptions(options) {
  if (!filterKeyword.value)
    return options
  return options.filter(option => option.label.toLowerCase().includes(filterKeyword.value.toLowerCase()))
}

// 搜索回调函数
function search(val: string) {
  filterKeyword.value = val || ''
}
</script>

<template>
  <div v-if="workflowHandleWrap.isNeedSelectPerson.value && isInit">
    <!-- 多分支选择 -->
    <template v-if="workflowHandleWrap.needMultipleBranchSelection.value && workflowHandleWrap.branchNodes.value.length > 0">
      <template v-for="node in workflowHandleWrap.branchNodes.value" :key="node.stepId">
        <VanField
          v-model="branchChargePersons[node.stepId].handler"
          :label="`${node.stepName}处理人`"
          is-link
          clickable
          required
          placeholder="请选择处理人"
          @click="selectedNode = node; showMultiplePicker = true;"
        />
      </template>
      <VanPopup v-model:show="showMultiplePicker" position="bottom">
        <!-- 搜索框 -->
        <VanSearch
          v-model="filterKeyword"
          placeholder="搜索"
          @clear="() => search('')"
          @update:model-value="search"
        />
        <VanPicker
          :columns="selectedOptions"
          :columns-field-names="customFieldName"
          value-key="label"
          @confirm="(val) => {
            setBranchPersonValue(selectedNode.stepId, val.selectedValues[0], selectedNode.chargePersonOptions, val.selectedOptions)
            showMultiplePicker = false;
          }"
          @cancel="showMultiplePicker = false;"
        />
      </VanPopup>
    </template>

    <!-- 单分支选择 -->
    <template v-else>
      <VanField
        v-model="workflowHandleWrap.checkedNextStepPersonName.value"
        :label="getBranchSelectionLabel()"
        label-width="auto"
        is-link
        clickable
        required
        placeholder="请选择处理人"
        @click="showPicker = true"
      />
      <VanPopup v-model:show="showPicker" position="bottom">
        <!-- 搜索框 -->
        <VanSearch
          v-model="filterKeyword"
          placeholder="搜索"
          @clear="() => search('')"
          @update:model-value="search"
        />
        <VanPicker
          :columns="filterOptions(workflowHandleWrap.nextStepPersonOptions.value)"
          :columns-field-names="customFieldName"
          @confirm="(val) => {
            setBranchPersonValue(workflowHandleWrap.calculatedTargetNode.value, val.selectedValues[0], workflowHandleWrap.nextStepPersonOptions.value, val.selectedOptions)
            showPicker = false;
          }"
          @cancel="showPicker = false;"
        />
      </VanPopup>
    </template>
  </div>
</template>

<style scoped>
/* 保持你的样式或根据 vant 移动端自行优化 */
</style>
