<template>
  <van-nav-bar
    :title="$t('forward.name')"
    left-text=""
    left-arrow
    @click-left="onClickLeft"
    @click-right="onClickRight"
  >
    <template #right>
      <div v-show="!isShowVideo">扫码</div>
      <div v-show="isShowVideo">关闭</div>
    </template>
  </van-nav-bar>
  <van-search
    v-model="req.keyword"
    :placeholder="$t('common.pleaseEnterKeywords')"
    @search="onRefresh"
  />

  <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="true"
          @onClick="toDtl"
        ></commonList>
      </van-list>
    </div>
  </van-pull-refresh>

  <video
    ref="video"
    id="video"
    class="scan-video"
    autoplay
    v-show="isShowVideo"
  ></video>
</template>
<script setup>
import { ref, getCurrentInstance, onMounted } from "vue";
import commonList from "@/components/common-list.vue";
import { useRoute } from "vue-router";
import { showSuccessToast, showFailToast } from "vant";
import { BrowserMultiFormatReader } from "@zxing/library";

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 listConfig = ref([
  {
    label: proxy.t("forward.productName"),
    prop: "productName",
  },
  {
    label: "规格型号",
    prop: "productSpec",
  },
  {
    label: proxy.t("forward.productSN"),
    prop: "productSn",
  },
  {
    label: proxy.t("forward.currentProcess"),
    prop: "productionProcessesName",
  },
]);
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("jxskForwardAdd");
// };

const toDtl = (row) => {
  let type = "";
  if (
    row.nextProductionProcessesId == "" ||
    row.nextProductionProcessesId == "-1"
  ) {
    type = "20";
  } else {
    type = "10";
  }
  proxy.$router.push({
    path: "jxskForwardAdd",
    query: {
      ...row,
      type: type,
    },
  });
};

const getList = (type) => {
  loading.value = true;
  proxy
    .post("/productionTaskDetail/circulationPage", req.value)
    .then((res) => {
      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;
    });
};

getList();
const isShowVideo = ref(false);
const codeReader = new BrowserMultiFormatReader();
const onClickRight = () => {
  if (isShowVideo.value) {
    codeReader.reset();
    isShowVideo.value = false;
  } else {
    handleScanCode();
  }
};
const showScanData = (text) => {
  console.log(text, "aweaw");
};
const decodeFromInputVideoFunc = (firstDeviceId) => {
  codeReader.reset(); // 重置
  isShowVideo.value = true;
  codeReader.decodeFromInputVideoDeviceContinuously(
    firstDeviceId,
    "video",
    (result, err) => {
      if (result) {
        codeReader.reset();
        showSuccessToast(proxy.t("manualInbound.scanSuccess"));
        isShowVideo.value = false;
        showScanData(result.text);
      }
      if (err && !err) {
        console.error(err);
        isShowVideo.value = false;
      }
    }
  );
};

const handleScanCode = () => {
  codeReader
    .getVideoInputDevices()
    .then((videoInputDevices) => {
      // 默认获取第一个摄像头设备id
      let firstDeviceId = videoInputDevices[0].deviceId;
      // 获取第一个摄像头设备的名称
      const videoInputDeviceslablestr = JSON.stringify(
        videoInputDevices[0].label
      );
      if (videoInputDevices.length > 1) {
        // 判断是否后置摄像头
        if (videoInputDeviceslablestr.indexOf("back") > -1) {
          firstDeviceId = videoInputDevices[0].deviceId;
        } else {
          firstDeviceId = videoInputDevices[1].deviceId;
        }
      }
      decodeFromInputVideoFunc(firstDeviceId);
    })
    .catch((err) => {
      console.error(err, "错误");
    });
};
</script>

<style lang="scss" scoped>
.list {
  min-height: 70vh;
}
.scan-video {
  width: 100vw;
  position: absolute;
  z-index: 1000;
  top: 60px;
}
</style>