<template>
  <div class="page-container column-container">
    <section class="list-part-container">
      <!-- 搜索区域 -->
      <el-form class="list-search-container" :inline="true">
        <el-form-item label="客户：">
          {{ currentProduct.companyAlias }}
        </el-form-item>
        <el-form-item label="图号：">
          {{ currentProduct.drawingNumber }}
        </el-form-item>
        <el-form-item label="规格：">
          {{ currentProduct.specification }}
        </el-form-item>
        <el-form-item label="产品描述：">
          {{ currentProduct.description }}
        </el-form-item>
        <el-form-item> </el-form-item>
        <el-form-item class="section-title" label="工艺版本：">
          <el-select-v2
            v-model="currentTechnological.productVersion"
            disabled="true"
            :options="technologicalProcessList"
            placeholder="请选择版本"
            @change="handelTechnological"
            style="width: 70px"
          />
        </el-form-item>
        <el-form-item class="section-title" label="当前工序：">
          <el-select-v2
            v-model="technologicalDetailId"
            clearable
            :options="technologicalProcessDetailsList"
            placeholder="请选择工序"
            style="width: 160px"
            @change="handleDetailsChange"
          />
        </el-form-item>
      </el-form>
    </section>
    <div class="page-container row-container">
      <section class="list-part-container column-container" style="flex: 4">
        <div class="list-btns-container">
          <el-button
            type="primary"
            icon="Plus"
            v-hasPermi="['business:electronicDrawings:add']"
            @click="handelUpload()"
            >上传
          </el-button>
        </div>
        <!-- <div class="page-container form-container"> -->
        <!-- 列表区 -->
        <div class="el-table-container">
          <div class="el-table-inner-container">
            <el-table
              ref="drawingTable"
              v-loading="loading"
              row-key="id"
              highlight-current-row
              @current-change="handleSelectionChange"
              :data="drawingList"
              height="100%"
            >
              <!-- <el-table-column type="selection" width="40" align="center" /> -->
              <el-table-column
                type="index"
                label="行号"
                width="50"
                align="center"
              />

              <el-table-column label="图纸" prop="drawingName" align="center" />
              <el-table-column
                label="类型"
                prop="pattern"
                align="center"
                width="80"
              />
              <el-table-column
                label="状态"
                width="80px"
                prop="recordsType"
                align="center"
              >
                <template #default="scope">
                  <dict-tag
                    :options="drawing_status"
                    :value="scope.row.recordsType"
                  />
                </template>
              </el-table-column>
              <!-- <el-table-column label="是否废弃" width="80px" prop="abandoned" align="center">
                                <template #default="scope">
                                    <dict-tag :options="drawing_type" :value="scope.row.abandoned" />
                                </template>
                            </el-table-column> -->
              <el-table-column
                label="制作人"
                width="100px"
                prop="producer"
                align="center"
              />
              <el-table-column
                label="审核人"
                width="100px"
                prop="reviewer"
                align="center"
              />
              <el-table-column
                label="批准人"
                width="100px"
                prop="issuer"
                align="center"
              />
              <el-table-column fixed="right" label="操作" align="center">
                <template #default="scope">
                  <el-button-group
                    style="
                      display: flex;
                      align-items: center;
                      justify-content: center;
                      flex-wrap: nowrap;
                    "
                  >
                    <el-button
                      v-if="
                        scope.row.status == 0 &&
                        scope.row.abandoned == 0 &&
                        scope.row.producerId != 0
                      "
                      link
                      type="primary"
                      v-hasPermi="['business:electronicDrawings:examine']"
                      @click="handlePreview(scope.row)"
                      >审核
                    </el-button>
                    <el-button
                      v-if="scope.row.status == 1"
                      link
                      type="success"
                      plain
                      v-hasPermi="['business:electronicDrawings:raift']"
                      @click="handlePreview(scope.row)"
                      >批准</el-button
                    >

                    <!-- <el-upload style="display: flex;align-items: center; justify-content: center;"
                                            :action="webHost + '/common/upload'" :headers="headers" :limit="1"
                                            :on-success="handleReplaceSuccess" :on-exceed="handleReplaceExceed"
                                            :before-upload="beforeUpload" :show-file-list="false">
                                            <el-button v-if="scope.row.status == 2 && scope.row.abandoned == 0" link
                                                type="warning" plain
                                                v-hasPermi="['business:electronicDrawings:replace']">替换</el-button>
                                        </el-upload> -->

                    <el-button
                      v-show="scope.row.status == 2 && scope.row.abandoned == 0"
                      link
                      type="warning"
                      v-hasPermi="['business:electronicDrawings:replace']"
                      @click="replaceClick(scope.row)"
                      >替换
                    </el-button>

                    <el-button
                      v-show="
                        scope.row.status == 0 &&
                        scope.row.abandoned == 0 &&
                        scope.row.producerId != 0
                      "
                      link
                      type="danger"
                      v-hasPermi="['business:electronicDrawings:examineNG']"
                      @click="handleDrawingNG(scope.row)"
                      >NG
                    </el-button>
                    <el-button
                      v-show="scope.row.status == 1"
                      link
                      type="danger"
                      v-hasPermi="['business:electronicDrawings:raiftNG']"
                      @click="handleDrawingNG(scope.row)"
                      >NG
                    </el-button>
                    <el-button
                      v-show="scope.row.status == 2 && scope.row.abandoned == 0"
                      link
                      type="danger"
                      v-hasPermi="['business:electronicDrawings:remove']"
                      @click="handleDrawingRemove(scope.row)"
                      >作废
                    </el-button>
                  </el-button-group>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
        <!-- 分页 -->
        <pagination
          v-show="total > 0"
          :total="total"
          v-model:page="queryparams.pageNum"
          v-model:limit="queryparams.pageSize"
          @pagination="getDrawing"
        />
        <!-- </div> -->
      </section>

      <section class="list-part-container" style="flex: 3">
        <el-form
          class="list-search-container"
          :model="draform"
          ref="queryRef"
          :inline="true"
          style="margin-right: 0px"
        >
          <el-form-item class="section-title" label="预览" />
          <el-form-item style="float: inline-end; margin-top: 8px">
            <el-button
              :disabled="!drawingUrl"
              link
              type="primary"
              @click="openDrawing"
              >全屏预览</el-button
            >
          </el-form-item>
        </el-form>
        <iframe
          :src="drawingUrl"
          frameborder="no"
          style="width: 100%; height: 100%"
          scrolling="auto"
        />
      </section>
    </div>
    <!-- 添加图纸对话框 -->
    <el-dialog
      title="上传文件"
      v-model="open"
      width="500px"
      @close="cancel"
      append-to-body
    >
      <el-form
        ref="drawingRef"
        :model="form"
        :rules="rules"
        label-width="120px"
        v-loading="formLoading"
      >
        <el-form-item
          label="工序："
          prop="technologicalProcessDetailId"
          style="margin-top: 20px"
        >
          <el-select-v2
            v-model="form.technologicalProcessDetailId"
            clearable
            :options="technologicalProcessDetailsList"
            placeholder="请选择工序："
            @change="handleDetailsFormChange"
            style="width: 200px"
          />
        </el-form-item>

        <el-form-item label="标识：" prop="identification">
          <el-checkbox v-model="form.identification" label="重" size="large" />
          <el-checkbox v-model="form.markD" label="D标识" size="large" />
        </el-form-item>

        <el-form-item label="上传文件：" prop="url">
          <el-input disabled v-model="form.url" placeholder="上传文件">
            <template #append>
              <el-upload
                :disabled="!form.technologicalProcessDetailId"
                :action="webHost + '/common/upload'"
                :headers="headers"
                :on-success="handleSuccess"
                :on-exceed="handleExceed"
                :before-upload="beforeUpload"
                :show-file-list="false"
                ref="uploadrefss"
              >
                <el-button icon="Upload"></el-button>
              </el-upload>
            </template>
          </el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :disabled="!form.url" type="primary" @click="submitForm"
            >确 定</el-button
          >
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script setup name="drawingDetails">
import { ref } from "vue";
import { getToken } from "@/utils/auth";
import {
  getNormalDrawing,
  getListByName,
  saveDrawing,
  drawingNG,
  replace,
  drawingRemove,
} from "@/api/business/drawing";
import useUserStore from "@/store/modules/user";
import { getTechnological, getById } from "@/api/business/product";
import { getTechnologicalProcessDetails } from "@/api/business/technologicalProcessDetail";

