<template>
  <div class="report">
    <div class="rpHeader">
      <div class="rphLeft">
        <QtReport ref="reportQT" :realRes="realRes" :pdSubType="pdSubType" v-if="pdSubType === 39 || pdSubType === 47">
        </QtReport>
        <RtReport ref="reportRT" :realRes="realRes" :pdSubType="pdSubType" v-else></RtReport>
      </div>
      <div class="rphRight">
        <div class="box1">
          <span class="sp1"></span><span class="sp2">产品检验报告PDF</span>
        </div>
        <div class="pdfContent" v-loading="pdfLoading" element-loading-text="PDF生成中..."
          element-loading-spinner="el-icon-loading">
          <iframe class="pdfPage" :src="pdfPath" frameborder="0" v-if="pdfLoading === false"></iframe>
        </div>
      </div>
    </div>
    <div class="rpShow">
      <el-tabs type="card">
        <el-tab-pane label="查看待检验产品">
          <div class="earth" id="cesiumView" @click="pickValue" style="overflow: hidden; position: relative"></div>
          <div class="cstop">
            <el-form :inline="true" :model="rpDataMsg" class="demo-form-inline" :disabled="true">
              <el-form-item label="卫星" class="ysjMsg">
                <el-input class="ysjMsgMrg" v-model="rpDataMsg.satellite" placeholder="采样卫星"></el-input>
              </el-form-item>
              <el-form-item label="载荷名称" class="ysjMsg">
                <el-input v-model="rpDataMsg.load" placeholder="载荷方式"></el-input>
              </el-form-item>
              <el-form-item label="空间分辨率" class="ysjMsg2">
                <el-input v-model="rpDataMsg.spatialRes" placeholder="空间分辨率"></el-input>
              </el-form-item>
              <el-form-item label="时间" class="ysjMsg">
                <el-input class="ysjMsgMrg" v-model="formatDateStr" placeholder="采样时间"></el-input>
              </el-form-item>
              <el-form-item label="级别" prop="resource" class="ysjMsg2">
                <el-radio-group v-model="rpDataMsg.level">
                  <el-radio label="3"></el-radio>
                  <el-radio label="4"></el-radio>
                  <el-radio label="5"></el-radio>
                  <!-- <el-radio label="其他"></el-radio> -->
                </el-radio-group> </el-form-item><br />
              <el-form-item label="坐标系统" class="ysjMsg">
                <el-input v-model="rpDataMsg.coordinateSys" placeholder="坐标系统"></el-input>
              </el-form-item>
              <el-form-item label="最小纬度" class="ysjMsg">
                <el-input v-model="rpDataMsg.minLat" placeholder="最小纬度"></el-input>
              </el-form-item>
              <el-form-item label="最大纬度" class="ysjMsg2">
                <el-input style="margin-left: 6px" v-model="rpDataMsg.maxLat" placeholder="最大纬度"></el-input>
              </el-form-item>
              <el-form-item label="最小经度" class="ysjMsg">
                <el-input v-model="rpDataMsg.minLon" placeholder="最小经度"></el-input>
              </el-form-item>
              <el-form-item label="最大经度" class="ysjMsg2">
                <el-input v-model="rpDataMsg.maxLon" placeholder="最大经度"></el-input>
              </el-form-item>
            </el-form>
          </div>
        </el-tab-pane>
        <el-tab-pane label="查看样本数据">
          <el-table :header-cell-style="headerRowClass" :cell-style="tableRowClassName"
            style="width: 98%; margin-left: 1%; margin-top: 15px" :data="sampleData" :stripe="true" height="520">
            <el-table-column type="index" label="序号" width="80">
            </el-table-column>
            <el-table-column prop="samplesId" label="样本编号" sortable>
            </el-table-column>
            <el-table-column prop="lng" label="经度">
              <template slot-scope="scope">
                {{ pdSubType == 45 ? scope.row.measureLong : scope.row.lng }}
              </template>
            </el-table-column>
            <el-table-column prop="lat" label="纬度">
              <template slot-scope="scope">
                {{ pdSubType == 45 ? scope.row.measureLat : scope.row.lat }}
              </template>
            </el-table-column>
            <!-- <el-table-column prop="alt" label="高度"></el-table-column> -->
            <el-table-column prop="collectDate" label="采样日期" sortable>
              <!-- <template slot-scope="scope">
                {{ scope.row.dataTime | formatDate }}
              </template> -->
            </el-table-column>
            <el-table-column prop="collectDate" label="预处理时间" sortable align="center">
              <template slot-scope="scope">
                {{ scope.row.collectDate }}
                <!-- {{ scope.row.addTime | formatDate }} -->
              </template>
            </el-table-column>
            <el-table-column prop="reliability" label="可信度" sortable align="center"></el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </div>
    <div class="rpBottom">
      <el-button type="primary" @click="downloadReport">下载PDF报告</el-button>
      <el-button type="primary" @click="submitReport">保存并提交</el-button>
      <el-button type="primary" @click="reExamine">重新检验</el-button>
    </div>
  </div>
