<template>
  <!-- 添加或修改项目信息对话框 -->
  <el-drawer v-model="visible" size="30%" direction="rtl" :close-on-press-escape="false" @close="close">
    <div class="page-container form-container">
      <div class="form-btns-container">
        <span class="title-label"><el-icon>
            <Document />
          </el-icon>
          电子工艺图纸</span>
      </div>

      <!-- 搜索区域 -->
      <el-form class="list-search-container" :inline="true">
        <el-form-item>
          <el-upload  v-loading.fullscreen.lock="allLoading" :action="webHost + '/common/upload'" :headers="headers" :on-success="handleSuccess"
            :on-exceed="handleExceed" :before-upload="beforeUpload" :show-file-list="false">
            <el-button type="success" icon="Plus" v-hasPermi="['business:drawing:add']">上传图纸
            </el-button>
          </el-upload>
          <el-button type="primary" icon="Search" v-hasPermi="['business:drawing:record']" @click="handleRecords"
            style="margin-left: 10px;">操作历史
          </el-button>
        </el-form-item>
      </el-form>
      <!-- 列表区 -->
      <div class="el-table-container">
        <el-table ref="equipmentTable" v-loading="loading" row-key="id" @selection-change="handleSelectionChange"
          :data="form.drawingList" height="100%">
          <!-- <el-table-column type="selection" width="40" align="center" /> -->
          <el-table-column label="图纸" prop="drawingName" align="center" />
          <el-table-column fixed="right" label="操作" align="center" width="140px">
            <template #default="scope">
              <el-button link type="primary" v-hasPermi="['business:drawing:preview']"
                @click="handlePreview(scope.row)">预览
              </el-button>
              <el-button link type="success" plain v-hasPermi="['business:drawing:download']"
                @click="handleDownload(scope.row)">下载</el-button>

              <el-button link type="danger" v-hasPermi="['business:drawing:remove']"
                @click="handleDelete(scope.row.id)">删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 分页 -->
      <pagination v-show="total > 0" :total="total" v-model:page="queryparams.pageNum"
        v-model:limit="queryparams.pageSize" @pagination="getList" />
    </div>

    <el-dialog v-model="dialogVisible" width="1500px">
      <iframe :src="pdfCover" style="width: 100%; height: 800px"></iframe>
    </el-dialog>

    <!-- 添加或修改app版本管理对话框 -->
    <el-dialog title="查询到有同名文件" v-model="openRecords" width="280px" append-to-body>

      <template #footer>
        <div>
          <el-button type="primary" @click="coverDrawing"  v-loading.fullscreen.lock="allLoading">覆 盖</el-button>
          <el-button type="success" @click="saveDrawing"  v-loading.fullscreen.lock="allLoading">不 覆 盖</el-button>
          <el-button type="info" @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </el-drawer>
  <!-- 图纸弹窗 -->
  <redcord-dialog ref="redcordsForm" />
  <!-- <pdf :src="pdfUrl" /> -->
</template>
<script setup>
// import  PDF  from 'vue-pdf';
import {
  listDrawing,
  addDrawing,
  delDrawing,
  updateDrawing,
  drawingByName
} from "@/api/business/drawing";
import { addRecords } from '@/api/business/drawingRecords'
import redcordDialog from './recordsDialog'
import { getToken } from '@/utils/auth'
import useUserStore from '@/store/modules/user'
const fileUrl = import.meta.env.VITE_PREVIEW_API
const webHost = import.meta.env.VITE_APP_BASE_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 total = ref(0)
/** 表单抽屉 页变量 */
const processDetail = ref({});
/**覆盖对话框显示 */
const openRecords = ref(false)
const formLoading = ref(false)
const pdfCover = ref('')
const dialogVisible = ref(false)
/**覆盖用对象 */
const editRow = ref({})
const pdfUrl = ref('')
/**不覆盖文件名 */
const coverName = ref('')
const repeatingDrawings = ref([])
const selections = ref([]);
const headers = { Authorization: getToken() }
const loading = ref(false);
const allLoading = ref(false)
const visible = ref(false);
const props = defineProps({

  handleRefresh: {
    type: Function,
    default: null
  }

})
const { handleRefresh } = toRefs(props)

