<template>
  <van-nav-bar
    title="入库" left-arrow left-text="返回" right-text="拍照" fixed placeholder @click-left="goBack()"
    @click-right="goTakePhoto"
  />
  <van-search v-model="stockInSearch" placeholder="请输入搜索关键词" @search="searchStockIn" />
  <div class="content">
    <div class="van-list-stock-in">
      <van-list
        v-model:loading="loading" class="list-stock-in" :finished="finished" finished-text=""
        :immediate-check="false" @load="loadStockInList"
      >
        <div v-for="(item, index) in stockInList" :key="item.id" class="list-container">
          <van-form :scroll-to-error="true">
            <div class="in-header">
              <strong>{{ index + 1 }}. {{ item.name }}</strong>
              <van-button type="primary" plain @click="stockIn(item)">入库</van-button>
            </div>
            <van-field v-model="item.no" name="no" label="物料编号:" readonly />
            <van-field v-model="item.name" name="name" label="物料名称:" readonly />
            <van-field v-model="item.type" name="type" label="规格型号:" readonly />
          </van-form>
        </div>
      </van-list>
    </div>
    <van-empty v-if="stockInList.length === 0" description="暂无入库单" />
  </div>
  <van-dialog v-model:show="isShowStockIn" title="填写入库信息" :show-confirm-button="false">
    <van-form :scroll-to-error="true">
      <van-field v-model="formData.no" name="no" label="物料编号:" readonly />
      <van-field v-model="formData.name" name="name" label="物料名称:" readonly />
      <van-field v-model="formData.type" name="type" label="规格型号:" readonly />
      <van-field v-model="formData.batchNo" name="batchNo" label="批号:" placeholder="点击输入批号" />
      <van-field v-model="formData.num" name="num" label="入库数量:" placeholder="点击输入数量" />
      <van-field
        v-model="formData.transferName" is-link readonly name="transfer" label="中转区货位:" placeholder="点击选择中转区货位"
        @click="isShowTransfer = true"
      />
      <van-field
        v-model="formData.idleName" is-link readonly name="warehouse" label="入库货位:" placeholder="点击选择入库货位"
        @click="isShowIdle = true"
      />
    </van-form>

    <template #footer>
      <div class="footer-btn">
        <van-button style="width: 40%;" plain type="primary" @click="cancelStockIn">
          取消
        </van-button>
        <van-button style="width: 40%;" type="primary" @click="stockInConfirm">
          提交
        </van-button>
      </div>
    </template>
  </van-dialog>
  <position-selector
    v-model:show="isShowTransfer" position-type="transfer" :default-selected-id="formData.transferId"
    @confirm="onTransferPositionSelected"
  />
  <position-selector
    v-model:show="isShowIdle" position-type="idle" :default-selected-id="formData.idleId"
    @confirm="onIdlePositionSelected"
  />
</template>

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

const router = useRouter();

const stockInSearch = ref('');

const stockInList = ref([]);
const loading = ref(false);
const finished = ref(false);

const page = ref(1);
const total = ref(0);
const pageSize = ref(10);

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

const isShowStockIn = ref(false);
const isShowTransfer = ref(false);
const isShowIdle = ref(false);

const goBack = () => {
  router.push('/app-menus');
};

// 搜索入库物料
const searchStockIn = value => {
  console.log(value);
  page.value = 1;
  total.value = 0;
  stockInList.value = [];
  loadStockInList();
};

// 处理中转区货位选择结果
const onTransferPositionSelected = item => {
  console.log(item, '中转区货位选择结果');
  formData.value.transferName = item.name;
  formData.value.transferId = item.id;
  formData.value.transferNo = item.no;
};

// 处理入库货位选择结果
const onIdlePositionSelected = item => {
  console.log(item, '入库货位选择结果');
  formData.value.idleName = item.name;
  formData.value.idleId = item.id;
  formData.value.idleNo = item.no;
};

// 入库
const stockIn = item => {
  console.log(item, '入库');
  formData.value.id = item.id;
  formData.value.no = item.no;
  formData.value.name = item.name;
  formData.value.type = item.type;
  isShowStockIn.value = true;
};

// 入库确认
const stockInConfirm = () => {
  console.log(formData.value, '入库确认');

  if (!formData.value.num) {
    showFailToast('请输入入库数量');
    return;
  }
  if (!formData.value.transferId) {
    showFailToast('请选择中转区货位');
    return;
  }
  if (!formData.value.idleId) {
    showFailToast('请选择入库货位');
    return;
  }
  submitStockIn();
};

// 加载入库物料列表
const loadStockInList = async () => {
  try {
    const res = await getList(page.value, pageSize.value);

    // 搜索时替换数据，上拉加载时追加数据
    stockInList.value =
      page.value === 1
        ? res.data
        : [...stockInList.value, ...res.data];

    total.value = res.total;

    // 检查是否已加载全部数据
    if (stockInList.value.length >= total.value) {
      finished.value = true;
    } else {
      page.value++; // 只有在成功加载后才增加页码
    }
  } catch (error) {
    processException(error);
    finished.value = true;
  } finally {
    loading.value = false;
  }
};

// 获取入库物料列表API
const getList = (page, pageSize) => {
  const start = (page - 1) * pageSize;
  const length = pageSize;
  const filter = '';
  const url = `/api/InventoryResource/queryStockInInventory?start=${start}&length=${length}&filter=${filter}`;
  return new Promise((resolve, reject) => {
    ajaxApiGet(url).then(
      success => {
        const { errorCode, errorMessage, datas, total } = success;
        if (errorCode === 0) {
          if (datas && datas.length) {
            resolve({ data: datas, total: total });
          } else {
            resolve({ data: [], total: 0 });
          }
        } else {
          const error = { status: 200, responseText: errorMessage };
          reject(error);
        }
      },
      error => {
        reject(error);
      },
    );
  });
};

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


// 取消入库
const cancelStockIn = () => {
  clearFormData();
  isShowStockIn.value = false;
};

// 清除表单数据
const clearFormData = () => {
  formData.value = {
    no: '',
    name: '',
    type: '',
    num: '',
    batchNo: '',
    transferId: '',
    transferName: '',
    transferNo: '',
    idleId: '',
    idleName: '',
    idleNo: '',
  };
};


// 拍照
const goTakePhoto = () => {
  router.push('/stock-in-photo');
};
onMounted(() => {
  loadStockInList();
});

</script>

<style scoped>
.van-search {
  padding-bottom: 4px !important;
}

.list-container {
  padding: 3px 10px;
  border: 1px solid #ccc;
  border-radius: 4px;
  margin: 6px 12px;
}

.in-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid #ccc;
  padding-bottom: 4px;
}

.footer-btn {
  display: flex;
  justify-content: space-around;
  align-items: center;
  margin-bottom: 10px;
}
</style>