</template>

<script>
import RtReport from "@/components/rtReport";
import QtReport from "@/components/qtReport";
import PdfLoad from "@/components/pdfLoad";
import cu from "@/lib/cesiumUtils";
import {
  saveValidationRes,
  saveReport,
  downloadPdf,
  updateOrderStage,
  exportWord,
  resetCheck,
} from "@/api/lang/pendingOrder";

import { productSubTypeVal, truthFunVal } from "@/lib/contract.js";
import {
  truthFunctionsMap,
  productTypeMap,
  productTypeSplMap,
} from "@/lib/variateMap";
import qs from "qs";

export default {
  components: {
    RtReport,
    QtReport,
    PdfLoad,
  },
  filters: {
    formatDate(inputTime) {
      if (!inputTime && typeof inputTime !== "number") {
        return "";
      }
      var localTime = "";
      inputTime = new Date(inputTime);
      const offset = new Date().getTimezoneOffset();
      localTime = new Date(inputTime - offset * 60000).toISOString();
      localTime = localTime.substr(0, localTime.lastIndexOf("."));
      localTime = localTime.replace("T", " ");
      return localTime;
    },
  },
  data() {
    return {
      queryParams: null,
      reportMsg: "",
      pdSubType: undefined,
      pdfLoading: true,
      pdfPath: "", // pdf文件地址
      sampleData: [],
      rpDataMsg: {
        satellite: "5米光学卫星",
        load: "可见/近红外相机",
        spatialRes: "0.00000307°",
        date: "2021-08-03 16:52:40",
        level: "3",
        coordinateSys: "WGS84",
        centerPoint: "POINT(118.32,34.7)",
        minLat: "116.13622332",
        maxLat: "118.3422222",
        minLon: "34.211234",
        maxLon: "35.3455667",
      },
      realRes: undefined,
      base64Data: null,
    };
  },
  mounted() {
    cu.initCesium("cesiumView");
    const geoWS = this.reportMsg.geoWS;
    const geoLN = this.reportMsg.geoLN;
    cu.addlayer(geoWS, geoLN);
    const gp = this.reportMsg.geoLayerPos;
    cu.flyToLayerRect(gp[0], gp[1], gp[2], gp[3]);

    const sd = this.sampleData;

    if (this.pdSubType === productSubTypeVal.ACS_ORTHOPHOTO) {
      for (let i in sd) {
        cu.addPoint(sd[i].measureLong, sd[i].measureLat, 10);
      }
    } else {
      for (let i in sd) {
        const alt = JSON.parse(sd[i].paramStr).alt;
        cu.addPoint(sd[i].lng, sd[i].lat, alt !== "null" ? alt : 10);
      }
    }

    if (
      this.pdSubType === productSubTypeVal.ACS_TYPESOFLANDCOVER ||
      this.pdSubType === productSubTypeVal.ACS_VEGETATIONPHENOLOGY
    ) {
      this.base64Data = this.$refs.reportQT.myCharts.getDataURL({
        type: "png",
        pixelRatio: 1.5, //放大两倍下载，之后压缩到同等大小展示。解决生成图片在移动端模糊问题
        backgroundColor: "#fff",
        excludeComponents: ["toolbox", "dataZoom"],
      });
    } else {
      this.base64Data = this.$refs.reportRT.myCharts.getDataURL({
        type: "png",
        pixelRatio: 1.5, //放大两倍下载，之后压缩到同等大小展示。解决生成图片在移动端模糊问题
        backgroundColor: "#fff",
        excludeComponents: ["toolbox", "dataZoom"],
      });
    }
    this.exportPdf(this.reportMsg);
  },
  created() {
    if (
      Object.keys(this.$route.params).length > 0 &&
      sessionStorage.getItem("prePage") === this.configration.path.inspection
    ) {
      this.queryParams = this.$route.params;
    } else {
      this.queryParams = JSON.parse(
        localStorage.getItem(this.configration.path.inspection)
      );
    }
    document.body.scrollTop = 0;
    this.init();
  },
  methods: {
    tableRowClassName({ rowIndex }) {
      if ((rowIndex + 1) % 2 !== 0) {
        return "background:#F5F7FA;text-align:center";
      } else {
        return "background:#FFFFFF;text-align:center";
      }
    },
    headerRowClass() {
      return "background: #E4E9F1;text-align:center";
    },
    init() {
      const self = this;
      const rpm = (self.reportMsg = this.queryParams);
      console.log("1111111", rpm);

      self.realRes = rpm.reportResult;
      self.pdSubType = rpm.pdSubType;
      const rsl = (self.sampleData = rpm.sampleList);
      // 设置样本数据展示（正射需要额外设置）
      if (rpm.pdSubType === productSubTypeVal.ACS_ORTHOPHOTO) {
        let otgVal = [];
        for (let i in rsl) {
          if (rsl[i].sameNameLong !== null) {
            otgVal.push({
              name: "mPoint",
              x: rsl[i].measureLong,
              y: rsl[i].measureLat,
            });
            otgVal.push({
              name: "sPoint",
              x: rsl[i].sameNameLong,
              y: rsl[i].sameNameLat,
            });
          }
        }
        self.realRes.otgVal = otgVal;
      }
      const md = rpm.metaData;
      self.rpDataMsg = {
        satellite: md.satellite,
        load: md.load,
        spatialRes: md.resRatio,
        date: md.producedDate,
        level: md.proLevel,
        coordinateSys: md.coordinateSys,
        minLat: md.minLat,
        maxLat: md.maxLat,
        minLon: md.minLon,
        maxLon: md.maxLon,
        centerPoint: "POINT(" + md.centerLon + "," + md.centerLat + ")",
      };
    },
    // 生产报告
    exportPdf(rpm) {
      const self = this;
      const asmo = rpm.orderMsg;
      const asmp = rpm.productMsg;
      const asmm = rpm.metaData;
      // 设置真实性检验参数
      const rpVal = rpm.reportResult.report;
      const crTime = rpm.reportResult.time;
      let iat = "";
      let iatResArr = [];
      const psId = self.pdSubType;
      const psVal = productSubTypeVal;
      let errorList = [];
      let realList = [];
      let otgError = [];
      for (let i in rpVal) {
        let ri = rpVal[i];
        const ni = Number(i);
        // 真实性检验算法判断（8，2，3）
        if (
          ni === truthFunVal.ACM_ERRORMATRIX ||
          ni === truthFunVal.ACM_RELATIVEERROR ||
          ni === truthFunVal.ACM_REALVALLIST
        ) {
          ri = JSON.stringify(rpVal[i]);
        }
        if (
          (ni === truthFunVal.ACM_MEANABSOLUTERELATIVEERROR ||
            ni === truthFunVal.ACM_MEANRELATIVEERROR) &&
          psId === psVal.ACS_ORTHOPHOTO
        ) {
          ri = JSON.stringify(rpVal[i]);
        }
        if (ni === truthFunVal.ACM_RELATIVEERROR) errorList = rpVal[i];
        if (ni === truthFunVal.ACM_REALVALLIST) realList = rpVal[i];
        if (ni === truthFunVal.ACM_OTGERROR) otgError = rpVal[i];
        iatResArr.push(truthFunctionsMap(i) + ":" + ri);
        if (
          ni !== truthFunVal.ACM_OTGERROR &&
          ni !== truthFunVal.ACM_REALVALLIST
        )
          iat += truthFunctionsMap(i) + ",";
      }
      if (iat.length > 0) iat = iat.substr(0, iat.length - 1);
      // 设置产品类型
      let category = undefined;
      if (psId === psVal.ACS_ORTHOPHOTO || psId === psVal.ACS_DEM)
        category = "几何";
      else if (
        psId === psVal.ACS_BACKSCATTERINGCOEFFICIENT ||
        psId === psVal.ACS_ATMOSPHERICDELAYCORRECTION
      )
        category = "辐射";
      else if (
        psId === psVal.ACS_GROUNDLEAFAREAINDEX ||
        psId === psVal.ACS_VEGETATIONPHENOLOGY ||
        psId === psVal.ACS_GROUNDVEGETATIONHEIGHT
      )
        category = "植被";
      else category = "陆表";
      const pdfMsg = {
        category: category,
        categoryType: productTypeSplMap(self.pdSubType),
        product: productTypeMap(self.pdSubType),
        orderID: asmo.orderCode,
        reportMaker: rpm.userName,
        orderCreateTime: asmo.createDate,
        orderStartTime: crTime.startTime,
        orderEndTime: crTime.endTime,
        reportCreateTime: asmo.createDate,
        inspectorName: rpm.userName,
        productFileName: asmp.fileName,
        resolution: asmm.resRatio + "",
        productCreateTime: asmp.collectDate,
        coordinatSeystem: asmm.coordinateSys,
        sampleTimeRequest: asmo.queryStartTime + "  -  " + asmo.queryEndTime,
        sampleType: "点",
        sampleCount: rpm.sampleList.length + "",
        // areaLeftUp: asmm.minLon + "," + asmm.maxLat,
        // areaRightDown: asmm.maxLon + "," + asmm.minLat,
        minLon: asmm.minLon + "",
        maxLon: asmm.maxLon + "",
        minLat: asmm.minLat + "",
        maxLat: asmm.maxLat + "",
        inspectionAlgorithm: iat,
        sampleList: JSON.stringify(rpm.sampleList),
        inspectionResultList: iatResArr,
        imgData: this.base64Data,
        errorList: errorList,
        realList: realList,
        otgError: otgError,
        sampleImgFd: rpm.imgRes.sampleImgFd,
        sampleImg: rpm.imgRes.sampleImg,
        productImg: rpm.imgRes.productImg,
        microwaveDataJson: asmp.microwaveDataJson,
        satellite: asmm.satellite,
        load: asmm.load,
        pixelHandleMsg:rpm.pixelHandleMsg,
        projStr:rpm.projStr,
        sampleFun:rpm.sampleFun
      };
      const pdfName = productTypeMap(self.pdSubType) + "报告";
      exportWord(
        pdfMsg,
        pdfName,
        psId
      ).then((res) => {
        if (res.msg === "success") {
          const ru = res.pdfUrl;
          const pos = ru.lastIndexOf("/");
          const pdfName = ru.substr(pos + 1);
          self.pdfPath = this.configration.urlprefix.pdfUrlPrefix + pdfName;
          self.pdfLoading = false;
        }
      });
    },
    // 下载报告
    downloadReport() {
      const pdfPath = this.pdfPath;
      if (pdfPath !== null || pdfPath !== undefined) {
        const pdfName = pdfPath.substr(pdfPath.lastIndexOf("/") + 1); //截取文件名称字符串
        downloadPdf(pdfPath).then((res) => {
          if (res.size > 0) {
            const content = res;
            const blob = new Blob([content]);
            const fileName = pdfName;
            if ("download" in document.createElement("a")) {
              // 非IE下载
              const elink = document.createElement("a");
              elink.download = fileName;
              elink.style.display = "none";
              elink.href = URL.createObjectURL(blob);
              document.body.appendChild(elink);
              elink.click();
              URL.revokeObjectURL(elink.href); // 释放URL 对象
              document.body.removeChild(elink);
            } else {
              // IE10+下载
              navigator.msSaveBlob(blob, fileName);
            }
          }
        });
      }
    },
    // 提交检验结果以及报告结果
    submitReport() {
      // saveValidationRes(this.reportMsg).then((res) => {
      // if (res.code === 200) {
      //   this.$message({
      //     message: "提交成功，检验完成",
      //     type: "success",
      //   });
      const os = 2; //审核完成
      this.updateOrder(os);
      // 上传报告
      const rpm = this.reportMsg;
      const pp = this.pdfPath;
      if (pp !== null || pp !== undefined) {
        const rpMsg = {
          orderId: rpm.orderId,
          path: pp,
        };
        saveReport(rpMsg).then((res) => {
          if (res.code === 200) {
            this.$message({
              type: "success",
              message: "订单处理成功",
            });
            window.location.href = `${DAICHULI_URL}?token=${rpm.token}`;
          }
        });
      }
      // }
      // });
    },
    // 重新检验
    reExamine() {
      const os = 0;
      this.updateOrder(os);
      resetCheck({ orderId: this.reportMsg.orderId }).then((res) => {
        if (res.code === 200) {
          window.location.href = `${DAICHULI_URL}?&token=${this.reportMsg.token}`;
        }
      });
    },
    // 更新订单状态
    updateOrder(orderStatus) {
      updateOrderStage(
        qs.stringify(
          {
            orderId: this.reportMsg.orderId,
            orderStatus: orderStatus,
            userId: this.reportMsg.userId,
          },
          { indices: false }
        )
      );
    },
    pickValue() {
      cu.handleClick();
    },
  },
  computed: {
    formatDateStr: function () {
      let inputTime = this.rpDataMsg.date;
      if (!inputTime) {
        //&& typeof inputTime !== 'number'){
        return "";
      }
      var localTime = "";
      inputTime = new Date(inputTime).getTime();
      const offset = new Date().getTimezoneOffset();
      localTime = new Date(inputTime - offset * 60000).toISOString();
      localTime = localTime.substr(0, localTime.lastIndexOf("."));
      localTime = localTime.replace("T", " ");
      return localTime;
    },
  },
};
</script>

