<template>
  <div style="position: relative;">
    <div style="position: absolute; top: 10px; left: 10px;">
      <!-- 策略切换单选框 -->
      <el-radio-group 
        v-model="currentStrategy" 
        size="mini"
      >
        <el-radio label="stockIo">盘点单</el-radio>
        <el-radio label="order">订单</el-radio>
        <el-radio label="purchase">采购计划</el-radio>
      </el-radio-group>

      <!-- 动态下拉选择框，根据策略切换数据源 -->
      <el-select 
        v-model="currentId" 
        :placeholder="`请选择${strategyLabels[currentStrategy]}`" 
        style="width: 200px;"
        size="mini"
      >
        <el-option 
          v-for="item in currentList" 
          :key="item[keyField]" 
          :label="item[labelField]" 
          :value="item[keyField]" 
        />
      </el-select>
    </div>
    
    <div class="print-container" v-loading="loading">
      <BarCode :barcodes="drawerBarcodeData" @delete="handleDelete" />
    </div>
  </div>
</template>

<script>
import BarCode from '../stockIo/panels/barcode.vue';
import { listStockIo } from '@/api/wms/stockIo';
import { listStockIoDetail } from '@/api/wms/stockIoDetail';
import { listOrder } from '@/api/wms/order';
import { listOrderDetail } from '@/api/wms/orderDetail';
import { listPurchasePlan } from '@/api/wms/purchasePlan';
import { listPurchasePlanDetail } from '@/api/wms/purchasePlanDetail';
import { mapState } from 'vuex';
import { ITEM_TYPE } from '../../../utils/enums';

// 策略配置 - 集中管理各策略的元数据
const strategyMetadata = {
  stockIo: {
    label: '盘点单',
    listKey: 'stockIoList',
    keyField: 'stockIoId',
    labelField: 'stockIoCode'
  },
  order: {
    label: '订单',
    listKey: 'orderList',
    keyField: 'orderId',
    labelField: 'orderCode'
  },
  purchase: {
    label: '采购计划',
    listKey: 'purchaseList',
    keyField: 'planId',
    labelField: 'planCode'
  }
};

// 策略实现 - 封装各策略的具体业务逻辑
const strategies = {
  stockIo: {
    // 加载列表数据
    list: (vm) => {
      if (vm.stockIoList.length) return;
      vm.loading = true;
      listStockIo({ pageNum: 1, pageSize: 9999 }).then(res => {
        vm.stockIoList = res.rows || [];
      }).finally(() => {
        vm.loading = false;
      });
    },
    // 获取条码数据
    getBarcodeData: (vm) => {
      if (!vm.currentId) return;
      vm.loading = true;
      listStockIoDetail({ stockIoId: vm.currentId }).then(res => {
        const details = res.rows || [];
        vm.drawerBarcodeData = details
          .filter(el => el.recordType === 0)
          .map(item => ({
            code: encodeURIComponent(`${item.itemType}__${item.itemId || ''}`),
            count: Math.min(item.quantity, 10),
            textTpl: item.itemType === ITEM_TYPE.PRODUCT 
              ? `${vm.productMap[item.itemId]?.productName}[${vm.productMap[item.itemId]?.productCode}](${item.quantity})`
              : `${vm.rawMaterialMap[item.itemId]?.rawMaterialName}[${vm.rawMaterialMap[item.itemId]?.rawMaterialCode}](${item.quantity})`
          }));
      }).finally(() => {
        vm.loading = false;
      });
    }
  },
  order: {
    list: (vm) => {
      if (vm.orderList.length) return;
      vm.loading = true;
      listOrder({ pageNum: 1, pageSize: 9999 }).then(res => {
        vm.orderList = res.rows || [];
      }).finally(() => {
        vm.loading = false;
      });
    },
    getBarcodeData: (vm) => {
      if (!vm.currentId) return;
      vm.loading = true;
      listOrderDetail({ orderId: vm.currentId }).then(res => {
        const details = res.rows || [];
        vm.drawerBarcodeData = details.map(item => ({
          code: encodeURIComponent(`product__${item.productId || ''}`),
          count: Math.min(item.quantity, 10),
          textTpl: `${vm.productMap[item.productId]?.productName}[${vm.productMap[item.productId]?.productCode}](${item.quantity})`
        }));
      }).finally(() => {
        vm.loading = false;
      });
    }
  },
  purchase: {
    list: (vm) => {
      if (vm.purchaseList.length) return;
      vm.loading = true;
      listPurchasePlan({ pageNum: 1, pageSize: 9999 }).then(res => {
        vm.purchaseList = res.rows || [];
      }).finally(() => {
        vm.loading = false;
      });
    },
    getBarcodeData: (vm) => {
      if (!vm.currentId) return;
      vm.loading = true;
      listPurchasePlanDetail({ planId: vm.currentId }).then(res => {
        const details = res.rows || [];
        vm.drawerBarcodeData = details.map(item => ({
          code: encodeURIComponent(`raw_material__${item.rawMaterialId || ''}`),
          count: Math.min(item.quantity, 10),
          textTpl: `${vm.rawMaterialMap[item.rawMaterialId]?.rawMaterialName}[${vm.rawMaterialMap[item.rawMaterialId]?.rawMaterialCode}](${item.quantity})`
        }));
      }).finally(() => {
        vm.loading = false;
      });
    }
  }
};

export default {
  name: 'Print',
  components: { BarCode },
  data() {
    return {
      currentStrategy: 'stockIo', // 默认策略
      currentId: '', // 当前选中的ID
      stockIoList: [], // 盘点单列表
      orderList: [], // 订单列表
      purchaseList: [], // 采购计划列表
      drawerBarcodeData: [], // 条码数据
      loading: false // 加载状态
    };
  },
  computed: {
    ...mapState({
      rawMaterialMap: state => state.category.rawMaterialMap,
      productMap: state => state.category.productMap
    }),
    // 策略标签映射
    strategyLabels() {
      return Object.keys(strategyMetadata).reduce((obj, key) => {
        obj[key] = strategyMetadata[key].label;
        return obj;
      }, {});
    },
    // 当前策略对应的列表数据
    currentList() {
      return this[strategyMetadata[this.currentStrategy].listKey] || [];
    },
    // 当前策略的主键字段
    keyField() {
      return strategyMetadata[this.currentStrategy].keyField;
    },
    // 当前策略的显示字段
    labelField() {
      return strategyMetadata[this.currentStrategy].labelField;
    }
  },
  watch: {
    // 策略切换时的处理
    currentStrategy: {
      handler(newVal) {
        this.currentId = ''; // 清空选择
        this.drawerBarcodeData = []; // 清空条码数据
        // 加载对应策略的列表数据
        if (strategies[newVal]?.list) {
          strategies[newVal].list(this);
        }
      },
      immediate: true // 初始化时执行
    },
    // 选中项变化时的处理
    currentId(newVal) {
      if (!newVal) {
        this.drawerBarcodeData = [];
        return;
      }
      // 获取对应策略的条码数据
      if (strategies[this.currentStrategy]?.getBarcodeData) {
        strategies[this.currentStrategy].getBarcodeData(this);
      }
    }
  },
  methods: {
    handleDelete(cfg, idx) {
      this.drawerBarcodeData.splice(idx, 1);
    }
  }
};
</script>

<style scoped lang="scss">
.print-container {
  margin-top: 20px;
  padding: 20px;
}
</style>