const drawingUrl = ref("");
const webHost = import.meta.env.VITE_APP_BASE_API;
const fileUrl = import.meta.env.VITE_PREVIEW_API;
const hostUrl = import.meta.env.VITE_HOST_URL;

const inNet = import.meta.env.VITE_HOST_INNET;
const outNet = import.meta.env.VITE_HOST_OUTNET;
const hostIp = import.meta.env.VITE_HOST_IP;
const { proxy } = getCurrentInstance();
const { drawing_status } = proxy.useDict("drawing_status");
const { drawing_type } = proxy.useDict("drawing_type");
const uploadrefss = ref();
const parentName = ref("");
const total = ref(0);
const route = useRoute();
const coverName = ref("");
const currentProduct = ref({});
const currentTechnological = ref({});
const formLoading = ref(false);
const currentTechnologicalDetail = ref({});
const technologicalProcessList = ref([]);
const technologicalProcessDetailsList = ref([]);
const technologicalDetailId = ref(null);
const open = ref(false);
const draform = ref({});
const currentDrawing = ref({});
const replaceForm = ref({});
const repeatingDrawings = ref([]);
const drawingTable = ref(null);
const loading = ref(false);
const drawingList = ref([]);
const headers = { Authorization: getToken() };
const productId = ref(null);
const technologicalprocessDetailId = ref(null);
const processCode = ref(null);
const productVersion = ref(null);
/** 查询对象 */
const data = reactive({
  queryparams: {
    pageNum: 1,
    pageSize: 10,
    technologicalProcessDetailId: null,
  },
  form: {
    pageNum: 1,
    pageSize: 10,
    parentId: null,
    technologicalProcessDetailId: null,
    groupDetailList: [],
    code: "",
    remark: "",
    type: false,
  },
  rules: {
    technologicalProcessDetailId: [
      { required: true, message: "工序不能为空", trigger: "blur" },
    ],
  },
});
const { form, rules, queryparams } = toRefs(data);

