<script setup lang="ts">
// 组件依赖：API 调用工具与 Vant 组件
import { runLogic } from '@af-mobile-client-vue3/services/api/common'
import {
  showFailToast,
  showToast,
  Button as VanButton,
  Field as VanField,
  Icon as VanIcon,
  Loading as VanLoading,
  Picker as VanPicker,
  Popup as VanPopup,
} from 'vant'
import { computed, reactive, ref, watch } from 'vue'

// 工单信息接口定义
interface WorkOrderOption {
  text: string
  value?: string
  workflowId?: string
}

// 材料组接口定义
interface MaterialGroupItem {
  value: string
  label: string
}

// 表单数据接口定义
interface FormData {
  workOrderId: string
  workOrderCode: string
  groupId: string
  groupName: string
}

// 组件属性定义：控制弹窗显示、工单数据与服务名
const props = defineProps<{
  show: boolean
  workOrderData: WorkOrderOption[]
  serviceName?: string
}>()

// 组件事件定义：同步 show 状态与新增收费项
const emit = defineEmits<{
  (e: 'update:show', value: boolean): void
  (e: 'add', item: {
    id: number
    type: string
    item: string
    model: string
    unitPrice: number
    quantity: number
    total: string
    workOrderCode: string
    workOrderId: string
  }): void
}>()

// 计算属性：双向绑定弹窗显隐
const showModal = computed({
  get: () => props.show,
  set: value => emit('update:show', value),
})

// 计算属性：确定服务名称（优先使用外部传入）
const serviceAppName = computed(() => props.serviceName || import.meta.env.VITE_APP_SYSTEM_NAME)

// 全局变量：用于记录当前选中的工单详细信息
const selectedWorkOrder = ref<WorkOrderOption | null>(null)

// 表单状态：记录选择的工单与材料组
const formData = reactive<FormData>({
  workOrderId: '',
  workOrderCode: '',
  groupId: '',
  groupName: '',
})

// 控制选择器显示状态
const showWorkOrderSelector = ref(false)
const showGroupSelector = ref(false)

// 加载状态与提示文案
const loading = ref(false)
const materialGroups = ref<MaterialGroupItem[]>([])
const materials = ref<any[]>([])
const groupMessage = ref('')
const materialMessage = ref('')
const initializing = ref(false)

// 工单下拉选项（仅保留合法 workflowId/value）
const workOrderOptions = computed(() => {
  return (props.workOrderData || []).map(order => ({
    text: order.text || order.workflowId || order.value || '未命名工单',
    value: order.workflowId || order.value || '',
  })).filter(option => option.value)
})

// 材料组选项
const groupOptions = computed(() => materialGroups.value.map(group => ({
  text: group.label,
  value: group.value,
})))

// 顶部提示信息：优先展示材料组提示，其次材料提示
const headerMessage = computed(() => {
  if (groupMessage.value)
    return groupMessage.value
  if (materialMessage.value)
    return materialMessage.value
  return ''
})

// 提交按钮可用状态：需选择材料组并成功获取材料
const canSubmit = computed(() => Boolean(formData.groupId && materials.value.length > 0 && !loading.value))

// 关闭弹窗并重置数据
function closeModal() {
  showModal.value = false
  resetForm()
}

// 重置所有状态数据
function resetForm() {
  formData.workOrderId = ''
  formData.workOrderCode = ''
  formData.groupId = ''
  formData.groupName = ''
  materialGroups.value = []
  materials.value = []
  groupMessage.value = ''
  materialMessage.value = ''
  showWorkOrderSelector.value = false
  showGroupSelector.value = false
  selectedWorkOrder.value = null
}

// 根据 workflowId 定位工单
function getSelectedWorkOrder(workflowId: string) {
  return (props.workOrderData || []).find(order => (order.workflowId || order.value) === workflowId)
}

// 选择工单后更新表单并查询材料组
function onWorkOrderSelected({ selectedValues }: { selectedValues: string[] }) {
  const workflowId = selectedValues[0]
  const selected = getSelectedWorkOrder(workflowId) || null
  selectedWorkOrder.value = selected
  formData.workOrderId = workflowId
  formData.workOrderCode = selected?.text || '未命名工单'
  showWorkOrderSelector.value = false
  fetchMaterialGroups(workflowId, true)
}

// 选择材料组后更新表单并查询材料
function onGroupSelected({ selectedValues }: { selectedValues: string[] }) {
  const selectedGroupId = selectedValues[0]
  const selectedGroup = materialGroups.value.find(group => group.value === selectedGroupId)
  if (selectedGroup) {
    formData.groupId = selectedGroup.value
    formData.groupName = selectedGroup.label
  }
  showGroupSelector.value = false
  materialMessage.value = ''
  materials.value = []
  if (formData.groupId) {
    fetchMaterialsByGroup(formData.groupId)
  }
}