<style scoped lang="less">
.rpHeader {
  height: 1000px;
  margin-bottom: 10px;
}

.rphLeft {
  width: calc(50% - 5px);
  height: 100%;
  float: left;
  margin-right: 5px;
}

.rphRight {
  width: 50%;
  height: 100%;
  float: left;
  background-color: white;
}

.pdfContent {
  background-color: #343537;
  height: calc(100% - 60px);
  margin: 10px;
  border: 1px solid #343537;

  .pdfPage {
    width: 100%;
    height: 100%;
  }
}

.rpShow {
  padding-top: 20px;
  background-color: white;
  width: 100%;
  height: 650px;

  .earth {
    width: 98%;
    height: 400px;
    background-color: darkblue;
    margin-left: 1%;
    margin-bottom: 10px;
  }
}

.rpBottom {
  position: relative;
  display: block;
  margin-top: 20px;
  text-align: center;
}

/deep/.rpBottom {
  .el-button--primary {
    width: 170px;
    height: 35px;
    margin-bottom: 20px;
    background-color: #354595;
    margin-left: 10px;
    border-color: #354595;
  }
}

.box1 {
  height: 40px;
  line-height: 40px;
  border-bottom: 1px solid rgb(205, 205, 205, 0.5);
}

.sp1 {
  display: inline-block;
  width: 7px;
  height: 26px;
  background-color: #354595;
  vertical-align: top;
  margin-left: 20px;
  margin-top: 8px;
}

