<template>
  <van-nav-bar
    :title="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 name="inventoryPackaged" label="是否包装">
        <template #input>
          <van-switch v-model="formData.inventoryPackaged" size="20px" />
        </template>
      </van-field>
      <van-field
        v-model="formData.carrierTypeName" name="carrierTypeName" label="托盘类型:" placeholder="点击选择托盘类型" is-link
        @click="showCarrierTypePicker = true"
      />
      <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
    ref="transferPositionSelector" v-model:show="isShowTransfer" position-type="transfer"
    :default-selected-id="formData.transferId" @confirm="onTransferPositionSelected"
  />
  <position-selector
    ref="idlePositionSelector" v-model:show="isShowIdle" position-type="idle" :is-default="true"
    type="stockIn" :dialog-show="isShowStockIn" :default-selected-id="formData.idleId"
    @confirm="onIdlePositionSelected"
  />

  <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 } 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 { showFailToast, showSuccessToast, showConfirmDialog } from 'vant';

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

const stockInSearch = ref('');
const transferPositionSelector = ref(null);
const idlePositionSelector = ref(null);

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: '',
  inventoryPackaged: false,
  carrierType: '',
  carrierTypeName: '',
});

const isShowStockIn = ref(false);
const isShowTransfer = ref(false);
const isShowIdle = ref(false);
const warehouseId = ref(null);
const warehouseName = ref(null);
const title = ref('');

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

const goBack = () => {
  router.push('/warehouse-selector?page=stock-in&warehouseId=' + warehouseId.value);
};

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

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

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

// 入库
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;
  }
  if (!formData.value.carrierType) {
    showFailToast('请选择托盘类型');
    return;
  }
  showConfirmDialog({
    title: '确认要入库吗？',
    message: '如果确认要入库，请点击【确认】按钮，否则点击【取消】按钮。',
  })
    .then(() => {
      submitStockIn();
    })
    .catch(() => {
      console.log('取消');
    });
};

// 加载入库物料列表
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) {
    finished.value = true;
    processException(error);
  } finally {
    loading.value = false;
  }
};

// 获取入库物料列表API
const getList = (page, pageSize) => {
  const start = (page - 1) * pageSize;
  const length = pageSize;
  const filter = stockInSearch.value;
  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);
      },
    );
  });
};

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);
    },
  );
};

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


// 取消入库
const cancelStockIn = () => {
  clearFormData();
};

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


// 拍照
const goTakePhoto = () => {
  router.push('/stock-in-scan?warehouseId=' + warehouseId.value + '&warehouseName=' + warehouseName.value);
};
onMounted(() => {
  warehouseId.value = route.query.warehouseId || '';
  warehouseName.value = route.query.warehouseName || '';
  title.value = route.query.warehouseName ? '入库 - ' + route.query.warehouseName : '入库';
  loadStockInList();
  getCarrierTypeList();
});

</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>
