<!--
 * @Author: ysh
 * @Date: 2025-01-09 15:51:01
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2025-01-22 13:43:34
-->
<template>
  <div>
    <!-- <el-row :gutter="20">
      <el-col :span="12">
        <el-form-item label="项目范围kml">
          <div style="display: flex">
            <div style="width: 100%;">
              <el-input v-model="kmlFileName" disabled placeholder="请选择kml文件"></el-input>
            </div>
            <div>
              <el-upload ref="uploadProKml" class="upload-demo" :headers="upload.headers" :auto-upload="false" action=""
                :on-success="successUploadProKml" accept=".kml" :on-change="handleKmlUploadChange"
                :show-file-list="false">
                <el-button type="primary" icon="el-icon-plus"></el-button>
              </el-upload>
            </div>
          </div>
          <div v-if="position.length != 0" class="centerBox">
            <div>项目点位经纬度：</div>
            <div>
              <el-tag>{{ position[0] }}</el-tag>- <el-tag>{{ position[1] }}</el-tag>
            </div>
          </div>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="项目控制点kml">
          <div style="display: flex;">
            <div style="width: 100%;">
              <el-input v-model="cpFileName" disabled placeholder="请选择kml文件"></el-input>
            </div>
            <div>
              <el-upload ref="uploadProCPKml" class="upload-demo" :headers="upload.headers" :auto-upload="false"
                action="" :on-success="successUploadProKml" accept=".kml" :on-change="handleCpUploadChange"
                :show-file-list="false">
                <el-button type="primary" icon="el-icon-plus"></el-button>
              </el-upload>
            </div>
          </div>
        </el-form-item>
      </el-col>
    </el-row> -->
    <el-form-item label="成果列表">
      <el-row style="margin-bottom: 10px;" v-if="taskName == '成果归档'">
        <el-button type="primary" size="mini" icon="el-icon-plus" @click="handleAddAchievement"
          v-hasPermi="['file:achievement:add']">新增成果</el-button>
        <el-button type="warning" size="mini" icon="el-icon-upload" @click="uploadAchievement"
          v-hasPermi="['file:achievement:add']">上传成果表</el-button>
      </el-row>
      <el-table :data="achiTableData" style="width: 100%" stripe v-loading="loading" :row-key="getRowKeys">
        <el-table-column type="index" label="序号" width="50px" align="center" />
        <el-table-column prop="projectNumber" label="项目编号" align="center" />
        <el-table-column prop="achiName" label="成果名称" width="200px" align="center" />
        <el-table-column prop="dataYear" label="数据年份" align="center"></el-table-column>
        <el-table-column prop="resultType" label="成果类型" align="center">
          <template slot-scope="scope">
            {{ selectDictLabel(dict.type.cmc_achi_type, scope.row.resultType) }}
          </template>
        </el-table-column>
        <el-table-column prop="scaleGrade" label="比例尺或等级" align="center">
          <template slot-scope="scope">
            {{ selectDictLabel(dict.type.cmc_scale_grade, scope.row.scaleGrade) }}
          </template>
        </el-table-column>
        <el-table-column prop="fileType" label="文件类型" align="center" />
        <el-table-column prop="workLoad" label="工作量" align="center" />
        <el-table-column prop="unit" label="单位" align="center" />
        <el-table-column prop="dataSource" label="数据来源" align="center" />
        <el-table-column prop="dataType" label="数据类型" align="center" />
        <el-table-column prop="storageAddress" label="存储地址" align="center" />
        <!-- <el-table-column prop="kmlUrl" label="KML地址" align="center" /> -->
        <el-table-column label="有无KML" align="center" :formatter="formatterKmlurl"></el-table-column>
        <el-table-column prop="remark" label="备注" align="center" />
        <el-table-column label="操作" fixed="right" align="center" width="100" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button type="text" icon="el-icon-edit-outline" @click="handleUpdate(scope.row)"
                v-hasPermi="['file:achievement:edit']">
              </el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                v-hasPermi="['file:achievement:remove']">
              </el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
        @pagination="getAchiList" />
    </el-form-item>

    <!-- 用户上传excel -->
    <el-dialog title="导入成果列表" :visible.sync="achiUpload.open" width="400px">
      <el-upload ref="uploadRef" accept=".xlsx, .xls" :headers="achiUpload.headers" :action="achiUpload.url"
        :disabled="achiUpload.isUploading" :on-progress="handleFileUploadProgress" :on-change="handleFileUploadChange"
        :on-success="handleFileSuccess" :auto-upload="false" drag v-loading="uploadLoading"
        element-loading-text="正在上传，请稍等">
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <div class="el-upload__tip text-center">
            <span>仅允许导入xls、xlsx格式文件。</span>
            <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;"
              @click="importTemplate">下载模板</el-link>
          </div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitUpload">确 定</el-button>
          <el-button @click="achiUpload.open = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog title="新增成果" :visible.sync="addOpen" width="50%">
      <add-achi :project="project" :isFlow="true" @getList="getAchiList" @cancel="addOpen = false"></add-achi>
    </el-dialog>
    <el-dialog title="修改成果" :visible.sync="modifyOpen" width="50%">
      <modify-achi :modifyForm="modifyForm" :isFlow="true" :isModify="true" @getList="getAchiList"
        @cancel="modifyOpen = false"></modify-achi>
    </el-dialog>
  </div>