.sp2 {
  margin-left: 10px;
  font-size: 20px;
  font-weight: 700;
  color: #354595;
  vertical-align: top;
}

.cstop {
  margin-top: 20px;
  margin-bottom: 0;
  position: relative;
  text-align: center;
}

.ysjMsg {
  width: 18%;
}

.ysjMsgMrg {
  margin-left: 14px;
}

.ysjMsg2 {
  width: 20%;
}

/deep/.cstop .el-input.is-disabled .el-input__inner {
  width: 140px;
  height: 33px;
}

/deep/.cstop .el-form--inline .el-form-item__label {
  text-align: justify;
  // text-align-last: justify;
  font-size: 15px;
}

/deep/.cstop .el-radio {
  margin-right: 10px;
}

/deep/.cstop .el-radio__inner::after {
  background-color: #354595;
}

/deep/.cstop .el-radio__input.is-checked .el-radio__inner {
  border-color: #354595;
  background: white;
}

/deep/.cstop .el-radio__input.is-disabled .el-radio__inner {
  border-color: #354595;
}

/deep/.cstop .el-radio__input.is-disabled.is-checked .el-radio__inner::after {
  background-color: #354595;
}

/deep/.cstop .el-radio__input.is-checked+.el-radio__label {
  color: #606266;
}