// 根据工单查询材料组，可选择自动选中第一个材料组
async function fetchMaterialGroups(workflowId: string, autoSelectFirstGroup = false) {
  if (!workflowId) {
    groupMessage.value = '请选择工单后再获取材料组'
    return
  }
  loading.value = true
  groupMessage.value = ''
  materialMessage.value = ''
  materialGroups.value = []
  materials.value = []
  formData.groupId = ''
  formData.groupName = ''

  try {
    const res = await runLogic('getMaterialGroup', {
      workflowId,
    }, serviceAppName.value)
    const groups = Array.isArray(res)
      ? res.map((item: any) => ({
          value: item.value || item.id || '',
          label: item.name || item.label || '未命名材料组',
        })).filter((group: MaterialGroupItem) => group.value)
      : []

    materialGroups.value = groups
    if (!groups.length) {
      groupMessage.value = '当前工单暂无可用材料组'
    }
    else if (autoSelectFirstGroup) {
      const [firstGroup] = groups
      formData.groupId = firstGroup.value
      formData.groupName = firstGroup.label
      await fetchMaterialsByGroup(firstGroup.value)
    }
  }
  catch (error) {
    console.error('获取材料组失败:', error)
    showFailToast('获取材料组失败')
    groupMessage.value = '获取材料组失败，请稍后重试'
  }
  finally {
    loading.value = false
  }
}

// 根据材料组查询材料清单
async function fetchMaterialsByGroup(groupId: string) {
  if (!groupId)
    return
  loading.value = true
  materialMessage.value = ''
  materials.value = []
  try {
    const res = await runLogic('getMaterialByGroup', {
      id: groupId,
    }, serviceAppName.value)

    if (Array.isArray(res) && res.length > 0) {
      materials.value = res
    }
    else {
      materialMessage.value = '该材料组暂无材料'
    }
  }
  catch (error) {
    console.error('获取材料列表失败:', error)
    showFailToast('获取材料列表失败')
    materialMessage.value = '获取材料失败，请稍后再试'
  }
  finally {
    loading.value = false
  }
}

// 点击添加按钮时校验并返回材料数据
async function handleSubmit() {
  if (!formData.workOrderId) {
    showToast('请选择工单')
    return
  }
  if (!formData.groupId) {
    showToast('请选择材料组')
    return
  }
  if (!materials.value.length) {
    showToast('该材料组暂无材料，无法添加')
    return
  }

  try {
    materials.value.forEach((material, index) => {
      const unitPrice = Number.parseFloat(material.price ?? '0') || 0
      const quantity = Number.parseFloat(material.count ?? '1') || 1
      const total = (unitPrice * quantity).toFixed(2)

      emit('add', {
        id: Date.now() + index,
        item: material.name || '未知材料',
        type: material.type || '未分类',
        model: material.model || '型号未知',
        unitPrice,
        quantity,
        total,
        workOrderId: formData.workOrderId,
        workOrderCode: formData.workOrderCode,
      })
    })
    showToast(`成功添加${materials.value.length}项材料`)
    closeModal()
  }
  catch (error) {
    console.error('提交材料失败:', error)
    showFailToast('添加材料失败')
  }
}

// 初始化默认选择：自动选择首个工单与材料组
async function initDefaultSelections() {
  if (formData.workOrderId || initializing.value)
    return
  if (!workOrderOptions.value.length)
    return
  initializing.value = true
  try {
    const firstOrderOption = workOrderOptions.value[0]
    const firstOrder = getSelectedWorkOrder(firstOrderOption.value) || null
    selectedWorkOrder.value = firstOrder
    formData.workOrderId = firstOrderOption.value
    formData.workOrderCode = firstOrderOption.text
    await fetchMaterialGroups(firstOrderOption.value, true)
  }
  finally {
    initializing.value = false
  }
}

// 监听弹窗显示状态，打开时尝试进行默认选择
watch(() => props.show, (visible) => {
  if (visible) {
    initDefaultSelections()
  }
  else {
    resetForm()
  }
})

// 监听工单数据变化，必要时重新初始化
watch(() => props.workOrderData, () => {
  if (showModal.value && !formData.workOrderId) {
    initDefaultSelections()
  }
}, { deep: true })
</script>

