<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"
      :multipleRow="multipleRow"
      @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,
  addBatch,
  addEsopBatch,
  addCheckBatch,
} 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.params.id);

// 传入一个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 multipleRow = ref(true);
const startCreat = () => {
  if (props.tableType === "wuliaocaiji") {
    if (data.value && data.value.length > 0) {
      bomVersion.value = data.value[0].recordVersion;
    }

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

// ============公共弹窗table选择相关，物料采集等使用===============
const commonTableRef = ref({});
const commonTableType = ref("MARTERIAL_BOM");
//批量增加物料采集
const itemRecord = ref({});
const itemRecordList = ref([]);
//批量增加ESOP
const esopItem = ref({});
const esopList = ref([]);
//批量增加点检
const checkItem = ref({});
const checkList = ref([]);
const onSelectedFinish = (itemValue) => {
  if (Object.keys(itemValue).length == 0) {
    return false;
  }
  itemRecordList.value = [];
  itemRecord.value.itemRecordList = [];
  checkList.value = [];
  checkItem.value.checkList = [];
  esopItem.value.esopList = [];
  esopList.value = [];
  if (props.tableType === "wuliaocaiji") {
    itemValue?.forEach((item, index) => {
      const recordItem = ref({});
      recordItem.value.itemName = item.bomMaterialName;
      recordItem.value.itemCode = item.bomMaterialCode;
      recordItem.value.itemModel = item.bomMaterialAttribute;
      recordItem.value.recordVersion = item.bomVersion;
      recordItem.value.num = item.bomMaterialNumber;
      recordItem.value.traceType = "S";
      recordItem.value.operationId = route.params.id;
      recordItem.value.unit = item.unit;
      recordItem.value.isTrace = 1;
      itemRecordList.value.push(recordItem.value);
    });
    itemRecord.value.operationId = route.params.id;
    itemRecord.value.itemRecordList = Array.from(itemRecordList.value);
    addBatch(itemRecord.value).then((data) => {
      if (data.code == "200") {
        dataList();
        ElMessage({
          message: data.msg,
          type: "success",
        });
      } else {
        ElMessage({
          message: data.msg,
          type: "error",
        });
      }
    });
    //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;*/
    itemValue?.forEach((item, index) => {
      const recordItem = ref({});
      recordItem.value.operationId = route.params.id;
      recordItem.value.checkName = item.checkName;
      recordItem.value.checkCode = item.checkCode;
      recordItem.value.content = item.content;
      recordItem.value.standard = item.standard;
      recordItem.value.upper = item.upper;
      recordItem.value.lower = item.lower;
      recordItem.value.unit = item.unit;
      checkList.value.push(recordItem.value);
    });
    checkItem.value.operationId = route.params.id;
    checkItem.value.checkList = Array.from(checkList.value);
    addCheckBatch(checkItem.value).then((data) => {
      if (data.code == "200") {
        dataList();
        commonTableRef.value?.mergeOption({
          reserveSelection: false,
        });
        ElMessage({
          message: data.msg,
          type: "success",
        });
      } else {
        ElMessage({
          message: data.msg,
          type: "error",
        });
      }
    });
  } 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;*/
    itemValue?.forEach((item, index) => {
      const recordItem = ref({});
      recordItem.value.operationId = route.params.id;
      recordItem.value.filePath = item.pdfPath;
      recordItem.value.showAppointPageNum = 1;
      recordItem.value.drawingCode = item.drawingCode;
      recordItem.value.recordVersion = item.drawingVersion;
      recordItem.value.sortNum = item.sort;
      recordItem.value.title = item.drawingTitle;
      esopList.value.push(recordItem.value);
    });
    esopItem.value.operationId = route.params.id;
    esopItem.value.esopList = Array.from(esopList.value);
    addEsopBatch(esopItem.value).then((data) => {
      if (data.code == "200") {
        dataList();
        ElMessage({
          message: data.msg,
          type: "success",
        });
      } else {
        ElMessage({
          message: data.msg,
          type: "error",
        });
      }
    });
  }
};

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(() => {
  search.value.operationId = route.params.id;
  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.query.routeId).then(({ data }) => {
    if (data) {
      bomVersion.value = data;
    }
  });
});

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