/deep/.cstop .el-radio__inner {
  border: 2px solid #354595;
}

// /deep/.el-input.is-disabled .el-input__inner {
//   width: 120px;
// }
// /deep/.el-form--inline .el-form-item__label {
//   // width: 90px;
//   text-align: justify;
//   // text-align-last: justify;
//   font-size: 14px;
//   margin-left: 15px;
//   padding: 0 5px 0 0;
// }
/deep/.el-tabs__item:hover {
  color: black;
}

/deep/.el-tabs--card>.el-tabs__header .el-tabs__item.is-active {
  color: white;
  background-color: #409eff;
  border-color: #409eff;
}

/deep/.el-tabs__nav-scroll {
  text-align: center;
  margin-bottom: 10px;
  //   display: block;
}

/deep/.el-tabs--card>.el-tabs__header .el-tabs__nav {
  display: block;
  left: 41.5%;
  // transform: translateX(-50%);
  // margin: 0 auto;
  //   text-align: center;
  position: relative;
}

/deep/.el-tabs--card>.el-tabs__header {
  border-bottom: 0;
  // border-bottom: 1px solid #E4E7ED;
}

/deep/.el-tabs--card>.el-tabs__header .el-tabs__nav {
  border-bottom: 1px solid #e4e7ed;
}
</style>
