<template>
  <el-select
    v-model="selected"
    :placeholder="placeholder"
    :clearable="clearable"
    :disabled="disabled"
    :size="size"
    :multiple="multiple"
    :collapse-tags="collapseTags"
    filterable
    @change="onChange"
    style="width: 100%"
  >
    <el-option
      v-for="item in warehouseOptions"
      :key="item.warehouseId"
      :label="item.warehouseName"
      :value="item.warehouseId" 
      :disabled="item.isEnabled == 0"
    >
      <span :style="{ paddingLeft: item.level * 20 + 'px' }">
        {{ item.warehouseName }}
      </span>
    </el-option>
  </el-select>
</template>

<script>
import { listWarehouse } from '@/api/wms/warehouse';

export default {
  name: 'WarehouseSelect',
  props: {
    value: {
      type: [Number, String, Array, null],
      default: null
    },
    multiple: {
      type: Boolean,
      default: false
    },
    placeholder: {
      type: String,
      default: '请选择仓库'
    },
    clearable: {
      type: Boolean,
      default: true
    },
    disabled: {
      type: Boolean,
      default: false
    },
    size: {
      type: String,
      default: 'mini'
    },
    collapseTags: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      warehouseOptions: [],
      selected: this.value
    };
  },
  watch: {
    value(val) {
      console.log('[WarehouseSelect] value changed:', val, 'type:', typeof val, 'isArray:', Array.isArray(val));
      this.selected = val;
    }
  },
  mounted() {
    console.log('[WarehouseSelect] mounted, initial value:', this.value, 'multiple:', this.multiple);
    this.loadOptions();
  },
  methods: {
    loadOptions() {
      listWarehouse().then(response => {
        console.log('仓库API返回数据:', response);
        const data = response.data || [];
        console.log('处理后的数据:', data);
        let options = this.buildTreeOptions(data);
        options = this.sortOptionsByUsage(options);
        this.warehouseOptions = options;
        console.log('构建并排序后的树形选项:', this.warehouseOptions);
      }).catch(error => {
        console.error("加载仓库选项失败:", error);
        this.warehouseOptions = [];
      });
    },
    buildTreeOptions(data, parentId = null, level = 0) {
      const options = [];
      
      data.forEach(item => {
        if (item.parentId === parentId) {
          const option = {
            warehouseId: item.warehouseId,
            warehouseName: item.warehouseName,
            level: level,
            isEnabled: item.isEnabled,
          };
          
          // 递归构建子节点
          const children = this.buildTreeOptions(data, item.warehouseId, level + 1);
          if (children.length > 0) {
            options.push(option);
            options.push(...children);
          } else {
            options.push(option);
          }
        }
      });
      
      return options;
    },
    getWarehouseUsage() {
      try {
        const usage = localStorage.getItem('warehouseUsage');
        return usage ? JSON.parse(usage) : {};
      } catch (error) {
        console.error('获取仓库使用记录失败:', error);
        return {};
      }
    },
    updateWarehouseUsage(warehouseId) {
      try {
        const usage = this.getWarehouseUsage();
        usage[warehouseId] = (usage[warehouseId] || 0) + 1;
        localStorage.setItem('warehouseUsage', JSON.stringify(usage));
      } catch (error) {
        console.error('更新仓库使用记录失败:', error);
      }
    },
    sortOptionsByUsage(options) {
      const usage = this.getWarehouseUsage();
      return options.sort((a, b) => {
        const usageA = usage[a.warehouseId] || 0;
        const usageB = usage[b.warehouseId] || 0;
        return usageB - usageA;
      });
    },
    onChange(val) {
      if (val) {
        if (this.multiple && Array.isArray(val)) {
          val.forEach(function(id) { this.updateWarehouseUsage(id); }, this);
        } else {
          this.updateWarehouseUsage(val);
        }
      }
      this.$emit('input', val);
      this.$emit('change', val);
    }
  }
};
</script>

<style scoped>
.el-select {
  width: 100%;
}
</style>
