<!-- ChannelCascader.vue -->
<template>
  <el-cascader
    v-model="selectedValue"
    :props="cascaderProps"
    :placeholder="placeholder"
    :options="groupedChannels"
    :filterable="filterable"
    :disabled="disabled"
    :show-all-levels="false"
    @change="handleChange"
    clearable
  >
    <template #default="{ node, data }">
      <div class="flex items-center">
        <span>{{ data.label }}</span>
        <span v-if="node.isLeaf" class="ml-2 text-gray-400 text-sm">
          {{ data.code }}
          <!-- 根据实际字段显示渠道编码 -->
        </span>
      </div>
    </template>
  </el-cascader>
</template>

<script setup>
import { ref, watch, onMounted } from 'vue';
import { listAllLogisticsChannel } from '@/api/amz/logisticsChannel';

const props = defineProps({
  modelValue: [String, Number, Array],
  placeholder: {
    type: String,
    default: '请选择物流渠道'
  },
  filterable: {
    type: Boolean,
    default: true
  },
  disabled: Boolean
});

const emit = defineEmits(['update:modelValue', 'change']);

const groupedChannels = ref([]);
const selectedValue = ref(props.modelValue);

const cascaderProps = {
  emitPath: false
};

// 监听外部值变化
watch(
  () => props.modelValue,
  (newVal) => {
    selectedValue.value = newVal;
  }
);

// 初始化加载数据
onMounted(async () => {
  await loadChannels();
});

const loadChannels = async () => {
  try {
    const res = await listAllLogisticsChannel();
    groupedChannels.value = transformChannels(res.rows); // 注意这里使用 res.rows
  } catch (error) {
    console.error('物流渠道加载失败:', error);
    ElMessage.error('渠道数据加载失败');
  }
};

// 定义映射关系，将编码转换为中文标签
const countryMap = {
  us: '美国',
  cn: '中国',
  jp: '日本',
  kr: '韩国',
  sg: '新加坡',
  de: '德国',
  fr: '法国',
  gb: '英国',
  it: '意大利',
  es: '西班牙',
  ru: '俄罗斯',
  ca: '加拿大',
  au: '澳大利亚',
  in: '印度',
  br: '巴西',
  za: '南非',
  mx: '墨西哥'
};

const shippingMethodMap = {
  air: '空运',
  sea: '海运'
  // 可扩展其他运输方式
};

function transformChannels(channels) {
  const result = [];
  const countryGroups = {}; // 按国家缓存顶级节点

  channels.forEach((channel) => {
    const { country, shippingMethod, channelName, id } = channel;

    // 处理国家节点
    const countryValue = country;
    const countryLabel = countryMap[country] || country;
    if (!countryGroups[countryValue]) {
      countryGroups[countryValue] = {
        value: countryValue,
        label: countryLabel,
        children: []
      };
      result.push(countryGroups[countryValue]);
    }

    // 处理运输方式节点
    const methodValue = shippingMethod;
    const methodLabel = shippingMethodMap[shippingMethod] || shippingMethod;
    let methodNode = countryGroups[countryValue].children.find((m) => m.value === methodValue);
    if (!methodNode) {
      methodNode = {
        value: methodValue,
        label: methodLabel,
        children: []
      };
      countryGroups[countryValue].children.push(methodNode);
    }

    // 添加渠道节点
    methodNode.children.push({
      value: id,
      label: channelName
    });
  });

  return result;
}

// // 数据结构转换方法
// const transformData = (items) => {
//   return items.map((item) => ({
//     channelId: item.id, // 假设你的返回字段是 id
//     channelName: item.name, // 假设你的返回字段是 name
//     code: item.code, // 额外携带的渠道编码
//     children: item.children ? transformData(item.children) : undefined
//   }));
// };

const handleChange = (value) => {
  console.log('handleChange', value);
  console.log('groupedChannels.value', groupedChannels.value);
  emit('update:modelValue', value);

  const node = findNode(value, groupedChannels.value);
  if (node != null) {
    emit('change', {
      value,
      node: findNode(value, groupedChannels.value).label
    });
  } else {
    emit('change', {
      value,
      node: null
    });
  }
};

// 递归查找节点
const findNode = (value, options) => {
  for (const item of options) {
    if (item.value === value) return item;
    if (item.children) {
      const found = findNode(value, item.children);
      if (found) return found;
    }
  }
  return null;
};
</script>