function getList() {
  // 解析查询字符串
  // var urlSearchParams = new URLSearchParams(route.params.currentProduct);

  // 将 URLSearchParams 对象转换为普通对象
  // var paramsObject = Object.fromEntries(urlSearchParams);

  // currentProduct.value = paramsObject

  productId.value = route.params.productId;
  productVersion.value = route.params.productVersion;
  if (route.params.processCode && !processCode.value) {
    processCode.value = route.params.processCode;
  } else if (!route.params.processCode && !processCode.value) {
    technologicalDetailId.value = null;
  }
  //查询产品
  getById(productId.value).then((resMsg) => {
    if (resMsg.code == 200) {
      currentProduct.value = resMsg.data;
    }
  });

  //查询工艺版本
  getTechnological({ productId: productId.value }).then((res) => {
    if (res.code == 200) {
      technologicalProcessList.value = res.data;
      //版本下拉框默认值
      currentTechnological.value.productVersion = productVersion.value;

      //查询工艺工序
      getTechnologicalProcessDetails({
        technologyVersion: currentTechnological.value.productVersion,
        productId: productId.value,
        isHistory: 0,
      }).then((response) => {
        if (response.code == 200) {
          technologicalProcessDetailsList.value = response.data;
          if (
            processCode.value !== undefined &&
            processCode.value !== null &&
            processCode.value !== "undefined"
          ) {
            if (!technologicalDetailId.value) {
              technologicalDetailId.value = response.data.find(
                (detail) => detail.code == processCode.value
              ).value;
              currentTechnologicalDetail.value.id = response.data.find(
                (detail) => detail.code === processCode.value
              ).value;
            }
          } else {
            technologicalDetailId.value = null;
          }

          getDrawing();
        }
      });
    }
  });
}

