<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="true"
      @selected-sure="onSelectedFinish"
    />
    <el-dialog v-model="dialogVisible">
      <VuePdfEmbed :source="previewImgUrl" annotation-layer text-layer />
    </el-dialog>

    <el-dialog v-model="versionDV" title="请先选择版本号" width="500" center>
      <el-select
        v-model="selectedVersion"
        placeholder="请先选择版本号"
        style="margin-bottom: 20px"
      >
        <el-option
          v-for="item in versionList"
          :key="item.id"
          :label="item.bomVersion"
          :value="item.bomVersion"
        />
      </el-select>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="versionDV = false">取消</el-button>
          <el-button type="primary" @click="goToSelectMaterial">
            确定
          </el-button>
        </div>
      </template>
    </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,
  addFuliao,
} 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]);
const afterDataListToGetBomVersion = () => {
  toGetBomVersion();
};
// 传入一个url，后面不带/
const { url, form, data, option, search, page, toDeleteIds, Methords, Utils } =
  useCrud({
    src: tableConfig[props.tableType].url,
    afterDataList: afterDataListToGetBomVersion,
  });

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;
        }
      );
    }

    // if (!route.fullPath.split("/")[5]) {
    //   ElMessage.error("物料编号读取错误");
    //   return;
    // }
    // //根据物料编码和版本号获取对应的物料BOM
    // let bomParam = {
    //   materialCode: route.fullPath.split("/")[5],
    // };
    // getBomVersion(bomParam).then((res) => {
    //   versionList.value = res?.data ?? [];
    //   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: true,
    //       selection: true,
    //       reserveSelection: 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 itemRecord = ref({});
const itemRecordList = ref([]);
//批量增加ESOP
const esopItem = ref({});
const esopList = ref([]);
//批量增加点检
const checkItem = ref({});
const checkList = ref([]);
const onSelectedFinish = (itemValue) => {
  console.log(itemValue);
  if (Object.keys(itemValue).length == 0) {
    ElMessage.error("请选择数据,数据不能为空!");
  }
  //crudRef.value && crudRef.value.rowAdd();
  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.spec;
      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",
        });
      }
    });
  } else if (props.tableType === "dianjian") {
    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") {
    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",
        });
      }
    });
  } else if (props.tableType === "fuliaoCJ") {
    itemValue?.forEach((item, index) => {
      const recordItem = ref({});
      recordItem.value.itemName = item.materialName;
      recordItem.value.itemCode = item.materialCode;
      recordItem.value.itemModel = item.spec;
      recordItem.value.recordVersion = item.bomVersion;
      recordItem.value.num = item.materialNumber;
      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.itemList = Array.from(itemRecordList.value);
    addFuliao(itemRecord.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(() => {
  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, {
    searchEnter: true,
    addBtn: false,
    searchShow: false,
    header: false,
    sortable: true,
    column: tableConfig[props.tableType].column,
  });
  dataList();
  toGetBomVersion();
});

watch(
  () => props.tableType,
  () => {
    routeId.value = route.fullPath.split("/")[6];
    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();
    toGetBomVersion();
  }
);

const toGetBomVersion = () => {
  getRouteMaxVersion(
    route.fullPath.split("/")[6] ? route.fullPath.split("/")[6] : routeId.value
  ).then(({ data }) => {
    bomVersion.value = data;
  });
};
</script>
