<template>
  <div>
    <avue-crud
      ref="crudRef"
      v-model:search="search"
      v-model="form"
      :data="data"
      :option="option"
      v-model:page="page"
      @row-save="createRow"
      @row-update="updateRow"
      @row-del="deleteRow"
      @selection-change="selectionChange"
      @sortable-change="onSortChange"
      @search-change="searchChange"
      @search-reset="resetChange"
      @size-change="dataList"
      @current-change="dataList"
    >
      <template #filePath-form="scope">
        <!-- <single-upload v-model="form.filePath" />
        <FilesUpload v-model:src="form.filePath" v-model:src-list="form.filePath" /> -->
        <div style="height: 100px; width: 100px; overflow: hidden">
          <PDFView
            :need-to-show-pdf="true"
            content-type="button"
            :is-link="true"
            :show-pdf-number="form.showAppointPageNum"
            :pdf-source="pdfPath"
          />
        </div>
      </template>
      <template #filePath="{ row }">
        <PDFView
          :need-to-show-pdf="true"
          content-type="button"
          btnText="查看PDF"
          :is-link="true"
          :pdf-source="getSOAPpdf(row)"
        />
      </template>
    </avue-crud>
    <CommonTable
      ref="commonTableRef"
      :tableTitle="tableTitle"
      :tableType="commonTableType"
      @selected-sure="onSelectedFinish"
    />
    <el-dialog v-model="dialogVisible">
      <VuePdfEmbed :source="previewImgUrl" annotation-layer text-layer />
    </el-dialog>
  </div>
</template>
<script setup>
import { ref, getCurrentInstance } from "vue";
import { useCrud } from "@/hooks/userCrud";
import { getTableConfig } from "./configs";
import PDFView from "@/components/PDFView/index.vue";
import VuePdfEmbed from "vue-pdf-embed";
import {
  saveCompoents,
  getBomVersion,
  getRouteMaxVersion,
} from "@/api/craft/process/index";
import SingleUpload from "@/components/Upload/SingleUpload.vue";

const props = defineProps({
  tableTitle: {
    default: "",
    type: String,
  },
  tableType: {
    default: "",
    type: String,
  },
});

const route = useRoute();
const tableConfig = getTableConfig(route.fullPath.split("/")[4]);

// 传入一个url，后面不带/
const { url, form, data, option, search, page, toDeleteIds, Methords, Utils } =
  useCrud({
    src: tableConfig[props.tableType].url,
  });

const { dataList, createRow, updateRow, deleteRow, searchChange, resetChange } =
  Methords; //增删改查
const { selectionChange, multipleUpdate } = Methords; //选中和批量删除事件

const crudRef = ref(null); //crudRef.value 获取avue-crud对象
const bomVersion = ref(null);
const pdfPath = ref(null);
const startCreat = () => {
  if (props.tableType === "wuliaocaiji") {
    if (data.value && data.value.length > 0) {
      bomVersion.value = data.value[0].recordVersion;
    }

    if (!route.fullPath.split("/")[5]) {
      ElMessage.error("物料编号读取错误");
      return;
    }
    //根据物料编码和版本号获取对应的物料BOM
    let bomParam = {
      materialCode: route.fullPath.split("/")[5],
    };
    getBomVersion(bomParam).then((res) => {
      let resListMap = [];
      //说明时物料采集的添加框 进行物料采集的下拉框数据获取
      res?.data.forEach((versions) => {
        resListMap.push({
          label: versions.bomVersion,
          value: versions.bomVersion,
        });
      });
      //查询参数
      let configParam = {};
      configParam.materialCode = route.fullPath.split("/")[5];
      if (bomVersion.value) {
        configParam.bomVersion = bomVersion.value;
      }
      //根据物料编码和版本号获取对应的物料BOM
      commonTableType.value = "MARTERIAL_BOM";
      nextTick(() => {
        commonTableRef.value?.startSelect(configParam);
        commonTableRef.value?.refreshDictData(
          "bomVersion",
          resListMap,
          "value"
        );
        commonTableRef.value?.mergeOption({
          searchShow: bomVersion.value ? false : true,
        });
      });
    });
  } else if (props.tableType === "dianjian") {
    commonTableType.value = "OP_CHECK";
    nextTick(() => {
      commonTableRef.value?.startSelect();
    });
  } else if (props.tableType === "ESOP") {
    commonTableType.value = "ESOP";
    nextTick(() => {
      commonTableRef.value?.startSelect({
        materialCode: route.fullPath.split("/")[5],
        enable: 1,
      });
    });
  } else {
    crudRef.value && crudRef.value.rowAdd();
  }
};