/** 查询对象 */
const data = reactive({
  queryparams: {
    pageNum: 1,
    pageSize: 10,
    technologicalProcessDetailId: null
  },
  form: {
    pageNum: 1,
    pageSize: 10,
    groupDetailList: [],
    code: "",
    remark: "",
    type: false
  },
  rules: {
    code: [{ required: true, message: "资源组编码不能为空", trigger: "blur" }],
  },
});
const { form, rules, queryparams } = toRefs(data);

/***********************  方法区  ****************************/
/** 打开抽屉 */
function open(row) {

  processDetail.value = row
  queryparams.value.productId = row.productId
  queryparams.value.processCode = row.processCode
  queryparams.value.productVersion = row.technologyVersion


  form.value.productId = row.productId
  form.value.processCode = row.processCode
  form.value.productVersion = row.technologyVersion

  getList()
  visible.value = true;
};
/**查询列表 */
function getList() {
  loading.value = true;
  listDrawing(queryparams.value).then(res => {
    form.value.drawingList = res.rows
    total.value = res.total

  })
  loading.value = false;
}
/**
 * 打开操作页面
 */
function handleRecords() {
  var item = {}

  item.productId = processDetail.value.productId
  item.processCode = processDetail.value.processCode
  item.productVersion = processDetail.value.technologyVersion
  proxy.$refs.redcordsForm.open(item);
}

/**
 * 列表checkbox列选择 事件
 */
function handleSelectionChange(selection) {
  selections.value = selection;
}



/** 文件下载 */
function handleDownload(row) {

  return new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest();
    xhr.open('GET', webHost + row.url, true);
    xhr.responseType = 'blob';
    xhr.upload.onprogress = (e) => {
      if (e.lengthComputable) {
        let progress = e.loaded / e.total;
      }
    };
    xhr.onload = function () {
      const url = window.URL.createObjectURL(xhr.response);
      const eleLink = document.createElement('a');
      eleLink.href = webHost + row.url;
      eleLink.download = `${row.drawingName}`;
      eleLink.style.display = 'none';
      document.body.appendChild(eleLink);
      eleLink.click();
      document.body.removeChild(eleLink);

      var recordsItem = {}
      recordsItem.technologicalProcessDetailId = row.technologicalProcessDetailId;

      recordsItem.productId = row.productId
      recordsItem.processCode = row.processCode
      recordsItem.productVersion = row.technologyVersion
      recordsItem.technologicalProcessDetailDrawingId = row.id
      recordsItem.userId = useUserStore().user.userId
      recordsItem.type = "下载"
      recordsItem.drawingName = row.drawingName
      addRecords(recordsItem).then(res => {
        if (res.code == 200) {
          resolve('success');
        }
      })

    };
    xhr.onerror = (e) => {
      proxy.$modal.msgError('下载文件失败!')
      reject(e);
    };
    xhr.send();
  });

  // window.location.href = webHost + url
}
/**删除 */
function handleDelete(id) {
  proxy.$modal
    .confirm('是否确认删除选中的电子图纸？')
    .then(function () {
      return delDrawing(id)
    })
    .then(() => {
      reset();
      open(processDetail.value)
      proxy.$modal.msgSuccess('删除成功！')
    })

}