function handleTechnologicalProcessDetails() {
  loading.value = true;
  //查询工艺工序
  getTechnologicalProcessDetails({
    technologyVersion: currentTechnological.value.productVersion,
    productId: productId.value,
    isHistory: 0,
  }).then((response) => {
    if (response.code == 200) {
      technologicalProcessDetailsList.value = response.data;
      if (
        processCode.value !== undefined &&
        processCode.value !== null &&
        processCode.value !== "undefined"
      ) {
        if (!technologicalDetailId.value) {
          technologicalDetailId.value = response.data.find(
            (detail) => detail.code == processCode.value
          ).value;
          currentTechnologicalDetail.value.id = response.data.find(
            (detail) => detail.code === processCode.value
          ).value;
        } else {
          // 判断下是否在列表里，假设不在赋值第一个
          const index = response.data.findIndex(
            (detail) => detail.value === technologicalDetailId.value
          );
          if (index < 0) {
            technologicalDetailId.value = response.data.find(
              (detail) => detail.code == processCode.value
            ).value;
            currentTechnologicalDetail.value.id = response.data.find(
              (detail) => detail.code === processCode.value
            ).value;
          }
        }
      } else {
        technologicalDetailId.value = null;
      }

      getDrawing();
    }
  });
}

function handleDetailsFormChange(row) {
  if (row) {
    technologicalDetailId.value = form.value.technologicalProcessDetailId;
    var matchingDetail = technologicalProcessDetailsList.value.find(
      (detail) => detail.value === technologicalDetailId.value
    );
    processCode.value = matchingDetail.code;
  } else {
    processCode.value = null;
    drawingUrl.value = null;
  }
}

function openDrawing() {
  window.open(drawingUrl.value);
}

function handleSelectionChange(row) {
  if (row) {
    loading.value = true;
    currentDrawing.value = row;
    // drawingUrl.value = fileUrl + encodeURIComponent(Base64.encode(document.location.origin + webHost + row.url))

    var itemUrl = document.location.origin;
    var fUrl = "";
    if (itemUrl.includes(hostIp)) {
      fUrl = inNet;
    } else {
      fUrl = outNet;
    }
    console.log(
      fUrl + encodeURIComponent(Base64.encode(hostUrl + webHost + row.url))
    );
    drawingUrl.value =
      fUrl + encodeURIComponent(Base64.encode(hostUrl + webHost + row.url));
    loading.value = false;
  }
}

