<template>
  <van-nav-bar title="拍照入库" left-arrow left-text="返回" fixed placeholder @click-left="goBack()" />
  <van-image v-if="imageUrl" width="100%" height="100%" :src="imageUrl" />
  <div class="content">
    <div class="scan-btn">
      <input
        ref="fileInput" type="file" accept="image/*" capture="camera" style="display: none"
        @change="onFileChange"
      />
      <van-button block plain icon="scan" type="primary" @click="takePhoto">
        拍摄
      </van-button>
      <van-button style="margin-top: 10px" block plain icon="orders-o" type="primary" @click="uploadImage">
        识别
      </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="点击输入批号" />

      <van-field v-model="stockData.num" name="num" label="生产数量:" placeholder="点击输入生产数量" />

      <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 v-model:show="isShowTransfer" position-type="transfer" @confirm="onTransferPositionSelected" />
    <position-selector v-model:show="isShowIdle" position-type="idle" @confirm="onIdlePositionSelected" />
  </div>
</template>

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


const router = useRouter();

const imageUrl = ref('');
const fileInput = ref(null);
const photoFile = ref(null);

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

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

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

const takePhoto = () => {
  fileInput.value.click();
};

// 处理文件选择/拍照结果
const onFileChange = event => {
  const file = event.target.files[0];
  if (!file) return;

  imageUrl.value = URL.createObjectURL(file);

  photoFile.value = file;

};
// 处理中转区货位选择结果
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: '',
  };
  imageUrl.value = '';
  photoFile.value = null;
};

// 提交入库
const submit = () => {
  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;
  }
  showConfirmDialog({
    title: '确认要入库吗？',
    message: '如果确认要入库，请点击【确认】按钮，否则点击【取消】按钮。',
  })
    .then(() => {
      submitStockIn();
    })
    .catch(() => {
      console.log('取消');
    });
};

// 上传图片获取入库信息
const uploadImage = async () => {
  if (!photoFile.value) {
    showFailToast('请先拍摄图片后再进行识别');
    return;
  }
  const url = 'http://192.168.1.109:10020/AppApi/OcrResource';
  const fileData = new FormData();
  fileData.append('image', photoFile.value);

  showFullscreenLoading();
  try {
    const response = await fetch(url, {
      method: 'POST',
      body: fileData,
    });

    if (response.ok) {
      const result = await response.json();

      if (result.errorCode === 0) {
        if (result.recognizeResult) {
          stockData.value = { ...result.recognizeResult };
          getInfo(result.recognizeResult.no);
        }
      } else {
        showFailToast({ duration: 4000, message: result.errorMessage });
      }
      hideFullscreenLoading();
    } else {
      hideFullscreenLoading();
      showFailToast(`识别失败 (${response.status}): ${response.statusText}`);
    }
  } catch (error) {
    hideFullscreenLoading();
    showFailToast('识别图片失败: 请调整角度后重新拍摄');
  }
};

// 获取入库物料详情
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: 5000, message: '获取信息成功，请先确认生产数量是否准确，若不准确请先修改数量。' });
        }
      } else {
        showFailToast({ duration: 5000, 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);
    },
  );
};
</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>
