<template>
  <div>
    <!-- 搜索栏 -->
    <el-row>
      <el-form :model="queryParams" ref="queryRef" :inline="true" label-width="90px">
        <el-form-item label="项目编号" prop="projectNumber">
          <el-input v-model="queryParams.projectNumber" placeholder="请输入项目编号" clearable @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="项目名称" prop="projectName">
          <el-input v-model="queryParams.projectName" placeholder="请输入项目名称" clearable @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="项目负责人" prop="projectLeader" v-hasRole="['archive','leader']">
          <el-select v-model="queryParams.projectLeader" filterable clearable @change="handleQuery">
            <el-option v-for="item in $store.state.user.userList" :key="item.userId" :label="item.nickName"
              :value="item.userId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>

        </el-form-item>
      </el-form>
    </el-row>
    <!-- 操作栏 -->
    <el-row>
      <!-- <el-button type="primary" size="small" icon="el-icon-plus" @click="handleAddProject"
        v-hasPermi="['oa:archive:add']">新增项目</el-button> -->
      <el-button type="success" size="small" icon="el-icon-download" @click="handleExport"
        v-hasPermi="['oa:archive:export']">导出</el-button>
      <!-- <el-button type="warning" size="small" icon="el-icon-upload" @click="uploadProject"
        v-hasPermi="['oa:archive:add']">上传项目表</el-button> -->
      <!-- <el-button type="danger" size="small" icon="el-icon-delete" :disabled="multiple" @click="handleDeleteMany"
        v-hasPermi="['oa:archive:remove']">批量删除</el-button> -->
    </el-row>
    <!-- 项目表格 -->
    <el-row>
      <el-table :data="projectTableData" style="width: 100%" stripe v-loading="loading" :row-key="getRowKeys"
        @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="50px" :reserve-selection="true" />
        <el-table-column prop="isFinished" label="项目状态" align="center">
          <template #default="scope">
            <el-tag :type="scope.row.isFinished === '1' ? 'warning' : 'success'" disable-transitions>{{
              scope.row.isFinished
                === "1" ? '已结束' : '正在进行'
              }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="projectNumber" label="项目编号" align="center" />
        <el-table-column prop="projectName" label="项目名称" width="200px" align="center" />
        <el-table-column prop="projectLeader" label="项目负责人" align="center" >
          <template #default="scope">
            <span>{{ getUserName(scope.row.projectLeader) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="partyA.partyAName" label="甲方单位" align="center" />
        <el-table-column prop="undertakingDeptName" label="承担部门" align="center" />
        <el-table-column label="有无范围KML" align="center" :formatter="formatterKmlurl" />
        <el-table-column label="有无控制点" align="center" :formatter="formatterCpKmlurl" />
        <el-table-column label="操作" align="center" width="150" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="详情" placement="top">
              <el-button type="text" icon="View" @click="handleLook(scope.row)" v-hasPermi="['file:achievement:query']">
              </el-button>
            </el-tooltip>
            <el-tooltip content="成果" placement="top">
              <el-button type="text" icon="Document" @click="handleLookAchi(scope.row)"
                v-hasPermi="['file:achievement:query']">
              </el-button>
            </el-tooltip>
            <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="getProList" />
    </el-row>
    <!-- 项目新增 -->
    <el-dialog :title="title" :visible.sync="addModifyOpen" width="60%" append-to-body>
      <el-form :model="form" ref="projectRef" label-width="130px" :rules="rules">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="项目编号" prop="projectNumber">
              <el-input v-model="form.projectNumber" placeholder="请输入项目编号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="项目名称" prop="projectName">
              <el-input v-model="form.projectName" placeholder="请输入项目名称" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="项目负责人" prop="projectLeader">
              <el-input v-model="form.projectLeader" placeholder="请输入项目负责人" />
            </el-form-item>
          </el-col>
          <!-- <el-col :span="12">
            <el-form-item label="存放地址" prop="storageAddress">
              <el-select v-model="form.storageAddress" placeholder="请选择" filterable allow-create clearable>
                <el-option v-for="item, index in storageList" :key="index" :label="item.storageAddress"
                  :value="item.storageAddress" />
              </el-select>
            </el-form-item>
          </el-col> -->
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="范围kml" prop="projectKml">
              <div style="display: flex;">
                <div>
                  <el-input v-model="kmlFileName" disabled placeholder="请选择kml文件"></el-input>
                </div>
                <div>
                  <el-upload ref="uploadProKml" class="upload-demo" :headers="upload.headers" action=""
                    :auto-upload="false" :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" prop="projectCp">
              <div style="display: flex;">
                <div>
                  <el-input v-model="cpFileName" disabled placeholder="请选择kml文件"></el-input>
                </div>
                <div>
                  <el-upload ref="uploadProCPKml" class="upload-demo" :headers="upload.headers" action=""
                    :auto-upload="false" :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>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitProForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 项目修改 -->
    <el-dialog :title="title" :visible.sync="modifyOpen" width="60%" append-to-body>
      <el-form :model="modifyForm" ref="projectModifyRef" label-width="130px" :rules="modifyRules">
        <el-row :gutter="20">
          <!-- <el-col :span="12">
            <el-form-item label="项目是否结束" prop="isFinished">
              <el-switch :disabled="true" v-model="modifyForm.isFinished" class="ml-2" inline-prompt
                style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949" active-text="是" inactive-text="否"
                active-value="1" inactive-value="0" />
            </el-form-item>
          </el-col> -->
          <el-col :span="12">
            <el-form-item label="项目编号" prop="projectNumber">
              <el-input :disabled="true" v-model="modifyForm.projectNumber" placeholder="请输入项目编号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="项目名称" prop="projectName">
              <el-input :disabled="true" v-model="modifyForm.projectName" placeholder="请输入项目名称" />
            </el-form-item>
          </el-col>
        </el-row>
        <!-- <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="项目负责人" prop="projectLeader">
              <el-input :disabled="true" v-model="modifyForm.projectLeader" placeholder="请输入项目负责人" />
            </el-form-item>
          </el-col>
        </el-row> -->
        <!-- <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="存放地址" prop="storageAddress">
              <el-select v-model="modifyForm.storageAddress" placeholder="请选择" filterable allow-create clearable
                style="width: 100%;">
                <el-option v-for="item, index in storageList" :key="index" :label="item.storageAddress"
                  :value="item.storageAddress" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row> -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="范围kml" prop="projectKml">
              <div style="display: flex;">
                <div style="width: 100%;">
                  <el-input v-model="kmlFileName" v-if="isUpdate" placeholder="请选择kml文件"></el-input>
                </div>
                <div>
                  <el-upload ref="uploadProKml" class="upload-demo" :headers="upload.headers" action=""
                    :auto-upload="false" :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" prop="projectCp">
              <div style="display: flex;">
                <div style="width: 100%;">
                  <el-input v-model="cpFileName" v-if="isUpdate" placeholder="请选择kml文件"></el-input>
                </div>
                <div>
                  <el-upload ref="uploadProCPKml" class="upload-demo" :headers="upload.headers" action="l"
                    :auto-upload="false" :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>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitModifyForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 查看项目详情 -->
    <el-dialog :title="title" v-model="openProject" width="80%" append-to-body>
      <el-descriptions title="" :column="4" border>
        <el-descriptions-item label="项目编号">{{ curProject.projectNumber }}</el-descriptions-item>
        <el-descriptions-item label="项目名称">{{ curProject.projectName }}</el-descriptions-item>
        <el-descriptions-item label="项目负责人">{{ curProject.projectLeader }}</el-descriptions-item>
        <el-descriptions-item label="项目类型">{{ curProject.projectType }}</el-descriptions-item>
        <el-descriptions-item label="甲方单位">{{ curProject.partyA }}</el-descriptions-item>
        <el-descriptions-item label="联系人">{{ curProject.contactPerson }}</el-descriptions-item>
        <el-descriptions-item label="联系电话">{{ curProject.telephone }}</el-descriptions-item>
        <el-descriptions-item label="项目来源">{{ curProject.projectSource }}</el-descriptions-item>
        <el-descriptions-item label="合同编码">{{ curProject.contractCode }}</el-descriptions-item>
        <el-descriptions-item label="合同编号">{{ curProject.contractNumber }}</el-descriptions-item>
        <el-descriptions-item label="预计价款">{{ curProject.expectedPrice }}</el-descriptions-item>
        <el-descriptions-item label="项目级别">{{ curProject.projectLevel }}</el-descriptions-item>
        <el-descriptions-item label="技术负责人">{{ curProject.technicalDirector }}</el-descriptions-item>
        <el-descriptions-item label="技术设计人">{{ curProject.techinicalDesigner }}</el-descriptions-item>
        <el-descriptions-item label="质量检查员">{{ curProject.qualityInspector }}</el-descriptions-item>
        <el-descriptions-item label="承担部门">{{ curProject.undertakingSector }}</el-descriptions-item>
        <el-descriptions-item label="经费合计">{{ curProject.fund }}</el-descriptions-item>
        <el-descriptions-item label="领导批准时间">{{ curProject.approvalDate }}</el-descriptions-item>
        <el-descriptions-item label="进场时间">{{ curProject.approachTime }}</el-descriptions-item>
        <el-descriptions-item label="撤场时间">{{ curProject.withdrawalTime }}</el-descriptions-item>
        <el-descriptions-item label="项目要求完成日期">{{ curProject.requiredCompletionDate }}</el-descriptions-item>
        <el-descriptions-item label="资料提交日期">{{ curProject.submissionDate }}</el-descriptions-item>
        <el-descriptions-item label="使用车辆">{{ curProject.licensePlateNumber }}</el-descriptions-item>
        <el-descriptions-item label="项目行车公里数">{{ curProject.mileage }}</el-descriptions-item>
        <el-descriptions-item label="项目燃油使用费">{{ curProject.fuelExpense }}</el-descriptions-item>
        <el-descriptions-item label="主要设备">{{ curProject.mainEquipment }}</el-descriptions-item>
        <el-descriptions-item label="项目参与人员">{{ curProject.projectParticipants }}</el-descriptions-item>
        <el-descriptions-item label="当前处理环节">{{ curProject.currentProcessing }}</el-descriptions-item>
        <el-descriptions-item label="当前处理人">{{ curProject.currentHandler }}</el-descriptions-item>
        <el-descriptions-item label="项目登记人">{{ curProject.projectRegistrant }}</el-descriptions-item>
        <el-descriptions-item label="项目登记日期">{{ curProject.registrationDate }}</el-descriptions-item>
        <el-descriptions-item label="牵头部门">{{ curProject.leadingSector }}</el-descriptions-item>
        <!-- <el-descriptions-item label="存储地址">{{ curProject.storageAddress }}</el-descriptions-item> -->
        <el-descriptions-item label="项目kml">{{ curProject.projectKml }}</el-descriptions-item>
        <el-descriptions-item label="项目控制点">{{ curProject.projectCp }}</el-descriptions-item>
      </el-descriptions>
    </el-dialog>
    <!-- 查看项目对应的成果信息 -->
    <el-dialog :title="title" v-model="open" width="80%" append-to-body>
      <el-table :data="proAchiTable" style="width: 100%" stripe v-loading="dialogLoading" border>
        <el-table-column type="index" label="序号" width="50px" align="center" />
        <el-table-column prop="achiName" label="成果名称" align="center" width="200px" />
        <el-table-column prop="dataYear" label="数据年份" align="center" />
        <el-table-column prop="scaleGrade" label="比例尺或等级" align="center" />
        <el-table-column prop="resultType" label="成果类型" align="center" />
        <el-table-column prop="fileType" label="文件类型" align="center" />
        <el-table-column prop="kmlUrl" label="KML地址" 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="submitDate" label="提交时间" align="center" />
      </el-table>
    </el-dialog>

    <!-- 用户上传excel -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px">
      <el-upload ref="uploadProRef" accept=".xlsx, .xls" :headers="upload.headers" :action="upload.url"
        :disabled="upload.isUploading" :on-progress="handleFileUploadProgress" :on-change="handleFileUploadChange"
        :on-success="handleFileSuccess" :auto-upload="false" drag v-loading="uploadLoading"
        element-loading-text="正在上传，请稍等">
        <el-icon class="el-icon--upload">
          <upload-filled />
        </el-icon>
        <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="upload.open = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { listProject, getProject, delProject, addProject, updateProject, uploadProjectKml, uploadProjectSheet } from "@/api/file/project";
import { getAchievementByProject } from "@/api/file/achievement";
import { listStorage } from "@/api/file/storage"
import { getToken } from "@/utils/auth";
/* ------------------------------------------------------------------------------------------------------------ */
export default {
  nam: "Project",
  data() {
    return {
      projectTableData: [],
      proAchiTable: [],
      multiple: true,
      ids: [],
      storageList: [], //存储列表
      loading: true,
      dialogLoading: true,
      total: 0,
      title: "",
      open: false,
      addModifyOpen: false,
      modifyOpen: false,
      openProject: false,
      position: [],
      uploadLoading: false, //上传loading
      fileList: [],  //上传文件列表
      isUpdate: false,//控制是否看得到kml地址，初始看不到
      kmlFileName: "",//范围kml文件的文件名
      cpFileName: "", //控制点文件的文件名
      form: {},
      modifyForm: {},
      curProject: {},
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        projectNumber: null,
        projectName: null,
        currentProgress: null,
        projectSource: null,
        partyA: null,
        contactPerson: null,
        telephone: null,
        contractCode: null,
        contractNumber: null,
        projectType: null,
        expectedPrice: null,
        projectLevel: null,
        technicalDirector: null,
        techinicalDesigner: null,
        qualityInspector: null,
        undertakingSector: null,
        projectLeader: null,
        fund: null,
        approvalDate: null,
        approachTime: null,
        withdrawalTime: null,
        requiredCompletionDate: null,
        submissionDate: null,
        licensePlateNumber: null,
        mileage: null,
        fuelExpense: null,
        mainEquipment: null,
        projectParticipants: null,
        currentProcessing: null,
        currentHandler: null,
        projectRegistrant: null,
        registrationDate: null,
        leadingSector: null,
        storageId: null,
        uploadProjectKmlFile: null,
        uploadCpKmlFile: null
      },
      rules: {
        projectNumber: [{ required: true, message: "项目编号不能为空", trigger: "blur" }],
        projectName: [{ required: true, message: "项目名称不能为空", trigger: "blur" }],
        projectLeader: [{ required: true, message: "项目负责人不能为空", trigger: "blur" }],
      },
      modifyRules: {
        projectNumber: [{ required: true, message: "项目编号不能为空", trigger: "blur" }],
        projectName: [{ required: true, message: "项目名称不能为空", trigger: "blur" }],
        // projectLeader: [{ required: true, message: "项目负责人不能为空", trigger: "blur" }],
      },
      /*** 用户导入参数 */
      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",
      },
      uploadFormData: undefined,
      uploadKmlData: undefined,
      kmlfile: undefined,
      cpfile: undefined,
    }
  },
  created() {
    this.getProList();
    this.getStorageList();
  },
  /* ------------------------------------------------------------------------------------------------------------ */
  /* 获取项目列表 */
  methods: {
    async getProList() {
      this.loading = true;
      if (this.$store.getters.roles.includes('projectLeader') && !this.$store.getters.roles.includes('leader')) {
        this.queryParams.projectLeader = this.$store.getters.userId
      }
      listProject(this.queryParams).then(res => {
        this.projectTableData = res.rows;
        this.total = res.total;
        this.loading = false;
      })
    },
    /* 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getProList();
    },
    /* 获取对应项目的成果列表 */
    getAchibyPro(projectId) {
      getAchievementByProject({ projectId }).then(res => {
        this.proAchiTable = res.data;
        this.dialogLoading = false;
      })
    },
    /* 新增项目 */
    handleAddProject() {
      this.reset();
      this.position = [];
      this.addModifyOpen = true;
      this.title = "新增项目";
      this.isUpdate = false;
    },
    // 导出项目表
    handleExport() {
      if (this.multiple) {
        this.download("/file/project/export", { ...this.queryParams }, `项目表_所有数据.xlsx`);
      } else {
        this.download("/file/project/exportBatch/" + this.ids, { ...this.queryParams }, `项目表_${this.ids.length}条.xlsx`);
      }
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.modifyForm = row;
      let leaderObj = this.$store.state.user.userList.find(obj => obj.userId == row.projectLeader);
      if (leaderObj)
        this.modifyForm.projectLeaderName = leaderObj.nickName
      this.modifyOpen = true;
      this.position = [];
      this.kmlFileName = row.projectKml;
      this.cpFileName = row.projectCp;
      this.title = "修改项目KML";
      this.isUpdate = true;
    },
    /* 新增确定按钮 */
    submitProForm() {
      this.uploadKmlData = new FormData();
      this.uploadKmlData.append("kmlfile", this.kmlfile);
      this.uploadKmlData.append("cpfile", this.cpfile);
      this.form.isFinished = '0';
      if (this.kmlfile) {
        this.form.kmlLng = this.position[0];
        this.form.kmlLat = this.position[1];
      }
      this.$refs["projectRef"].validate(valid => {
        if (valid) {
          for (let i in this.form) {
            this.uploadKmlData.append(i, this.form[i] == null ? "" : this.form[i]);
          }
          addProject(this.uploadKmlData).then(response => {
            this.$modal.msgSuccess("新增成功");
            this.addModifyOpen = false;
            this.getProList();
          });
        } else {
          this.$modal.msgError("请完善必填项");
        }
      });
    },
    /* 修改确认按钮 */
    submitModifyForm() {
      this.uploadKmlData = new FormData();
      this.uploadKmlData.append("kmlfile", this.kmlfile);
      this.uploadKmlData.append("cpfile", this.cpfile);
      this.modifyForm.partyA = null
      if (this.position.length != 0) {
        this.modifyForm.kmlLng = this.position[0];
        this.modifyForm.kmlLat = this.position[1];
      }
      this.$refs["projectModifyRef"].validate(valid => {
        if (valid) {
          delete this.modifyForm.params
          // 初始化一个对象来收集要发送的数据  
          const formDataEntries = [];
          // 遍历 modifyForm，收集非空、非对象、非特定跳过的字段  
          for (let key in this.modifyForm) {
            if (key === 'contract' || key === 'partyA' || key.endsWith('User')  || this.modifyForm[key] instanceof Object) {
              continue;
            }

            // 添加字段到 formDataEntries 数组  
            formDataEntries.push([key, this.modifyForm[key] != null ? this.modifyForm[key] : '']);
          }
          // 将收集的数据添加到 FormData  
          formDataEntries.forEach(([key, value]) => {
            this.uploadKmlData.append(key, value);
          });
          // for (let i in this.modifyForm) {
          //   if (i == 'contract' || i == 'partyA') continue
          //   if (this.modifyForm[i] instanceof Object) continue
          //   this.uploadKmlData.append(i, this.modifyForm[i] == null ? '' : this.modifyForm[i]);
          // }
          // return
          updateProject(this.uploadKmlData).then(response => {
            this.$modal.msgSuccess("修改成功");
            this.addModifyOpen = false;
            this.modifyOpen = false;
            this.getProList();
          });
        } else {
          this.$modal.msgError("请完善必填项");
        }
      })
    },
    /** 取消按钮 */
    cancel() {
      this.addModifyOpen = false;
      this.modifyOpen = false;
      this.reset();
      // getProList();
    },
    reset() {
      this.kmlFileName = "";
      this.cpFileName = "";
      this.form = {
        projectNumber: undefined,
        projectName: undefined,
        currentProgress: undefined,
        projectSource: undefined,
        partyA: undefined,
        contactPerson: undefined,
        telephone: undefined,
        contractCode: undefined,
        contractNumber: undefined,
        projectType: undefined,
        expectedPrice: undefined,
        projectLevel: undefined,
        technicalDirector: undefined,
        techinicalDesigner: undefined,
        qualityInspector: undefined,
        undertakingSector: undefined,
        projectLeader: undefined,
        fund: undefined,
        approvalDate: undefined,
        approachTime: undefined,
        withdrawalTime: undefined,
        requiredCompletionDate: undefined,
        submissionDate: undefined,
        licensePlateNumber: undefined,
        mileage: undefined,
        fuelExpense: undefined,
        mainEquipment: undefined,
        projectParticipants: undefined,
        currentProcessing: undefined,
        currentHandler: undefined,
        projectRegistrant: undefined,
        registrationDate: undefined,
        leadingSector: undefined,
        storageId: undefined,
        projectKml: undefined,
        projectCp: undefined,
      };
      this.modifyForm = {
        projectNumber: undefined,
        projectName: undefined,
        currentProgress: undefined,
        projectSource: undefined,
        partyA: undefined,
        contactPerson: undefined,
        telephone: undefined,
        contractCode: undefined,
        contractNumber: undefined,
        projectType: undefined,
        expectedPrice: undefined,
        projectLevel: undefined,
        technicalDirector: undefined,
        techinicalDesigner: undefined,
        qualityInspector: undefined,
        undertakingSector: undefined,
        projectLeader: undefined,
        fund: undefined,
        approvalDate: undefined,
        approachTime: undefined,
        withdrawalTime: undefined,
        requiredCompletionDate: undefined,
        submissionDate: undefined,
        licensePlateNumber: undefined,
        mileage: undefined,
        fuelExpense: undefined,
        mainEquipment: undefined,
        projectParticipants: undefined,
        currentProcessing: undefined,
        currentHandler: undefined,
        projectRegistrant: undefined,
        registrationDate: undefined,
        leadingSector: undefined,
        storageId: undefined,
        projectKml: undefined,
        projectCp: undefined,
      };
      this.resetForm("projectRef");
    },
    /* 上传项目表 */
    uploadProject() {
      this.upload.title = "上传项目表";
      this.upload.open = true;
    },
    /**EXCEL文件上传中处理 */
    handleFileUploadProgress(event, file, fileList) {
      upload.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.upload.data = this.uploadFormData;
    },
    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]);
        }
      }
    },
    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 };
    },
    /* 读取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 }
    },
    /* 只上传一个文件，如果重复上传就替换 */
    handleCpUploadChange(file, fileList) {
      if (fileList.length > 1) {
        fileList.splice(0, 1);
      }
      this.cpFileName = file.name;
      this.cpfile = file.raw
    },
    /* 下载模板 */
    importTemplate() {
      this.download("file/project/importTemplate", {
      }, `项目模板.xlsx`);
    },
    /** EXCEL文件上传成功处理 */
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.uploadLoading = false;
      this.fileList = [];
      this.$refs.uploadProRef.clearFiles();
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
      this.getProList();
    },
    /* 上传提交按钮 */
    submitUpload() {
      this.$refs['uploadProRef'].submit();
    },
    /** 多选框选中数据 */
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.multiple = !selection.length;
    },
    // 返回row 的key
    getRowKeys(row) {
      return row.id;
    },
    /* 查看按钮操作 */
    handleLook(row) {
      let proName = row.projectNumber + '-' + row.projectName;
      this.title = proName;
      this.curProject = row;
      this.openProject = true;
    },
    /* 查看成果按钮 */
    handleLookAchi(row) {
      let proName = row.projectNumber + '——' + row.projectName;
      this.title = proName + '《成果列表》';
      this.open = true;
      getAchibyPro(row.id);
    },

    /* 删除按钮操作 */
    handleDelete(row) {
      const Ids = row.id;
      const projectNumber = row.projectNumber
      this.$modal.confirm('确认删除后项目编号为：' + projectNumber + '下的成果都会被删除，是否确认？').then(() => {
        return delProject(Ids);
      }).then(() => {
        this.$modal.msgSuccess("删除成功");
        this.getProList();
      }).catch(() => { });
    },
    /* 批量删除操作 */
    handleDeleteMany() {
      this.$modal.confirm('是否确认删除？').then(() => {
        return delProject(this.ids);
      }).then(() => {
        this.$modal.msgSuccess("删除成功");
        this.getProList();
      }).catch(() => { });
    },
    /* 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 });
    },
    /* 获取存储地址列表 */
    getStorageList() {
      let queryParams = {
        pageNum: 1,
        pageSize: 99999,
        storageAddress: null,
        administrator: null,
        remark: null
      };
      listStorage(queryParams).then(response => {
        this.storageList = response.rows;
      })
    },
    /* 格式化表格显示 */
    formatterKmlurl(row, cloumn) {
      if (row.projectKml == "" || row.projectKml == null) {
        return "无";
      } else {
        return "有";
      }
    },
    formatterCpKmlurl(row, cloumn) {
      if (row.projectCp == "" || row.projectCp == null) {
        return "无";
      } else {
        return "有";
      }
    },
    formatterProStatus(row, cloumn) {
      if (row.isFinished == "" || row.isFinished == null || row.isFinished == "0") {
        return
      }
    },
  }
}
</script>

<style lang="scss" scoped>
@import "@/assets/styles/element-reset.scss";

.centerBox {
  border: 1px dashed #bccfec;
  padding: 5px;
}
</style>