</template>

<script>
import { saveAs } from 'file-saver';
import { cloneDeep } from "lodash";
import { getToken } from "@/utils/auth";
import { listType } from '@/api/system/dict/type'
import { getProject, downloadTemplate } from "@/api/file/project";
import { listAchievement, uploadAchievementSheet, addAchievement, updateAchievement, delAchievement } from "@/api/file/achievement";
import addAchi from '../../file/components/addAchi.vue';
import ModifyAchi from '../../file/components/modifyAchi.vue';
export default {
  components: { addAchi,ModifyAchi },
  dicts: ['cmc_achi_type', 'cmc_scale_grade'],
  props: {
    project: {
      type: Object,
      require: true
    },
    taskName:{
      type:String,
    }
  },
  watch: {
    project: {
      handler(newVal) {
        this.getAchiList();
      },
      immediate: true, // 立即生效
      deep: true  //监听对象或数组的时候，要用到深度监听
    }
  },
  data() {
    return {
      loading: false,
      achiTableData: [],
      kmlfile: undefined,
      cpfile: undefined,
      kmlFileName: "",//范围kml文件的文件名
      cpFileName: "", //控制点文件的文件名
      position: [],
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部'Content-Type': 'multipart/form-data',
        headers: { Authorization: "Bearer " + getToken() },
        data: undefined,
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/file/project/uploadSheet",
        // kml上传地址
        kmlUrl: process.env.VUE_APP_BASE_API + "/file/project/uploadProjectKmlFile",
        // 控制点上传地址
        cpUrl: process.env.VUE_APP_BASE_API + "/file/project/uploadCpKmlFile",
      },
      achiUpload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部'Content-Type': 'multipart/form-data', 
        headers: { 'Authorization': "Bearer " + getToken() },
        data: undefined,
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/file/achievement/uploadSheet"
      },
      uploadLoading: false,
      uploadFormData: undefined,
      fileList: [],
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        id: undefined,
        projectId: undefined,
        projectNumber: undefined,
        achiName: undefined,
        dataYear: undefined,
        scaleGrade: undefined,
        resultType: undefined,
        fileType: undefined,
        kmlUrl: undefined,
        kmlLng: undefined,
        kmlLat: undefined,
        workLoad: undefined,
        unit: undefined,
        dataSource: undefined,
        dataType: undefined,
        storageId: undefined,
        remark: undefined,
      },
      total: 0,
      addOpen: false,
      modifyOpen: false,
      modifyForm: {}
    };
  },
  created() {

  },
  methods: {
    getAchiList() {
      this.queryParams.projectId = this.project.projectId;
      this.loading = true;
      if (this.$store.getters.roles.includes('projectLeader') && !this.$store.getters.roles.includes('leader')) {
        this.queryParams.projectLeader = this.$store.getters.userId
      }
      if(!this.queryParams.projectId){
        this.loading = false;
        return
      }
      listAchievement(this.queryParams).then(res => {
        this.achiTableData = res.rows;
        this.total = res.total;
        this.loading = false;
      })
    },
    /* 新增成果 */
    handleAddAchievement() {
      this.addOpen = true
    },
    /* 修改成果按钮 */
    handleUpdate(row) {
      this.modifyForm = cloneDeep(row);
      this.modifyForm.projectNumber = this.modifyForm.projectNumber + '-' + this.modifyForm.projectName;
      this.modifyOpen = true;
    },
    /* 删除成果 */
    handleDelete(row) {
      const achiIds = row.id;
      const achiName = row.achiName
      this.$modal.confirm('是否确认成果名为"' + achiName + '"的数据项？').then(function () {
        return delAchievement(achiIds);
      }).then(() => {
        this.getAchiList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /* 上传成果 */
    uploadAchievement() {
      this.achiUpload.open = true
    },
    /**Excel文件上传中处理 */
    handleFileUploadProgress(event, file, fileList) {
      this.achiUpload.isUploading = true;
      this.uploadLoading = true;
    },
    /* Excel文件改变时 */
    handleFileUploadChange(file, fileList) {
      if (fileList.length > 1) {
        fileList.splice(0, 1);
      }
      this.uploadFormData = new FormData();
      this.uploadFormData.append("file", file);
      this.achiUpload.data = this.uploadFormData;
    },
    /** Excel文件上传成功处理 */
    handleFileSuccess(response, file, fileList) {
      this.achiUpload.open = false;
      this.achiUpload.isUploading = false;
      this.uploadLoading = false;
      this.fileList = [];
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
      this.$refs["uploadRef"].clearFiles();
      this.getAchiList();
    },
    /* 下载模板 */
    importTemplate() {
      const path = "http://oa.sccehui.com:6200/prod-api/profile/upload/成果归档/cg-template.xlsx"
      downloadTemplate(path).then(res => {
        const blob = new Blob([res])
        saveAs(blob, '成果表模版.xlsx');
      });
    },
    /* Excel上传提交按钮 */
    submitUpload() {
      this.$refs['uploadRef'].submit();
    },
    // ____________项目KML________________
    successUploadProKml(response, file, fileList) {
      this.$refs["uploadProKml"].clearFiles();
      this.$refs["uploadProCPKml"].clearFiles();
      this.$alert(
        "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
        response.msg +
        "</div>",
        "导入结果",
        { dangerouslyUseHTMLString: true }
      );
    },
    /* 只上传一个文件，如果重复上传就替换 */
    handleCpUploadChange(file, fileList) {
      if (fileList.length > 1) {
        fileList.splice(0, 1);
      }
      this.cpFileName = file.name;
      this.cpfile = file.raw
    },
    async handleKmlUploadChange(file, fileList) {
      if (fileList.length > 1) {
        fileList.splice(0, 1);
      }
      this.kmlFileName = file.name;
      this.kmlfile = file.raw;
      let fileReader = new FileReader();
      fileReader.readAsText(this.kmlfile);
      fileReader.onload = async (e) => {
        let result = await this.extractGoogleCoords(e.target.result)
        //Do something with result object here
        if (result.markers.length != 0) {
          let points = result.markers[0];
          this.position.push(points.lng);
          this.position.push(points.lat);
        } else if (result.polygons.length != 0) {
          let polygonCor = result.polygons;
          let center = this.calculateCenter(polygonCor);
          this.position = [];
          this.position.push(center.lng);
          this.position.push(center.lat);
        } else if (result.polylines.length != 0) {
          let center = result.polylines[0];
          this.position = [];
          this.position.push(center[0]);
          this.position.push(center[1]);
        }
      }
    },
    /* 读取kml范围的坐标 */
    extractGoogleCoords(plainText) {
      let parser = new DOMParser();
      let xmlDoc = parser.parseFromString(plainText, "text/xml")
      let googlePolygons = []
      let googleMarkers = []
      let googlePolylines = []
      if (xmlDoc.documentElement.nodeName == "kml") {
        for (const item of xmlDoc.getElementsByTagName('Placemark')) {
          // let placeMarkName = item.getElementsByTagName('name')[0].childNodes[0].nodeValue.trim();
          let polygons = item.getElementsByTagName('Polygon');
          let polylines = item.getElementsByTagName('LineString');
          let markers = item.getElementsByTagName('Point');
          /** POLYGONS PARSE **/
          if (polygons.length != 0) {
            for (const polygon of polygons) {
              let coords = polygon.getElementsByTagName('coordinates')[0].childNodes[0].nodeValue.trim();
              let b = coords.replace(/[\t\f\r\n]/g, '');
              let points = b.split(" ");
              let googlePolygonsPaths = [];
              for (const point of points) {
                if (point != "") {
                  let coord = point.split(",");
                  googlePolygonsPaths.push({ lat: + Number(coord[1]), lng: + Number(coord[0]) });
                }
              }
              googlePolygons = googlePolygonsPaths;
            }
          }

          /* line  */
          if (polylines.length != 0) {
            let coords = polylines[0].getElementsByTagName('coordinates')[0].childNodes[0].nodeValue.trim();
            let points = coords.split(" ");
            let polylinesList = [];
            for (const p of points) {
              let coord = p.split(",");
              polylinesList.push([Number(coord[0]), Number(coord[1])])
            }
            let midLen = parseInt(polylinesList.length / 2);
            googlePolylines.push(polylinesList[midLen]);
          }
          if (markers.length != 0) {
            for (const marker of markers) {
              var coords = marker.getElementsByTagName('coordinates')[0].childNodes[0].nodeValue.trim()
              let coord = coords.split(",")
              googleMarkers.push({ lat: +coord[1], lng: +coord[0] })
            }
          }
        }
      } else {
        this.$modal.msgError('无效的KML文件');
        this.position = [];
        throw "error while parsing"
      }
      return { markers: googleMarkers, polygons: googlePolygons, polylines: googlePolylines }
    },
    calculateCenter(lnglatarr) {
      var total = lnglatarr.length;
      var X = 0, Y = 0, Z = 0;
      lnglatarr.forEach((lnglat) => {
        var lng = lnglat.lng * Math.PI / 180;
        var lat = lnglat.lat * Math.PI / 180;
        var x, y, z;
        x = Math.cos(lat) * Math.cos(lng);
        y = Math.cos(lat) * Math.sin(lng);
        z = Math.sin(lat);
        X += x;
        Y += y;
        Z += z;
      });
      X = X / total;
      Y = Y / total;
      Z = Z / total;
      var Lng = Math.atan2(Y, X);
      var Hyp = Math.sqrt(X * X + Y * Y);
      var Lat = Math.atan2(Z, Hyp);
      return { lng: Lng * 180 / Math.PI, lat: Lat * 180 / Math.PI };
    },
    // 获取表格的row-key,
    getRowKeys(row) {
      return row.id;
    },
    formatterKmlurl(row, cloumn) {
      if (row.kmlUrl == "" || row.kmlUrl == null) {
        return "无";
      } else {
        return "有";
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.centerBox {
  border: 1px dashed #bccfec;
  padding: 5px;
}
</style>
