<template>
  <van-nav-bar
    :title="title" left-arrow left-text="返回" fixed placeholder right-text="返回菜单" @click-left="goBack()"
    @click-right="goMenu"
  />
  <div class="content">
    <div class="scan-btn">
      <van-button block plain icon="orders-o" type="primary">
        等待扫码数据
      </van-button>
    </div>
    <van-form :scroll-to-error="true">
      <van-field v-model="stockData.no" name="no" label="物料编号:" :readonly="true" />

      <van-field v-model="stockData.name" name="name" label="物料名称:" :readonly="true" />

      <van-field v-model="stockData.type" name="type" label="规格型号:" :readonly="true" />

      <van-field v-model="stockData.batchNo" name="batchNo" label="批号:" placeholder="点击输入批号" type="textarea" rows="1" autosize />

      <van-field v-model="stockData.num" name="num" label="生产数量:" placeholder="点击输入生产数量" />
      <van-field name="inventoryPackaged" label="是否包装">
        <template #input>
          <van-switch v-model="stockData.inventoryPackaged" size="20px" />
        </template>
      </van-field>

      <van-field v-model="stockData.carrierTypeName" name="carrierTypeName" label="托盘类型:" placeholder="点击选择托盘类型" is-link @click="showCarrierTypePicker = true" />

      <van-field
        v-model="stockData.transferName" is-link readonly name="transfer" label="中转区货位:"
        placeholder="点击选择中转区货位" @click="isShowTransfer = true"
      />
      <van-field
        v-model="stockData.idleName" is-link readonly name="warehouse" label="入库货位:" placeholder="点击选择入库货位"
        @click="isShowIdle = true"
      />
      <div style="margin: 16px">
        <van-button round block type="primary" @click="submit">
          提交
        </van-button>
      </div>
    </van-form>
  </div>
  <div>
    <position-selector
      ref="transferPositionSelector" v-model:show="isShowTransfer" position-type="transfer"
      @confirm="onTransferPositionSelected"
    />
    <position-selector
      ref="idlePositionSelector" v-model:show="isShowIdle" position-type="idle" type="stockInPhoto"
      :is-default="true" @confirm="onIdlePositionSelected"
    />
  </div>
  <van-popup v-model:show="showCarrierTypePicker" destroy-on-close round position="bottom">
    <van-picker
      :model-value="carrierType"
      :columns="columns"
      @cancel="showCarrierTypePicker = false"
      @confirm="onConfirm"
    />
  </van-popup>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import PositionSelector from './PositionSelector.vue';
import { processException } from '../common/Common.js';
import { ajaxApiGet, ajaxApiPost } from '../common/utils.js';
import { showSuccessToast, showFailToast, showConfirmDialog } from 'vant';
import { showFullscreenLoading, hideFullscreenLoading } from '../common/loading.js';

const route = useRoute();
const router = useRouter();

// WebSocket实例
const ws = ref(null);

// 状态
const isShowTransfer = ref(false);
const isShowIdle = ref(false);
const transferPositionSelector = ref(null);
const idlePositionSelector = ref(null);

const stockData = ref({
  no: '',
  name: '',
  type: '',
  num: '',
  batchNo: '',
  transferId: '',
  transferName: '',
  transferNo: '',
  idleId: '',
  idleName: '',
  idleNo: '',
  inventoryPackaged: false,
  carrierType:'',
  carrierTypeName: '',
});

const warehouseId = ref('');
const title  = ref('');

onMounted(() => {
  warehouseId.value = route.query.warehouseId || '';
  title.value = route.query.warehouseName ? '扫描入库 - ' + route.query.warehouseName : '扫描入库';
  getCarrierTypeList();

  // 建立WebSocket连接
  initWebSocket();
});

onUnmounted(() => {
  // 关闭WebSocket连接
  if (ws.value) {
    ws.value.close();
  }
});

// 初始化WebSocket连接
const initWebSocket = () => {
  const wsUrl = 'ws://127.0.0.1:10023';
  ws.value = new WebSocket(wsUrl);

  ws.value.onopen = () => {
    console.log('WebSocket连接已建立');
  };

  ws.value.onmessage = event => {
    handleWebSocketMessage(event);
  };

  ws.value.onerror = error => {
    console.error('WebSocket错误:', error);
  };

  ws.value.onclose = () => {
    console.log('WebSocket连接已关闭');
  };
};

// 处理WebSocket消息
const handleWebSocketMessage = event => {
  try {
    // 解析接收到的JSON数据
    const data = JSON.parse(event.data);
    console.log('接收到WebSocket数据:', data);

    // 将数据赋值到对应字段
    if (data.batchNumber) {
      stockData.value.batchNo = data.batchNumber;
    }
    if (data.count) {
      stockData.value.num = data.count.toString();
    }

    // 使用code调用getInfo方法
    if (data.code) {
      getInfo(data.code);
    }
  } catch (error) {
    console.error('解析WebSocket消息失败:', error);
    showFailToast('解析数据失败，请检查数据格式');
  }
};