/**文件数量超出的回调 */
function handleExceed(files) {
  uploadrefss.value.clearFiles();

  // console.log("handleExceed", files);
  // form.value.url = files[0].url;
}
/** 文件上传前的 回调事件 */
function beforeUpload(file) {
  formLoading.value = true;
  const allowedTypes = ["application/pdf"];
  const isAllowed = allowedTypes.includes(file.type);
  if (!isAllowed) {
    proxy.$modal.msgError("只能上传 PDF 格式的文件!");
    formLoading.value = false;
    return false;
  }
}
function handelUpload() {
  open.value = true;
  form.value.identification = 0;
  form.value.markD = 0;
  form.value.productId = productId.value;
  form.value.productVersion = currentTechnological.value.productVersion;
  form.value.processCode = processCode.value;
  form.value.technologicalProcessDetailId = currentTechnologicalDetail.value.id;
}
/**获取图纸列表 */
function getDrawing() {
  queryparams.value.productId = productId.value;
  queryparams.value.productVersion = currentTechnological.value.productVersion;

  queryparams.value.processCode = processCode.value;
  // if (currentTechnologicalDetail.value.id !== undefined && currentTechnologicalDetail.value.id !== 'undefined') {
  //     queryparams.value.technologicalProcessDetailId = currentTechnologicalDetail.value.id

  // }
  getNormalDrawing(queryparams.value).then((res) => {
    if (res.code == 200) {
      drawingList.value = res.rows;

      if (res.rows.length > 0) {
        proxy.$refs.drawingTable.setCurrentRow(res.rows[0]);
      } else {
        drawingUrl.value = null;
      }
      total.value = res.total;
    }
    loading.value = false;
  });
}
/**上传成功回调 */
function handleSuccess(row) {
  form.value.url = row.fileName;

  var fileDrawing = {};
  fileDrawing.drawingName = row.originalFilename;
  fileDrawing.productId = productId.value;
  fileDrawing.processCode = processCode.value;
  fileDrawing.productVersion = currentTechnological.value.productVersion;

  // fileDrawing.productVersion = productVersion.value;
  getListByName(fileDrawing).then((res) => {
    // debugger;
    if (res.code == 200) {
      repeatingDrawings.value = res.data;
      if (repeatingDrawings.value.length == 0) {
        coverName.value = row.originalFilename;
        formLoading.value = false;
      } else {
        //判断重名文件状态是否已发行需要替换
        if (repeatingDrawings.value[0].status == 2) {
          proxy.$modal.msgWarning("待审核中已有相同文件");
          var item = {};
          item = repeatingDrawings.value[0];
          item.parentId = currentDrawing.value.id;
          item.id = null;
          item.url = replaceForm.value.url;
          item.drawingName = fileDrawing.drawingName;
          item.technologicalProcessDetailId =
            fileDrawing.technologicalProcessDetailId;
          formLoading.value = false;
          handleReplace(item);
        } else {
          proxy.$modal.msgError("已有相同文件，请修改后重新上传");
          open.value = false;
          formLoading.value = false;
        }
      }
    }
  });
}

/**文件数量超出的回调 */
function handleReplaceExceed(files) {
  replaceForm.value.url = files[0].url;
}
/**上传成功回调 */
function handleReplaceSuccess(row) {
  replaceForm.value.url = row.fileName;
  var fileDrawing = {};
  fileDrawing.drawingName = row.originalFilename;
  fileDrawing.technologicalProcessDetailId =
    currentTechnologicalDetail.value.id;
  var item = {};
  item.parentId = currentDrawing.value.id;
  item.id = null;
  item.url = replaceForm.value.url;
  item.drawingName = fileDrawing.drawingName;
  item.technologicalProcessDetailId = fileDrawing.technologicalProcessDetailId;
  handleReplace(item);
}

