<template>
  <div class="excel-detail">
    <a-spin :spinning="loading" :delay="100">
      <div class="excel-detail-header">
        <div class="back-btn" @click="back">
          <left-outlined class="back-btn-icon" />
          <span>返回</span>
        </div>
        <a-divider type="vertical" class="divider" />
        <div class="excel-name">{{ excelData?.excelName }}</div>

        <a-space class="excel-action" :size="16">
          <template v-if="excelType == '1'">
            <a-button class="border-radius" @click="exportClick('xlsx')">导出Excel</a-button>
            <a-button class="border-radius" @click="importClick()">导入Excel</a-button>
            <a-button class="border-radius" type="primary" ghost @click="save('back')">保存并返回</a-button>
            <a-button class="border-radius" type="primary" @click="save()">保存</a-button>
          </template>
          <a-button class="border-radius" v-if="excelType == '2'" @click="printClick()">打印</a-button>
        </a-space>
      </div>
      <div class="excel-detail-body">
        <input
          id="file-input"
          type="file"
          name="files[]"
          accept=".xlsx, .ssjson, .json, .sjs, .zip, .xlsm"
          class="hide"
          @change="openFile()"
          style="display: none"
        />
        <div id="designer-container" ref="designerContainerRef"></div>
        <div id="ss2" style="display: none"></div>
      </div>
    </a-spin>
  </div>
</template>

<script setup>
import { useRoute, useRouter } from 'vue-router';
import { ref, onMounted } from 'vue';
import { BusinessExcelApi } from '../manage/api/BusinessExcelApi';
// excel
import '@grapecity-software/spread-sheets/styles/gc.spread.sheets.excel2013white.css';
import '@grapecity-software/spread-sheets-designer/styles/gc.spread.sheets.designer.min.css';
import GC from '@grapecity-software/spread-sheets';
import '@grapecity-software/spread-sheets-shapes';
import '@grapecity-software/spread-sheets-charts';
import '@grapecity-software/spread-sheets-slicers';
import '@grapecity-software/spread-sheets-print';
import '@grapecity-software/spread-sheets-barcode';
import '@grapecity-software/spread-sheets-pdf';
import '@grapecity-software/spread-sheets-pivot-addon';
import '@grapecity-software/spread-sheets-tablesheet';
import '@grapecity-software/spread-sheets-ganttsheet';
import '@grapecity-software/spread-sheets-formula-panel';
import '@grapecity-software/spread-sheets-reportsheet-addon';
import '@grapecity-software/spread-sheets-io';
import '@grapecity-software/spread-sheets-resources-zh';
// 注意：spread-sheets-designer-resources-cn 与 spread-sheets-designer 的先后顺序
import '@grapecity-software/spread-sheets-designer-resources-cn';
import '@grapecity-software/spread-sheets-designer';
import { message } from 'ant-design-vue';
import { getToken } from '@/utils/token-util';
import { API_BASE_PREFIX } from '@/config/setting';

GC.Spread.Common.CultureManager.culture('zh-cn');

const openOptions = {
  openMode: GC.Spread.Sheets.OpenMode.normal,
  fullRecalc: true
};

// excel 文件类型
const FileType = {
  SJS: 'sjs',
  Excel: 'xlsx',
  SSJson: 'ssjson'
};

const route = useRoute();
const router = useRouter();

const excelId = ref('');

const excelType = ref('');

const excelData = ref(null);

const designerContainerRef = ref(null);

const loading = ref(false);

let designer;
let Spread;

onMounted(() => {
  const { id, type } = route.query;
  excelId.value = id;
  excelType.value = type;

  if (!(id || type)) back();
  getDetail();
});

const getDetail = () => {
  BusinessExcelApi.detail({ id: excelId.value }).then(res => {
    excelData.value = res;
    if (excelType.value == '1') {
      designer = new GC.Spread.Sheets.Designer.Designer(designerContainerRef.value);
      Spread = designer.getWorkbook();
    } else if (excelType.value == '2') {
      Spread = new GC.Spread.Sheets.Workbook(designerContainerRef.value);
    }

    // 如果存在详情
    if (res?.excelFileId) {
      let url = `${API_BASE_PREFIX}/sysFileInfo/privateDownload?fileId=${res.excelFileId}&token=${getToken()}&secretFlag=Y`;
      var xhr = new XMLHttpRequest();
      xhr.open('GET', url, true);
      xhr.responseType = 'blob';
      xhr.onload = function (e) {
        if (this.status == 200) {
          var blob = this.response;
          var fd = new FormData();
          fd.append('file', [blob]);
          var fd = new File([blob], `${excelData.value?.excelName}.xlsx`);
          Spread.import(
            fd,
            function () {},
            function () {},
            openOptions
          );
        }
      };
      xhr.send();
    }
  });
};

const back = () => {
  router.push({
    path: '/mid/app/detail',
    query: {
      type: 'excel'
    }
  });
};

// 导出excel
const exportClick = (fileType = 'xlsx') => {
  var Spread = designer.getWorkbook();
  var json = Spread.toJSON({ columnHeadersAsFrozenRows: true });
  var newSpread = new GC.Spread.Sheets.Workbook(document.getElementById('ss2'));
  newSpread.fromJSON(json);
  var fileName = `${excelData.value?.excelName}.${fileType}`;
  var options = getExportOptions(fileType);
  if (fileType === FileType.SJS) {
    newSpread.save(
      function (blob) {
        saveAs(blob, fileName);
      },
      function () {},
      options
    );
  } else if (fileType === FileType.SSJson) {
    var template = Spread.toJSON({ includeBindingSource: true });
    const designerBindingPathSchema =
      designer.getData('treeNodeFromJson') || designer.getData('updatedTreeNode') || designer.getData('oldTreeNodeFromJson');
    if (designerBindingPathSchema) {
      template.designerBindingPathSchema = JSON.parse(designerBindingPathSchema);
    }
    var ssjson = JSON.stringify(template);
    funDownload(ssjson, fileName);
  } else {
    newSpread.export(
      function (blob) {
        saveAs(blob, fileName);
      },
      function () {},
      options
    );
  }
};