/**上传成功回调 */
function handleSuccess(row) {
  allLoading.value = true
  form.value.url = row.fileName
  console.log(row.fileName, "上传成功")
  var fileDrawing = {}
  fileDrawing.drawingName = row.originalFilename
  fileDrawing.productId = processDetail.value.productId
  fileDrawing.processCode = processDetail.value.processCode
  fileDrawing.productVersion = processDetail.value.technologyVersion

  drawingByName(fileDrawing).then(res => {
    // debugger;
    if (res.code == 200) {
      console.log(res, "数据库查询")
      repeatingDrawings.value = res.data
      if (repeatingDrawings.value.length == 0) {
        coverName.value = row.originalFilename
        saveDrawing();
      } else {
        allLoading.value = false
        /**覆盖对象 */
        editRow.value = JSON.parse(JSON.stringify(repeatingDrawings.value[0]));
        editRow.value.url = form.value.url
        //有同名文件，询问是否覆盖
        openRecords.value = true
        coverName.value = row.originalFilename
        // coverName.value = row.originalFilename.slice(0, -4) + "_" + row.newFileName.slice(-6, -4) + row.originalFilename.slice(-4);
      }


    }
  })
}
//覆盖保存
function coverDrawing() {
  allLoading.value = true
  updateDrawing(editRow.value).then(res => {
    if (res.code == 200) {
    
      reset();
      open(processDetail.value)
      formLoading.value = false
      openRecords.value = false
      allLoading.value = false
      // form.value.type = true
      // form.value.drawingName = coverName.value
      // saveDrawing();

    }
  })
}
//不覆盖保存
function saveDrawing() {
allLoading.value = true
  form.value.drawingName = coverName.value
  addDrawing(form.value).then(res => {
    if (res.code == 200) {
      proxy.$modal.msgSuccess('上传成功!')
      reset();
      open(processDetail.value)
      formLoading.value = false
      openRecords.value = false
      allLoading.value = false
    }
  })
}

/**预览 */
function handlePreview(row) {
  //0617预览不需要内嵌，新开一个标签页
  // hostUrl+webHost+row.url 必须时文件全路径 不能转
  // window.open(fileUrl + encodeURIComponent(Base64.encode(document.location.origin  + webHost + row.url)))
  // // window.open(fileUrl+ encodeURIComponent(Base64.encode(document.location.host +webHost+row.url)))
  // console.log('全路径：'+hostUrl+webHost+row.url)

  console.log(document.location)
  //0617预览不需要内嵌，新开一个标签页
  // hostUrl+webHost+row.url 必须时文件全路径 不能转
  var itemUrl = document.location.origin
  var fUrl = ''
  var webUrl = ''
  console.log(hostIp, itemUrl, 215)
  console.log(document.location.origin + webHost + row.url)
  if (itemUrl.includes(hostIp)) {
    fUrl = inNet
    // webUrl = "http://192.168.10.41"
  } else {
    fUrl = outNet
    // webUrl = "http://36.129.132.128:401"
  }
  window.open(fUrl + encodeURIComponent(Base64.encode(hostUrl + webHost + row.url)))
}

// 取消按钮
function cancel() {
  openRecords.value = false
}
/**文件数量超出的回调 */
function handleExceed(files) {
  form.value.url = files[0].url
}
/** 文件上传前的 回调事件 */
function beforeUpload(file) {
  formLoading.value = true
  allLoading.value = true
  const allowedTypes = ['application/pdf'];
  const isAllowed = allowedTypes.includes(file.type);
  if (!isAllowed) {
    proxy.$modal.msgError('只能上传 PDF 格式的文件!')
    allLoading.value = false
    return false
  }

}
/**
 * 对话框关闭 事件
 */
function close() {
  reset();
  handleRefresh.value()
  visible.value = false;
}

/** 表单重置 */
function reset() {
  form.value = {
    pageNum: 1,
    pageSize: 10,
    code: null,
    remark: null,
    groupDetailList: [],
    url: null,
    drawingName: null,
    type: false
  };
  coverName.value = ''
  repeatingDrawings.value = []
  proxy.resetForm("formRef");
}





/** 取消按钮 */
const handleCancel = () => {
  visible.value = false;
  reset();
};

/** 暴露给父组件的方法 */
defineExpose({
  open,
});
</script>
  