<template>
  <van-nav-bar
    title="待返回出库单" left-arrow left-text="返回" fixed placeholder @click-left="goBack()"
  />
  <van-search v-model="stockBackSearch" placeholder="请输入搜索关键词" @search="searchStockBack" />
  <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="loadStockOutBackList"
      >
        <div v-for="(item, index) in stockBackList" :key="item.id" class="list-container">
          <van-form :scroll-to-error="true">
            <div class="in-header">
              <strong>{{ index + 1 }}. {{ item.inventoryName }}</strong>
              <van-button type="primary" plain @click="stockOutConfirm(item)">返回</van-button>
            </div>
            <van-field v-model="item.inventoryNo" name="inventoryNo" label="物料编号:" readonly />
            <van-field v-model="item.inventoryName" name="inventoryName" label="物料名称:" readonly />
            <van-field v-model="item.inventoryType" name="inventoryType" label="规格型号:" readonly />
            <van-field v-model="item.quantity" name="quantity" label="数量:" readonly />
            <van-field v-model="item.batchNo" name="batchNo" label="批号:" readonly />
            <van-field v-model="item.positionName" name="positionName" label="货位:" readonly />
          </van-form>
        </div>
      </van-list>
    </div>
    <van-empty v-if="stockBackList.length === 0" description="暂无待返回出库单" />
  </div>
</template>

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

const router = useRouter();

const stockBackSearch = ref('');

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

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

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

// 搜索返回物料
const searchStockBack = value => {
  page.value = 1;
  total.value = 0;
  stockBackList.value = [];
  loadStockOutBackList();
};

// 返回确认
const stockOutConfirm = item => {
  console.log(item, '返回确认');
  showConfirmDialog({
    title: '确认要返回吗？',
    message: '如果确认要返回，请点击【确认】按钮，否则点击【取消】按钮。',
  })
    .then(() => {
      submitStockBack(item.stockOutId);
    })
    .catch(() => {
      console.log('取消');
    });
};

// 加载返回出库单列表
const loadStockOutBackList = async () => {
  try {
    const res = await getList(page.value, pageSize.value);

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

    total.value = res.total;

    // 检查是否已加载全部数据
    if (stockBackList.value.length >= total.value) {
      finished.value = true;
    } else {
      page.value++; // 只有在成功加载后才增加页码
    }
  } catch (error) {
    finished.value = true;
    if(error.responseText === '未查询出部分出库的出库单') return;
    processException(error);
  } finally {
    loading.value = false;
  }
};

// 获取返回出库单列表API
const getList = (page, pageSize) => {
  const start = (page - 1) * pageSize;
  const length = pageSize;
  const filter = stockBackSearch.value;
  const url = `/api/StockOutResource/queryReturnStockOut?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 submitStockBack = stockOutId => {
  const url = `/api/StockOutResource/generateTask?stockOutId=${stockOutId}`;
  ajaxApiGet(url).then(
    success => {
      if (success.errorCode === 0) {
        searchStockBack(stockBackSearch.value);
        showSuccessToast('返回成功');
      } else {
        showFailToast(success.errorMessage);
      }
    },
    error => {
      processException(error);
    },
  );
};

onMounted(() => {
  loadStockOutBackList();
});

</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: 3px;
}

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