<template>
  <van-nav-bar :title="$t('inventoryQuery.name')" left-text="" left-arrow @click-left="onClickLeft">
  </van-nav-bar>
  <van-search v-model="req.keyword" :placeholder="$t('common.pleaseEnterKeywords')" @search="onRefresh" />
  <van-tabs v-model:active="active" @change="handleChangeTab">
    <van-tab :title="'按仓库'" name="first"></van-tab>
    <van-tab :title="'按产品'" name="second"></van-tab>
    <van-tab :title="'按SPU'" name="three"></van-tab>
  </van-tabs>
  <div style="overflow-y:auto" :style="{height:!deviceStore.isIosSysteme?'calc(100vh - 205px)':'calc(100vh - 225px)'}">
    <van-pull-refresh v-model="loading" @refresh="onRefresh">
      <div class="list">
        <van-list v-model:loading="loading" :finished="finished" :finished-text="$t('common.noMore')" @load="onLoad" style="margin-bottom: 60px">
          <commonList :data="listData" :config="listConfig" :showMore="false">
            <template #productUnit="{row}">
              <div style="width:100%">
                {{dictValueLabel(row.productUnit,productUnit)}}
              </div>
            </template>
            <template #btn="{row}">
              <div style="width:100%;text-align:right">
                <van-button type="primary" size="small" style="margin-right:10px" @click="toDtl(row,true)">良转次</van-button>
                <van-button type="primary" size="small" @click="toDtl(row,false)">次转良</van-button>
              </div>
            </template>
          </commonList>
          <!-- @onClick="toDtl" -->
        </van-list>
      </div>
    </van-pull-refresh>
  </div>

  <van-popup v-model:show="openPopup" position="bottom" :style="{ height: '370px' }" closeable>
    <div style="padding:10px">
      <van-form @submit="onSubmit" label-align="top">
        <TitleInfo :title="submitType?'良转次':'次转良'"></TitleInfo>
        <van-field v-model="formData.data.canSum" type="text" label="可转数量" readonly />
        <van-field v-model="formData.data.quantity" type="digit" label="数量" placeholder="请输入数量" :rules="[{ required: true, message: '请填写数量' }]" />
        <div style="margin: 16px">
          <van-button round block type="primary" native-type="submit">
            提交
          </van-button>
        </div>
      </van-form>

    </div>
  </van-popup>
</template>
<script setup>
import { ref, getCurrentInstance, onMounted, reactive } from "vue";
import commonList from "@/components/common-list.vue";
import { useRoute } from "vue-router";
import { getUserInfo } from "@/utils/auth";
import { showSuccessToast, showFailToast } from "vant";
import TitleInfo from "@/components/TitleInfo/index.vue";
import useDeviceStore from "@/store/device";
const deviceStore = useDeviceStore();
const loading = ref(false);
const router = useRoute();
const req = ref({
  pageNum: 1,
  keyword: null,
});
const finished = ref(false);
const proxy = getCurrentInstance().proxy;
const listData = ref([]);
const warehouseData = ref([]);
const productUnit = ref([]);
const active = ref("first");
let listConfigSet = [
  [
    {
      label: "仓库名称",
      prop: "warehouseName",
    },
    {
      label: "项目组",
      prop: "deptName",
    },
    {
      label: "所属分类",
      prop: "productClassifyName",
    },
    {
      label: "物品编码",
      prop: "productCustomCode",
    },
    {
      label: "物品名称",
      prop: "productName",
    },
    {
      label: "规格",
      prop: "productSpec",
    },
    {
      type: "slot",
      slotName: "productUnit",
      label: "单位",
      prop: "productUnit",
    },
    {
      label: "可用库存",
      prop: "quantity",
    },
    {
      label: "冻结库存",
      prop: "frozenQuantity",
    },
    {
      label: "次品库存",
      prop: "defectiveQuantity",
    },
    {
      label: "最近入库时间",
      prop: "updateTime",
    },
    {
      type: "slot",
      slotName: "btn",
      label: "",
    },
  ],
  [
    {
      label: "项目组",
      prop: "deptName",
    },
    {
      label: "所属分类",
      prop: "productClassifyName",
    },
    {
      label: "物品编码",
      prop: "productCustomCode",
    },
    {
      label: "物品名称",
      prop: "productName",
    },
    {
      label: "规格",
      prop: "productSpec",
    },
    {
      type: "slot",
      slotName: "productUnit",
      label: "单位",
      prop: "productUnit",
    },
    {
      label: "可用库存",
      prop: "quantity",
    },
    {
      label: "冻结库存",
      prop: "frozenQuantity",
    },
    {
      label: "次品库存",
      prop: "defectiveQuantity",
    },
    {
      label: "最近入库时间",
      prop: "updateTime",
    },
    {
      type: "slot",
      slotName: "btn",
      label: "",
    },
  ],
  [
    {
      label: "spu编码",
      prop: "productSpuCode",
    },
    {
      label: "spu名称",
      prop: "productSpuName",
    },
    {
      label: "关联产品数",
      prop: "linkProductQuantity",
    },
    {
      label: "库存数量",
      prop: "quantity",
    },
  ],
];
const listConfig = ref([]);
listConfig.value = listConfigSet[0];
const onRefresh = () => {
  req.value.pageNum = 1;
  finished.value = false;
  getList("refresh");
};
const onLoad = () => {
  getList();
};