<template>
  <!-- 材料组选择弹窗容器 -->
  <VanPopup
    v-model:show="showModal"
    round
    position="center"
    :style="{ width: '90%', maxWidth: '420px' }"
    close-icon-position="top-right"
    class="other-charge-group-modal"
  >
    <!-- 主内容区域 -->
    <div class="other-charge-group-modal__container">
      <!-- 弹窗加载遮罩 -->
      <div v-if="loading" class="other-charge-group-modal__loading-mask">
        <VanLoading size="24px">
          加载中...
        </VanLoading>
      </div>
      <!-- 弹窗标题区域 -->
      <div class="other-charge-group-modal__header">
        <h3 class="other-charge-group-modal__title">
          选择材料组
        </h3>
        <VanIcon name="cross" @click="closeModal" />
      </div>
      <!-- 顶部提示信息 -->
      <p v-if="headerMessage" class="other-charge-group-modal__tip">
        {{ headerMessage }}
      </p>

      <!-- 选择表单 -->
      <form class="other-charge-group-modal__form" @submit.prevent="handleSubmit">
        <!-- 工单选择 -->
        <div class="other-charge-group-modal__field">
          <label class="other-charge-group-modal__label">工单号</label>
          <VanField
            v-model="formData.workOrderCode"
            placeholder="请选择工单"
            readonly
            right-icon="arrow-down"
            :disabled="!workOrderOptions.length"
            @click="workOrderOptions.length ? showWorkOrderSelector = true : showToast('暂无工单可选')"
          />
        </div>

        <!-- 材料组选择 -->
        <div class="other-charge-group-modal__field">
          <label class="other-charge-group-modal__label">材料组名称</label>
          <VanField
            v-model="formData.groupName"
            placeholder="请先选择工单"
            readonly
            right-icon="arrow-down"
            :disabled="!formData.workOrderId || !materialGroups.length"
            @click="formData.workOrderId && materialGroups.length ? showGroupSelector = true : showToast(formData.workOrderId ? '该工单暂无材料组' : '请先选择工单')"
          />
        </div>

        <!-- 材料数量提示 -->
        <p v-if="materials.length" class="other-charge-group-modal__material-count">
          已获取 {{ materials.length }} 条材料
        </p>

        <!-- 操作按钮 -->
        <div class="other-charge-group-modal__buttons">
          <VanButton
            plain
            type="default"
            size="normal"
            class="other-charge-group-modal__cancel-btn"
            @click="closeModal"
          >
            取消
          </VanButton>
          <VanButton
            type="primary"
            size="normal"
            native-type="submit"
            class="other-charge-group-modal__confirm-btn"
            :loading="loading"
            :disabled="!canSubmit"
          >
            添加
          </VanButton>
        </div>
      </form>
    </div>

    <!-- 工单选择器弹窗 -->
    <VanPopup
      v-model:show="showWorkOrderSelector"
      position="bottom"
      teleport="#other-charge-form"
      round
      destroy-on-close
    >
      <VanPicker
        :columns="workOrderOptions"
        show-toolbar
        title="选择工单"
        @confirm="onWorkOrderSelected"
        @cancel="showWorkOrderSelector = false"
      />
    </VanPopup>

    <!-- 材料组选择器弹窗 -->
    <VanPopup
      v-model:show="showGroupSelector"
      position="bottom"
      teleport="#other-charge-form"
      round
      destroy-on-close
    >
      <VanPicker
        :columns="groupOptions"
        show-toolbar
        title="选择材料组"
        @confirm="onGroupSelected"
        @cancel="showGroupSelector = false"
      />
    </VanPopup>
  </VanPopup>
</template>

<style scoped lang="less">
/* 组件样式：整体结构 */
.other-charge-group-modal {
  /* 容器样式，含内边距与定位 */
  &__container {
    padding: 16px;
    position: relative;
  }

  /* 头部区域布局 */
  &__header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;
  }

  /* 标题样式 */
  &__title {
    font-size: 18px;
    font-weight: 500;
    color: #1f2937;
    margin: 0;
  }

  /* 表单输入域样式 */
  &__form {
    .van-field {
      background-color: #f9fafb;
      border-radius: 6px;
    }
  }

  /* 单个字段间距 */
  &__field {
    margin-bottom: 16px;
  }

  /* 字段标题样式 */
  &__label {
    display: block;
    font-size: 14px;
    font-weight: 500;
    color: #374151;
    margin-bottom: 4px;
  }

  /* 操作按钮区域 */
  &__buttons {
    display: flex;
    justify-content: flex-end;
    margin-top: 24px;
    gap: 12px;
  }

  /* 取消按钮样式 */
  &__cancel-btn {
    border-color: #d1d5db;
    color: #374151;
  }

  /* 确认按钮样式 */
  &__confirm-btn {
    background-color: #2563eb;
  }

  /* 加载遮罩样式 */
  &__loading-mask {
    position: absolute;
    inset: 0;
    background-color: rgba(255, 255, 255, 0.85);
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 2;
    border-radius: 12px;
  }

  /* 顶部提示文字 */
  &__tip {
    margin: 8px 0 0 0;
    font-size: 13px;
    color: #ef4444;
  }

  /* 材料数量提示 */
  &__material-count {
    font-size: 13px;
    color: #10b981;
    margin: 0 0 12px 0;
  }
}
</style>