function getExportOptions(fileType) {
  return {
    fileType: GC.Spread.Sheets.FileType[fileType],
    includeBindingSource: true,
    saveAsView: true
  };
}

var funDownload = function (content, filenam) {
  var eleLink = document.createElement('a');
  eleLink.download = filenam;
  eleLink.style.display = 'none';
  // 字符内容转变成blob地址
  var blob = new Blob([content]);
  eleLink.href = URL.createObjectURL(blob);
  // 触发点击
  document.body.appendChild(eleLink);
  eleLink.click();
  // 然后移除
  document.body.removeChild(eleLink);
};

// 导入excel
const importClick = () => {
  var fileInput = document.getElementById('file-input');
  fileInput.click();
};

// 打开文件
const openFile = e => {
  var fileInput = document.getElementById('file-input');
  var file = fileInput.files[0];
  if (!file) {
    message.error('没有上传文件');
    return;
  }
  var fileName = file.name;
  var extensionName = fileName.substring(fileName.lastIndexOf('.') + 1);

  if (extensionName === 'ssjson' || extensionName === 'json') {
    var reader = new FileReader();
    reader.readAsText(file);
    reader.onload = function (evt) {
      var fileString = evt.target.result;
      var jsonObj = JSON.parse(fileString);
      designer.setData('treeNodeFromJson', JSON.stringify(jsonObj.designerBindingPathSchema));
      designer.setData('updatedTreeNode', JSON.stringify(jsonObj.designerBindingPathSchema));
      designer.setData('oldTreeNodeFromJson', JSON.stringify(jsonObj.designerBindingPathSchema));
      var ssjson = jsonObj;
      Spread.suspendPaint();
      Spread.fromJSON(ssjson, { doNotRecalculateAfterLoad: true });
      Spread.resumePaint();
    };
  } else if (extensionName === '.SJS') {
    Spread.open(
      file,
      function () {
        fileNameItem.value = fileName;
        fileInput.value = '';
      },
      function () {},
      openOptions
    );
  } else {
    Spread.import(
      file,
      function () {
        fileNameItem.value = fileName;
        fileInput.value = '';
      },
      function () {},
      openOptions
    );
  }
};

const save = type => {
  loading.value = true;
  var Spread = designer.getWorkbook();
  Spread.export(function (blob) {
    var fd = new FormData();
    fd.append('file', blob);
    fd.append('id', excelId.value);
    BusinessExcelApi.updateExcelContent(fd)
      .then(res => {
        message.success(res.message);
        if (type) {
          back();
        }
      })
      .finally(() => (loading.value = false));
  });
};

const printClick = () => {
  function setPrintInfoNumberValueItem(printInfo, key, method) {
    var value = parseInt(_getElementById(key).value),
      method = method || key;
    if (!isNaN(value)) {
      printInfo[method](value);
    }
  }
  var sheetCount = Spread.getSheetCount();
  for (let j = 0; j < sheetCount; j++) {
    var sheet = Spread.getSheet(j);
    var printInfo = sheet.printInfo();
    sheet.suspendPaint();

    //   ["rowStart", "rowEnd", "columnStart", "columnEnd", "repeatRowStart", "repeatRowEnd", "repeatColumnStart", "repeatColumnEnd"].forEach(function (name) {
    //       setPrintInfoNumberValueItem(printInfo, name);
    //   });
    // sheet.setRowPageBreak(5, true);
    // sheet.setColumnPageBreak(3, true);
    printInfo.showBorder(false);
    printInfo.showGridLine(false);
    printInfo.showRowHeader('1');
    printInfo.showColumnHeader('1');

    printInfo.margin({ top: 60, bottom: 25, left: 30, right: 30, header: 10, footer: 20 });
    sheet.resumePaint();
  }
  Spread.print();
};
</script>

<style scoped lang="less">
.excel-detail {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  background-color: #fff;

  .excel-detail-header {
    width: 100%;
    padding: 8px 16px;
    display: flex;
    height: 52px;
    align-items: center;
    position: relative;
    gap: 16px;
    border-bottom: 1.5px solid rgba(197, 207, 209, 0.4);

    .back-btn {
      color: #60666b;
      font-size: 16px;
      font-style: normal;
      font-weight: 400;
      line-height: normal;
      display: flex;
      align-items: center;
      cursor: pointer;

      .back-btn-icon {
        font-size: 14px;
        color: #898e91;
        margin-right: 4px;
      }
    }

    .divider {
      border-right: 1.5px solid #c5cfd1;
      height: 14px;
      top: 1px;
    }

    .excel-name {
      color: #43505e;
      font-size: 16px;
      font-style: normal;
      font-weight: 700;
      line-height: normal;
    }

    .excel-action {
      top: 8px;
      position: absolute;
      right: 16px;
    }
  }

  .excel-detail-body {
    width: 100%;
    height: calc(100% - 52px);

    #designer-container {
      width: 100%;
      height: 100%;
    }
  }
}
</style>