const onClickLeft = () => proxy.$router.push("/main/working");

const onClickRight = () => {
  proxy.$router.push("/main/manualInboundAdd");
};
const formData = reactive({
  data: {},
});
const openPopup = ref(false);
const submitType = ref(false);
const toDtl = (row, flag) => {
  submitType.value = flag;
  // proxy.$router.push({
  //   path: "outInList",
  //   query: {
  //     productId: row.productId,
  //     warehouseId: row.warehouseId,
  //   },
  // });
  let canSum = flag ? row.quantity : row.defectiveQuantity;
  formData.data = {
    id: row.id,
    canSum,
    quantity: null,
  };
  openPopup.value = true;
};

const onSubmit = () => {
  let url = submitType.value
    ? "/stock/qualifiedToDefective"
    : "/stock/defectiveToQualified";
  if (!(Number(formData.data.quantity) > 0)) {
    return showFailToast("数量不能为0");
  }
  if (Number(formData.data.quantity) > Number(formData.data.canSum)) {
    return showFailToast("数量不可大于可转数量");
  }
  proxy.post(url, formData.data).then(
    (res) => {
      onRefresh();
      showSuccessToast("操作成功");
      openPopup.value = false;
    },
    (err) => {
      return showFailToast(err.message);
    }
  );
};
const getDict = () => {
  let query = {
    pageNum: 1,
    pageSize: 999,
    tenantId: getUserInfo().tenantId,
  };
  // proxy
  //   .post("/supplierInfo/page", { pageNum: 1, pageSize: 9999 })
  //   .then((res) => {
  //     supplierData.value = res.data.rows;
  //     formConfig[5].data = supplierData.value;
  //   });
  proxy
    .post("/dictTenantData/page", {
      ...query,
      dictCode: "unit",
    })
    .then((res) => {
      if (res.data.rows && res.data.rows.length > 0) {
        productUnit.value = res.data.rows.map((item) => {
          return {
            label: item.dictValue,
            value: item.dictKey,
          };
        });
      }
    });
};
getDict();
const getList = (type) => {
  loading.value = true;
  proxy
    .post(requestUrl.value, req.value)
    .then((res) => {
      res.data.rows = res.data.rows.map((x) => ({
        ...x,
        ...JSON.parse(x.victoriatouristJson),
        quantity: x.quantity,
      }));
      listData.value =
        type === "refresh"
          ? res.data.rows
          : listData.value.concat(res.data.rows);
      if (req.value.pageNum * 10 >= res.data.total) {
        finished.value = true;
      }
      req.value.pageNum++;
      loading.value = false;
    })
    .catch((err) => {
      loading.value = false;
    });
};

const requestUrl = ref("/stock/pageByWarehouse");
const handleChangeTab = (val) => {
  if (val == "first") {
    requestUrl.value = "/stock/pageByWarehouse";
    listConfig.value = listConfigSet[0];
  } else if (val == "second") {
    requestUrl.value = "/stock/pageByProduct";
    listConfig.value = listConfigSet[1];
  } else {
    requestUrl.value = "/stock/pageByProductSpu";
    listConfig.value = listConfigSet[2];
  }
  req.value.pageNum = 1;
  listData.value = [];
  getList();
};

getList();
</script>

<style lang="scss" scoped>
.list {
  min-height: 100%;
}
</style>