<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">
        <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"-->
          <!--          />-->
          <el-button link type="primary" @click="toShowPDF(pdfPath,form.showAppointPageNum)">
            预览
          </el-button>
        </div>
      </template>
      <template #filePath="{ row }">
        <!--        <PDFView-->
        <!--          :need-to-show-pdf="true"-->
        <!--          content-type="button"-->
        <!--          btnText="查看PDF"-->
        <!--          :is-link="true"-->
        <!--          :pdf-source="getSOAPpdf(row)"-->
        <!--        />-->
        <el-button link type="primary" @click="toShowPDF(row.filePath,1)">
          查看PDF
        </el-button>
      </template>
    </avue-crud>
    <el-dialog v-model="dialogVisible">
      <VuePdfEmbed :source="previewImgUrl" annotation-layer text-layer/>
    </el-dialog>
    <PDFDrawerView ref="PDFDrawerViewRef"></PDFDrawerView>
  </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 {
  getBomVersion,
} from "@/api/craft/process/index";

const props = defineProps({
  tableTitle: {
    default: "",
    type: String,
  },
  tableType: {
    default: "",
    type: String,
  },
  groupId: {
    default: "",
    type: String,
  },
  isTree: {
    default: "0",
    type: String,
  },
  operationId: {
    default: "0",
    type: String,
  },
  routeId: {
    default: "0",
    type: String,
  },
});
const PDFDrawerViewRef = ref(null);
const toShowPDF = (pdfPath, pdfNum) => {
  let url = import.meta.env.VITE_APP_UPLOAD_URL + pdfPath;
  PDFDrawerViewRef.value && PDFDrawerViewRef.value.showPdf(url, pdfNum);
};
const route = useRoute();
const tableConfig = getTableConfig(props.operationId);
// 传入一个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 versionList = ref([]);
const versionDV = ref(false);
const selectedVersion = ref("");
const goToSelectMaterial = () => {
  if (!route.fullPath.split("/")[5]) {
    ElMessage.error("物料编号读取错误");
    return;
  }
  let configParam = {};
  configParam.materialCode = route.fullPath.split("/")[5];
  configParam.bomVersion = selectedVersion.value;
  //根据物料编码和版本号获取对应的物料BOM
  commonTableType.value = "MARTERIAL_BOM";
  nextTick(() => {
    commonTableRef.value?.startSelect(configParam);
    commonTableRef.value?.refreshDictData("bomVersion", [], "value");
    commonTableRef.value?.mergeOption({
      searchShow: true,
      selection: true,
      reserveSelection: true,
    });
  });
  selectedVersion.value = "";
  versionDV.value = false;
};
const startCreat = () => {
  if (props.tableType === "wuliaocaiji") {
    if (bomVersion.value) {
      selectedVersion.value = bomVersion.value;
      goToSelectMaterial();
    } else {
      getBomVersion({materialCode: route.fullPath.split("/")[5]}).then(
        (res) => {
          versionList.value = res?.data ?? [];
          versionDV.value = true;
        }
      );
    }

  } else if (props.tableType === "dianjian") {
    commonTableType.value = "OP_CHECK";
    nextTick(() => {
      commonTableRef.value?.startSelect({
        operationId: route.params.id
      });
      commonTableRef.value?.mergeOption({
        selection: true,
        reserveSelection: true,
        header: false,
        selectable: function (row, index) {
          return row.isSelect;

        },
      });
    });
  } else if (props.tableType === "ESOP") {
    commonTableType.value = "ESOP";
    nextTick(() => {
      commonTableRef.value?.startSelect({
        materialCode: route.fullPath.split("/")[5],
        enable: 1,
      });
      commonTableRef.value?.mergeOption({
        selection: true,
        reserveSelection: true,
      });
    });
  } else if (props.tableType === "fuliaoCJ") {
    commonTableType.value = "FULIAO_CAIJI";

    nextTick(() => {
      commonTableRef.value?.startSelect({
        accessoriesProperty: "2", //默认直接查所有的部件辅料)
      });
      commonTableRef.value?.mergeOption({
        selection: true,
        reserveSelection: true,
      });
    });
  } 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 itemGroup = ref(null);
const previewImgUrl = ref("");
const dialogVisible = ref(false);
const getSOAPpdf = (itemValue) => {
  return import.meta.env.VITE_APP_UPLOAD_URL + itemValue.filePath;
};

onMounted(() => {
  routeId.value = props.routeId
  search.value.operationId = props.operationId + ""
  url.value = tableConfig[props.tableType].url;
  search.value.isTree = props.isTree;
  if (props.groupId) {
    search.value.itemGroupId = props.groupId;
    itemGroup.value=props.groupId;
  }
  //物料双规格分组的话没有编辑，删除要自定义
  if (props.isTree === '1') {
    option.value = Object.assign(option.value, {
      searchEnter: true,
      addBtn: false,
      editBtn: false,
      delBtn: false,
      searchShow: false,
      header: false,
      sortable: true,
      column: tableConfig[props.tableType].column,
    });
  } else {
    option.value = Object.assign(option.value, {
      searchEnter: true,
      addBtn: false,
      editBtn: false,
      delBtn: false,
      searchShow: false,
      header: false,
      column: tableConfig[props.tableType].column,
    });
  }
  dataList();
});

watch(
  () => props.tableType,
  () => {
    routeId.value = props.routeId
    url.value = tableConfig[props.tableType].url;
    option.value = Object.assign(option.value, {
      searchEnter: true,
      addBtn: false,
      searchShow: false,
      header: false,
      sortable: true,
      column: tableConfig[props.tableType].column,
    });
    dataList();
  }
);

/**监听分组是否变化*/
watch(
  () => props.groupId,
  () => {
    routeId.value = props.routeId
    url.value = tableConfig[props.tableType].url;
    option.value = Object.assign(option.value, {
      searchEnter: true,
      addBtn: false,
      searchShow: false,
      header: false,
      sortable: true,
      column: tableConfig[props.tableType].column,
    });
    search.value.itemGroupId = props.groupId
    itemGroup.value = props.groupId
    console.log("aaaa",itemGroup.value);
    dataList();
  }
);
watch(
    () => props.operationId,
    () => {

    }
);
watch(
    () => props.routeId,
    () => {

    }
);
</script>