const saveSortData = async () => {
  multipleUpdate();
};

defineExpose({ startCreat, saveSortData });

const onSortChange = () => {
  data.value.forEach((item) => {
    console.log(item.id);
  });
};
const routeId = ref("");
// ============公共弹窗table选择相关，物料采集等使用===============
const commonTableRef = ref({});
const commonTableType = ref("MARTERIAL_BOM");
const onSelectedFinish = (itemValue) => {
  crudRef.value && crudRef.value.rowAdd();
  if (props.tableType === "wuliaocaiji") {
    form.value.itemName = itemValue.bomMaterialName;
    form.value.itemCode = itemValue.bomMaterialCode;
    form.value.itemModel = itemValue.bomMaterialAttribute;
    form.value.recordVersion = itemValue.bomVersion;
    form.value.num = itemValue.bomMaterialNumber;
    form.value.traceType = "S";
    form.value.unit = itemValue.unit;
  } else if (props.tableType === "dianjian") {
    form.value.checkName = itemValue.checkName;
    form.value.checkCode = itemValue.checkCode;
    form.value.content = itemValue.content;
    form.value.standard = itemValue.standard;
    form.value.upper = itemValue.upper;
    form.value.lower = itemValue.lower;
    form.value.unit = itemValue.unit;
  } else if (props.tableType === "ESOP") {
    form.value.filePath = itemValue.pdfPath;
    pdfPath.value = import.meta.env.VITE_APP_UPLOAD_URL + itemValue.pdfPath;
    form.value.drawingCode = itemValue.drawingCode;
    form.value.recordVersion = itemValue.drawingVersion;
    form.value.sortNum = itemValue.sort;
    form.value.title = itemValue.drawingTitle;
  }
};

const previewImgUrl = ref("");
const dialogVisible = ref(false);
const imgUrlClick = (itemValue) => {
  previewImgUrl.value =
    import.meta.env.VITE_APP_UPLOAD_URL + itemValue.filePath;
  dialogVisible.value = true;
};
const getSOAPpdf = (itemValue) => {
  return import.meta.env.VITE_APP_UPLOAD_URL + itemValue.filePath;
};

onMounted(() => {
  routeId.value = route.fullPath.split("/")[6];
  search.value.operationId = route.fullPath.split("/")[4];
  url.value = tableConfig[props.tableType].url;
  option.value = Object.assign(option.value, {
    addBtn: false,
    searchShow: false,
    header: false,
    sortable: true,
    column: tableConfig[props.tableType].column,
  });
  dataList();
  getRouteMaxVersion(
    route.fullPath.split("/")[6] ? route.fullPath.split("/")[6] : routeId.value
  ).then(({ data }) => {
    if (data) {
      bomVersion.value = data;
    }
  });
});

watch(
  () => props.tableType,
  () => {
    routeId.value = route.fullPath.split("/")[6];
    url.value = tableConfig[props.tableType].url;
    option.value = Object.assign(option.value, {
      addBtn: false,
      searchShow: false,
      header: false,
      sortable: true,
      column: tableConfig[props.tableType].column,
    });
    dataList();
    getRouteMaxVersion(
      route.fullPath.split("/")[6]
        ? route.fullPath.split("/")[6]
        : routeId.value
    ).then(({ data }) => {
      if (data) {
        bomVersion.value = data;
      }
    });
  }
);
</script>