function replaceClick(row) {
  console.log(form.value.identification, 453);
  form.value.parentId = row.id;
  form.value.technologicalProcessDetailId = row.technologicalProcessDetailId;
  form.value.identification = 0;
  form.value.markD = 0;
  open.value = true;
}
function submitForm() {
  proxy.$refs["drawingRef"].validate((valid) => {
    if (valid) {
      if (form.value.parentId) {
        proxy.$modal
          .confirm("是否确认替换图纸？")
          .then(function () {
            if (
              currentTechnologicalDetail.value.id !== undefined &&
              currentTechnologicalDetail.value.id !== null &&
              currentTechnologicalDetail.value.id !== "undefined"
            ) {
              form.value.technologicalProcessDetailId =
                currentTechnologicalDetail.value.id;
            }
            return replace(form.value);
          })
          .then(() => {
            reset();
            handleDetailsChange();
            open.value = false;
            proxy.$modal.msgSuccess("替换成功");
          })
          .catch(() => {});
      } else {
        saveDrawingDetail();
      }
    }
  });
}
/**保存方法 */
function saveDrawingDetail() {
  // if (currentTechnologicalDetail.value.id !== undefined && currentTechnologicalDetail.value.id !== null && currentTechnologicalDetail.value.id !== 'undefined') {
  //     form.value.technologicalProcessDetailId = currentTechnologicalDetail.value.id
  // }

  console.log("保存processCode", processCode.value);
  form.value.drawingName = coverName.value;
  form.value.processCode = processCode.value;
  form.value.productId = productId.value;
  form.value.productVersion = currentTechnological.value.productVersion;
  // form.value.productVersion = productVersion.value;
  var itemList = [];
  itemList.push(form.value);
  saveDrawing(itemList).then((res) => {
    if (res.code == 200) {
      reset();
      getList();
      formLoading.value = false;
      open.value = false;
    }
  });
}
/**审核 */
function handlePreview(row) {
  var drawing = [];
  drawing.push(row);
  saveDrawing(drawing).then((res) => {
    if (res.code == 200) {
      proxy.$modal.msgSuccess("审核通过");
      reset();
      getList();
    }
  });
}
function reset() {
  form.value = {
    pageNum: 1,
    pageSize: 10,
    code: null,
    remark: null,
    groupDetailList: [],
    url: null,
    drawingName: null,
    identification: 0,
    markD: 0,
    type: false,
  };
  currentTechnologicalDetail.value = {};
  coverName.value = "";
  repeatingDrawings.value = [];
  proxy.resetForm("drawingRef");
}
// 取消按钮
function cancel() {
  uploadrefss.value.clearFiles();
  handleDetailsChange();

  open.value = false;

  reset();
}
/**版本change事件 */
function handelTechnological(row) {
  let selectedOption = technologicalProcessList.value.find(
    (option) => option.value === row
  );
  currentTechnological.value.productVersion = selectedOption.label;
  handleTechnologicalProcessDetails();
}
/**工序选择change事件 */
function handleDetailsChange() {
  loading.value = true;
  if (technologicalDetailId.value) {
    var matchingDetail = technologicalProcessDetailsList.value.find(
      (detail) => detail.value === technologicalDetailId.value
    );
    currentTechnologicalDetail.value.id =
      technologicalDetailId.value == undefined
        ? null
        : technologicalDetailId.value;
    processCode.value = matchingDetail.code;
  } else {
    processCode.value = null;
    drawingUrl.value = null;
  }
  getDrawing();
}
/**NG电子图纸 */
function handleDrawingNG(row) {
  proxy.$modal
    .confirm("是否确认NG？")
    .then(function () {
      var itemList = [];
      itemList.push(row);
      return drawingNG(itemList);
    })
    .then(() => {
      reset();
      getList();
      open.value = false;
      proxy.$modal.msgSuccess("操作成功");
    })
    .catch(() => {});
}
/**废弃电子图纸 */

function handleDrawingRemove(row) {
  proxy.$modal
    .confirm("是否确认作废？")
    .then(function () {
      var itemList = [];
      itemList.push(row);
      return drawingRemove(itemList);
    })
    .then(() => {
      reset();
      getList();
      open.value = false;
      proxy.$modal.msgSuccess("操作成功");
    })
    .catch(() => {});
}

function handleReplace(row) {
  proxy.$modal
    .confirm("是否确认替换图纸？")
    .then(function () {
      return replace(row);
    })
    .then(() => {
      reset();
      getList();
      open.value = false;
      proxy.$modal.msgSuccess("替换成功");
    })
    .catch(() => {});
}

getList();
</script>

<style scoped>
:deep(.el-form-item .el-form-item__label) {
  font-size: 14px !important;
  padding-right: 0 !important;
}

:deep(#list-search-container .el-form-item--default .el-form-item__content) {
  line-height: 32px;
  font-size: 18px;
}
</style>