const columns = ref([]);
const showCarrierTypePicker = ref(false);
const carrierType = ref([]);
const onConfirm = ({ selectedValues, selectedOptions }) => {
  showCarrierTypePicker.value = false;
  stockData.value.carrierType = selectedValues[0];
  stockData.value.carrierTypeName = selectedOptions[0].text;
};

const goBack = () => {
  router.back();
};

const goMenu = () => {
  router.push('/app-menus');
};
// 处理中转区货位选择结果
const onTransferPositionSelected = item => {
  stockData.value.transferId = item.id;
  stockData.value.transferNo = item.no;
  stockData.value.transferName = item.name;
};

// 处理入库货位选择结果
const onIdlePositionSelected = item => {
  stockData.value.idleId = item.id;
  stockData.value.idleNo = item.no;
  stockData.value.idleName = item.name;
};

// 清除表单数据
const clearFormData = () => {
  stockData.value = {
    id: '',
    no: '',
    name: '',
    type: '',
    num: '',
    batchNo: '',
    transferId: '',
    transferName: '',
    transferNo: '',
    idleId: '',
    idleName: '',
    idleNo: '',
    inventoryPackaged: false,
    carrierType:'',
    carrierTypeName:'',
  };
  carrierType.value = [];
  transferPositionSelector.value.clearSelected();
  idlePositionSelector.value.clearSelected();
};

// 提交入库
const submit = () => {
  console.log(stockData.value);
  if (!stockData.value.no) {
    showFailToast({ duration: 4000, message: '请等待扫码数据并确认入库信息后再提交' });
    return;
  }
  if (!stockData.value.num) {
    showFailToast('请输入入库数量');
    return;
  }
  if (!stockData.value.transferId) {
    showFailToast('请选择中转区货位');
    return;
  }
  if (!stockData.value.idleId) {
    showFailToast('请选择入库货位');
    return;
  }
  if (!stockData.value.carrierType) {
    showFailToast('请选择托盘类型');
    return;
  }
  showConfirmDialog({
    title: '确认要入库吗？',
    message: '如果确认要入库，请点击【确认】按钮，否则点击【取消】按钮。',
  })
    .then(() => {
      submitStockIn();
    })
    .catch(() => {
      console.log('取消');
    });
};



// 获取入库物料详情
const getInfo = no => {
  showFullscreenLoading();
  const url = `/api/InventoryResource/queryStockInInventory?start=0&length=1&filter=${no}`;
  ajaxApiGet(url).then(
    success => {
      const { errorCode, errorMessage, datas } = success;
      if (errorCode === 0) {
        if (datas && datas.length) {
          stockData.value = { ...stockData.value, ...datas[0] };
          showSuccessToast({ duration: 1000, message: '获取信息成功。' });
        }
      } else {
        showFailToast({ duration: 1000, message: errorMessage });
      }
      hideFullscreenLoading();
    },
    error => {
      hideFullscreenLoading();
      processException(error);
    },
  );
};

// 提交API
const submitStockIn = () => {
  const url = '/api/stockInResource/scanGeneratorStockIn';
  const params = JSON.parse(JSON.stringify(stockData.value));
  delete params.workDate;
  ajaxApiPost(url, params).then(
    success => {
      if (success.errorCode === 0) {
        showSuccessToast('入库成功');
        clearFormData();
      } else {
        showFailToast(success.errorMessage);
      }
    },
    error => {
      processException(error);
    },
  );
};

const getCarrierTypeList = () => {
  const url = '/api/CarrierTypeResource/queryAllType';
  ajaxApiGet(url).then(
    success => {
      const { errorCode, errorMessage, datas, total } = success;
      if (errorCode === 0) {
        if (datas && datas.length) {
          columns.value = datas.map(item => ({ text: item.name, value: item.id }));
        } else {
          columns.value = [];
        }
      } else {
        showFailToast(errorMessage);
      }
    },
    error => {
      processException(error);
    },
  );
};
</script>

<style scoped>
.content {
  margin-top: 10px;
}

.scan-btn {
  margin: 0 10px;
}

.custom-picker {
  display: flex !important;
  flex-direction: column !important;
  height: 100% !important;
}

.picker-header {
  display: flex !important;
  justify-content: space-between !important;
  align-items: center !important;
  padding: 10px 16px !important;
  border-bottom: 1px solid #ebedf0 !important;
}

.picker-title {
  font-size: 16px !important;
  font-weight: 500 !important;
}

.picker-content {
  flex: 1 !important;
  overflow-y: auto !important;
}

.picker-footer {
  padding: 10px 16px !important;
  border-top: 1px solid #ebedf0 !important;
  display: flex !important;
  flex-direction: column !important;
  gap: 8px !important;
}

.loading-more {
  text-align: center !important;
  color: #969799 !important;
  padding: 10px 0 !important;
}
</style>
