<template>
  <div>
    <tf-page>
      <template v-slot:action>
        <tf-title>工程列表</tf-title>
        <el-row style="padding-bottom: 10px">
          <el-col :span="12">
            <el-row>
              <el-col></el-col>
            </el-row>
            <span></span>
            <span>工程名称</span>
            <pbs-tree
              :structures="structures"
              @changeProjectName="treeNodeClick"
              style="width: 50%; display: inline-block"
            ></pbs-tree>
            <el-button type="primary" size="mini" @click="getPbsTree">查询</el-button>
          </el-col>
          <el-col :span="6" :offset="6">
            <el-button type="primary" size="mini" @click="publicService">数据发布</el-button>
          </el-col>
        </el-row>
      </template>
      <tf-table
        v-if="!isNewProj"
        highlight-current-row
        @current-change="selectChange"
        class="tabletree"
        :stripe="false"
        row-key="id"
        border
        style="width: 100%"
        :data="tableData"
        :tree-props="{ children: 'children' }"
      >
        <el-table-column prop="name" label="节点名称" width="400" :show-overflow-tooltip="true"> </el-table-column>
        <el-table-column prop="code" label="PBS编码"> </el-table-column>
        <el-table-column prop="levelname" label="类型"> </el-table-column>
        <el-table-column prop="isPublish" label="发布状态">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.isPublish === '1'" type="success">已发布</el-tag>
            <el-tag v-else type="danger">未发布</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="" label="操作">
          <template slot-scope="scope">
            <div
              v-if="
                scope.row.levelname === '工程' ||
                scope.row.levelname === '单项工程' ||
                scope.row.levelname === '单位工程（CWP）'
              "
            >
              <el-button class="tdbutton" size="mini" type="primary" @click="openNewNode(scope.row)">新建</el-button>
              <!-- <i class="el-icon-delete" style="color:red;margin-left:10px;" @click="deleteData(scope.row)"></i> -->
            </div>
            <div v-else-if="scope.row.levelname === '分部工程（专业）'">
              <el-button class="tdbutton" size="mini" type="success" @click="pipeDataImport(scope.row)">导入</el-button>
              <i class="el-icon-delete" style="color: red; margin-left: 10px" @click="deleteData(scope.row)"></i>
            </div>
            <div v-else>
              <el-button class="tdbutton" size="mini" type="primary" @click="openNewNode(scope.row)">新建</el-button>
              <i class="el-icon-delete" style="color: red; margin-left: 10px" @click="deleteData(scope.row)"></i>
            </div>
          </template>
        </el-table-column>
      </tf-table>
      <el-row v-else type="flex" justify="center" align="middle" style="height: 100%; background: #fff">
        <el-button type="primary" @click="addProjectNode">创建项目工程结构树</el-button>
      </el-row>
    </tf-page>
    <tf-dialog :visible.sync="newNodeDialogShow" title="新建下级节点" width="600px">
      <el-form :model="addNodeForm" label-width="140px">
        <el-form-item label="当前节点">
          <el-input v-model="addNodeForm.pName" disabled></el-input>
        </el-form-item>
        <el-form-item label="当前节点PBS编码">
          <el-input v-model="addNodeForm.pCode" disabled></el-input>
        </el-form-item>
        <el-form-item label="下级节点选择">
          <el-select @change="nextNodeChange()" v-model="addNodeForm.id" clearable style="width: 100%">
            <el-option v-for="(item, index) in nodeOptions" :key="index" :label="item.name" :value="item.id">
              <span style="float: left">{{ item.name }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ item.value }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="下级节点PBS编码">
          <el-input v-model="addNodeForm.code" disabled></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" style="text-align: right">
        <el-button type="primary" @click="addNodeSubmit()" size="small">提 交</el-button>
        <el-button @click="newNodeDialogShow = false" size="small">取 消</el-button>
      </div>
    </tf-dialog>
    <tf-dialog
      class="fullDialog"
      title="管线数据导入"
      max-width="100%"
      max-height="calc(100vh - 54px)"
      :fullscreen="true"
      :visible.sync="importDialogShow"
    >
      <el-container style="height: 100%">
        <el-aside width="300px" style="overflow-x: hidden">
          <div>
            <tf-title>成果表选择</tf-title>
            <el-form ref="addForm" :model="impForm" size="mini">
              <el-form-item label="项目工程" prop="prjName" class="impForm" :rules="addRules">
                <!-- <pbs-tree @changeProjectName="treeNodeClick" style="width:100%;"></pbs-tree> -->
                <el-input type="textarea" :rows="3" v-model="impForm.prjName"></el-input>
              </el-form-item>
              <el-form-item label="数据阶段" prop="stage">
                <el-select v-model="impForm.stage" style="width: 100%">
                  <el-option label="设计" value="SJ"></el-option>
                  <!-- <el-option label="普查" value="PC"></el-option>
          <el-option label="竣工" value="JG"></el-option> -->
                </el-select>
              </el-form-item>
              <el-form-item label="成果表">
                <el-upload
                  class="eluploadcontainer"
                  action="none"
                  :file-list="fileList"
                  accept=".xls,.xlsx"
                  multiple
                  :limit="2"
                  :before-remove="onBeforeRemove"
                  :on-remove="onRemove"
                  :on-change="onChange"
                  :auto-upload="false"
                  :on-exceed="onExceed"
                >
                  <el-button slot="trigger" size="small" type="text">本地文件</el-button>
                  <el-button size="small" type="text" @click="OnlineAccess">在线获取</el-button>
                </el-upload>
              </el-form-item>
              <el-form-item>
                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-button type="primary" size="small" style="width: 100%">取消</el-button>
                  </el-col>
                  <el-col :span="12">
                    <el-button type="primary" size="small" style="width: 100%" @click="previewExcel">提交</el-button>
                  </el-col>
                </el-row>
              </el-form-item>
              <!-- <el-form-item>
                <el-button type="primary" style="width:100%" @click="deleteData">删除数据</el-button>
              </el-form-item> -->
            </el-form>
            <tf-dialog title="在线获取数据成果" :visible.sync="dialogVisible" width="80%" top="3%">
              <el-form :inline="true" class="toolbar" size="mini">
                <el-form-item label="所属区域">
                  <el-select v-model="areaName" filterable clearable placeholder="请选择" size="mini">
                    <el-option v-for="item in prjOptions" :key="item.code" :label="item.name" :value="item.value">
                    </el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="项目">
                  <el-select v-model="selectPrjId" filterable clearable placeholder="请选择" size="mini">
                    <el-option v-for="item in optionsoffter" :key="item.key" :label="item.name" :value="item.value">
                    </el-option>
                  </el-select>
                </el-form-item>
                <el-form-item>
                  <el-input v-model="queryPara" clearable placeholder="支持数据名称,上传单位">
                    <el-button
                      type="primary"
                      slot="append"
                      size="mini"
                      icon="el-icon-search"
                      @click="getlist"
                    ></el-button>
                  </el-input>
                  <!-- <el-button type="primary" size="mini" icon="el-icon-search" @click="getlist"></el-button> -->
                </el-form-item>
                <el-form-item label="提交状态">
                  <el-radio-group v-model="radio" @change="getlist">
                    <el-radio label="">全部</el-radio>
                    <el-radio label="1">未提交</el-radio>
                    <el-radio label="0">已提交</el-radio>
                  </el-radio-group>
                </el-form-item>
                <el-form-item>
                  <el-radio-group v-model="radio2" @change="getlist">
                    <el-radio label="">全部</el-radio>
                    <el-radio label="2">设计</el-radio>
                    <el-radio label="1">普查</el-radio>
                    <el-radio label="3">竣工</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-form>
              <!-- 弹出框表单 -->
              <div class="content-body" style="height: 410px">
                <tf-table @page-change="onPageChange" :data="onlineRecords" :pagination="pagination">
                  <template slot="empty">
                    <img src="@/assets/icon/null.png" alt="暂无数据" />
                  </template>
                  <el-table-column prop="id" label="ID" width="100"></el-table-column>
                  <el-table-column prop="areaName" label="所属区域"></el-table-column>
                  <el-table-column prop="fullName" label="项目"></el-table-column>
                  <el-table-column prop="division" label="片区"></el-table-column>
                  <el-table-column prop="batchName" label="数据名称" :show-overflow-tooltip="true"></el-table-column>
                  <el-table-column prop="dataSource" label="数据阶段"></el-table-column>
                  <el-table-column prop="submitStatus" label="提交状态"></el-table-column>
                  <el-table-column
                    prop="detectionUnit"
                    label="上传单位"
                    :show-overflow-tooltip="true"
                  ></el-table-column>
                  <el-table-column prop="updateTime" label="上传时间" width="150px"></el-table-column>
                  <el-table-column label="下载" width="50">
                    <template slot-scope="scope">
                      <el-button type="text" icon="el-icon-download" @click="downLoadFile(scope.row)"></el-button>
                    </template>
                  </el-table-column>
                </tf-table>
              </div>
              <!-- <div class="content-footer">
        <el-pagination class="pagination" @size-change="onPageChange" @current-change="onPageChange" :current-page="pagination.current" :page-sizes="pageSizes" :page-size="pagination.size" layout="total, sizes, prev, pager, next, jumper" :total="pagination.total"></el-pagination>
      </div> -->
            </tf-dialog>
          </div>
        </el-aside>
        <el-main class="impotMain">
          <el-tabs class="pipetable">
            <el-tab-pane label="表格">
              <el-row>
                <el-col :span="8">源数据情况：{{ importInfo }}</el-col>
                <el-col :span="8">预览情况：{{ priviewInfo }}</el-col>
                <el-col :span="8">
                  <el-button type="primary" size="small" @click="buildDatasets">预览</el-button>
                  <el-button type="primary" size="small" @click="zsbuildDatasets">提交</el-button>
                </el-col>
              </el-row>
              <el-tabs style="height: calc(100% - 32px)">
                <el-tab-pane label="点表">
                  <tf-table :columns="impForm.pointColumns" :data="impForm.pointData"></tf-table>
                </el-tab-pane>
                <el-tab-pane label="线表">
                  <tf-table :columns="impForm.lineColumns" :data="impForm.lineData"></tf-table>
                </el-tab-pane>
              </el-tabs>
            </el-tab-pane>
            <el-tab-pane label="地图">
              <div id="viewer" class="cesium_container"></div>
            </el-tab-pane>
          </el-tabs>
        </el-main>
      </el-container>
      <div slot="footer"></div>
    </tf-dialog>
    <tf-dialog title="服务发布" width="600px" :visible.sync="isPublicDialogShow">
      <el-checkbox-group v-model="publicConfig">
        <el-checkbox label="重建三维网络"></el-checkbox>
        <el-checkbox label="发布地图服务" :disabled="true"></el-checkbox>
        <el-checkbox label="更新发布标识" :disabled="!listSelect"></el-checkbox>
      </el-checkbox-group>
      <div slot="footer" style="text-align: right">
        <el-button type="primary" size="small" @click="submitPublicService">确 定</el-button>
        <el-button size="small" @click="isPublicDialogShow = false">取 消</el-button>
      </div>
    </tf-dialog>
  </div>
</template>

<script lang='ts'>
declare global {
  interface Window {
    impViewer: any
  }
}
declare let Cesium

/**
 *@description 该功能为管网数据在线入库
 *@author lishun <876330731@qq.com>
 */
import { Vue, Prop, Watch, Component } from 'vue-property-decorator'
import request, { IP } from '@/utils/request'
import { getDefaultPagination } from '@/utils/constant'
import {
  pbsTreeListwithPublish,
  getStructureDetailByID,
  getPbsLevelByID,
  getPbsLevelPage,
  getBoinfoPage,
  getPbsCodeDetailPage,
  addStrctureNode
} from '@/api/APIs'
import { pageSizes } from '@/utils/constant'
import { IPagination } from '@/api/common'
import PbsTree from '../DataImport/components/PbsTree.vue'
import BaseConfig from '@/config/configure'

@Component({
  name: 'PipeOnlineImprt',
  components: { PbsTree }
})
export default class PipeOnlineImprt extends Vue {
  impForm = {
    id: null, //pbs结构id
    prjName: '',
    stage: 'SJ',
    paperName: '',
    paperUnit: '',
    paperPerson: '',
    origin: '',
    pointColumns: [],
    lineColumns: [],
    pointData: [],
    lineData: []
  }
  /**是否创建新项目 */
  isNewProj = false
  /**服务发布对话框 */
  isPublicDialogShow = false
  /**发布服务选项 */
  publicConfig = []
  /**新建下级节点弹框显隐 */
  newNodeDialogShow = false
  /**导入弹框显隐控制 */
  importDialogShow = false
  /**下级节点列表 */
  nodeOptions = []
  /**下级节点连接符 */
  connector = ''
  tableData = []
  pageSizes = pageSizes
  addNodeForm = {
    pid: '',
    pName: '',
    pCode: '',
    id: '',
    code: '',
    name: '',
    nextCode: ''
  }
  /**表格树勾选项 */
  listSelect = null
  addRules = {
    prjName: [{ required: true, message: '请选择单位工程', trigger: 'blur' }],
    stage: [{ required: true, message: '请选择数据阶段', trigger: 'change' }],
    paperName: [{ required: true, message: '请输入图纸名称', trigger: 'blur' }],
    paperUnit: [{ required: true, message: '请输入图纸提供单位', trigger: 'blur' }],
    paperPerson: [{ required: true, message: '请输入图纸提供人', trigger: 'blur' }]
  }
  importInfo = ''
  priviewInfo = ''
  /**
   * 搜索PBS结构树层级ID
   */
  searchStructureId = null
  /**
  在线获取弹窗开关
   */
  dialogVisible = false
  radio = ''
  radio2 = ''
  areaName = ''
  selectPrjId = ''
  queryPara = ''
  prjOptions = []
  optionsoffter = [{ name: '全部', value: '', key: '2' }]
  pagination: IPagination = getDefaultPagination()
  tableColumns = [
    {
      prop: 'id',
      label: 'ID'
    },
    {
      prop: 'areaName',
      label: '所属区域'
    },
    {
      prop: 'fullName',
      label: '项目'
    },
    {
      prop: 'division',
      label: '片区'
    },
    {
      prop: 'batchName',
      label: '数据名称',
      showOverflowTooltip: true
    },
    {
      prop: 'dataSource',
      label: '数据阶段'
    },
    {
      prop: 'submitStatus',
      label: '提交状态'
    },
    {
      prop: 'detectionUnit',
      label: '上传单位',
      showOverflowTooltip: true
    },
    {
      prop: 'proName',
      label: '上传人'
    },
    {
      prop: 'updateTime',
      label: '上传时间',
      minWidth: '150px'
    },
    {
      slot: 'DownloadBtn',
      width: '50px'
    }
  ]
  /**
   * 在线文件列表数据
   */
  onlineRecords = []
  /**树结构 */
  structures = []
  /**
   * 上传文件
   */
  fileList = []
  /**
   * 最终提交的上传文件
   */
  files = []
  mapService = ['img', 'theme', 'temp']
  baseScene = 'scenes'
  baseTerrain = 'terrain'
  terrain = 'dixing'
  baselayer = []
  scenesIndex = 0
  get AppX() {
    return this.$store.getters.AppX
  }
  uploadSuccess() {
    this.$message.success('文件上传成功')
  }
  onBeforeRemove(file, fileList) {
    return this.$confirm(`确定移除${file.name}?`)
  }
  onRemove(file, fileList) {
    this.fileList = fileList
  }
  onCheckFile(file) {
    let fileName = file.name
    let esuffixt = fileName.substr(fileName.lastIndexOf('.') + 1)

    const isIMAGE = esuffixt === 'xls' || esuffixt === 'xlsx'
    //const isLt1M = file.size / 1024 / 1024 < 10

    if (!isIMAGE) {
      this.$message.error('上传文件只能是excel文件!')
    }
    // if (!isLt1M) {
    //   this.$message.error('上传文件大小不能超过 10MB!')
    // }
    return isIMAGE
  }
  onChange(file, fileList) {
    const isLoad = this.onCheckFile(file.raw)
    if (isLoad) {
      this.fileMap(fileList)
    } else {
      fileList.pop()
    }
  }
  fileMap(fileList) {
    if (fileList.length !== 0) {
      const files = fileList.map((v) => {
        return v.raw
      })
      this.files = files
    }
  }
  mounted() {
    this.getPbsTree()
  }
  /**未过滤发布状态的 */
  getPbsTree() {
    const params = { structDetailId: this.searchStructureId }
    pbsTreeListwithPublish(params).then((res) => {
      const { code, result } = res
      if (code === 1) {
        function formatTree(obj) {
          const copyedObj = JSON.parse(JSON.stringify(obj)) // 深拷贝源数据
          return copyedObj.filter((parent) => {
            const findChildren = copyedObj.filter((child) => parent.id === child.pid)

            findChildren.length > 0 ? (parent.children = findChildren) : (parent.children = [])
            return parent.pid === null // 返回顶层，依据实际情况判断这里的返回值
          })
        }
        if (result[0]) {
          this.isNewProj = false
          this.structures = result[0].structures
          let data = formatTree(result[0].structures)
          this.tableData = data
        } else {
          this.isNewProj = true
        }
      } else {
        this.$message.error('信息获取失败')
      }
    })
  }
  onExceed(files, fileList) {
    this.$message.warning(
      `当前限制选择 2 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`
    )
  }
  treeNodeClick(info) {
    if (!info) return
    this.searchStructureId = info.id
  }
  /**
   * 该方法用于新建节点
   */
  openNewNode(row) {
    this.addNodeForm.id = ''
    this.addNodeForm.code = ''
    this.newNodeDialogShow = true
    this.addNodeForm.pName = row.name
    this.addNodeForm.pCode = row.code
    this.addNodeForm.pid = row.id
    getStructureDetailByID({ id: row.id }).then((result) => {
      //获取PBSlevel id
      if (result.code === 1) {
        getPbsLevelByID({ id: result.result.pbslevelId }).then((pbslevel) => {
          //获取pbslevel信息
          if (pbslevel.code === 1) {
            this.connector = pbslevel.result.connector ? pbslevel.result.connector : ''
            //获取下级PBSlevel信息
            getPbsLevelPage({ alevel: pbslevel.result.alevel + 1, pbsId: pbslevel.result.pbsId }).then(
              (nextPbslevel) => {
                if (nextPbslevel.code === 1 && nextPbslevel.result.records.length === 1) {
                  //获取层级对应的业务对象
                  getPbsCodeDetailPage({ pbslevelId: nextPbslevel.result.records[0].id }).then((codeDetail) => {
                    if (codeDetail.code === 1 && codeDetail.result.records.length === 1) {
                      getBoinfoPage({
                        boId: codeDetail.result.records[0].boId,
                        size: 100,
                        'orders[0].column': 'code',
                        'orders[0].asc': true
                      }).then((boinfos) => {
                        if (boinfos.code === 1) {
                          const list = boinfos.result.records.map((item) => {
                            return { name: item.name, value: item.code, id: item.id }
                          })
                          this.nodeOptions = list
                        }
                      })
                    }
                  })
                }
              }
            )
          }
        })
      }
    })
  }
  /**该方法用于提交新建节点信息 */
  addNodeSubmit() {
    const data = {
      pid: this.addNodeForm.pid,
      code: this.addNodeForm.code,
      name: this.addNodeForm.name,
      prjId: this.$store.state.project.project.id,
      nextCode: this.addNodeForm.nextCode
    }
    addStrctureNode(data).then((result) => {
      if (result.code === -1) {
        this.$message.error(result.message || '添加失败')
        return
      }
      this.$message.success('添加成功')
      this.newNodeDialogShow = false
      this.getPbsTree()
    })
    // .catch((err) => {
    //   console.error(err)
    // })
  }
  /**下级节点选择器选中事件 */
  nextNodeChange() {
    const node = this.nodeOptions.find((item) => {
      return item.id === this.addNodeForm.id
    })
    this.addNodeForm.code = this.addNodeForm.pCode + this.connector + node.value
    this.addNodeForm.name = node.name
    this.addNodeForm.nextCode = node.value
  }
  /**添加项目 */
  addProjectNode() {
    const { pbsModel } = this.$store.state.project.project
    if (!pbsModel) {
      this.$message.warning('项目未绑定PBS模板')
      return
    }
    getPbsLevelPage({ pbsId: pbsModel, alevel: 1 }).then((pbslevel) => {
      if (pbslevel.code == 1 && pbslevel.result.records.length > 0) {
        const levelId = pbslevel.result.records[0].id
        //获取层级对应的业务对象
        getPbsCodeDetailPage({ pbslevelId: levelId }).then((codeDetail) => {
          if (codeDetail.code === 1 && codeDetail.result.records.length === 1) {
            getBoinfoPage({
              boId: codeDetail.result.records[0].boId,
              size: 100,
              'orders[0].column': 'code',
              'orders[0].asc': true
            }).then((boinfos) => {
              if (boinfos.code === 1) {
                const list = boinfos.result.records.map((item) => {
                  return { name: item.name, value: item.code }
                })
                if (list.length === 0) {
                  this.$message.warning('未创建工程业务对象')
                  return
                }
                const proj = list[0]
                const data = {
                  pid: null,
                  code: proj.value,
                  name: proj.name,
                  prjId: this.$store.state.project.project.id
                }
                addStrctureNode(data)
                  .then((result) => {
                    if (result.code === -1) {
                      this.$message.error('添加失败')
                      return
                    }
                    this.$message.success('添加成功')
                    this.getPbsTree()
                  })
                  .catch((err) => {
                    console.error(err)
                  })
              }
            })
          }
        })
      }
    })
  }
  /**导入按钮点击事件 */
  pipeDataImport(row) {
    this.impForm.id = row.id
    getStructureDetailByID({ id: row.pid })
      .then((result) => {
        this.impForm.prjName = result.result.name + '-' + row.name
      })
      .catch((err) => {
        console.log(err)
      })
    this.importDialogShow = true
    this.fileList = []
    this.impForm.pointColumns = []
    this.impForm.lineColumns = []
    this.impForm.pointData = []
    this.impForm.lineData = []
    this.importInfo = ''
    this.priviewInfo = ''
    this.$nextTick(() => {
      this.addToMap()
    })
  }
  /**
  导入excel表，创建二三维数据集  
   */
  buildDatasets() {
    if (this.files.length === 0) {
      this.$message.warning('请上传管网数据表')
      return
    }
    if (!this.impForm.id) {
      this.$message.warning('请选择导入层级')
      return
    }
    const wkid = this.$store.state.project.project.wkid
    if (!wkid || wkid === '') {
      this.$message.warning('请选择导入层级')
      return
    }
    const loading = this.$loading({
      text: '后台处理中',
      lock: true,
      spinner: 'el-icon-loading',
      background: 'rgba(0, 0, 0, 0.7)'
    })
    const formdata = new FormData()
    this.files.forEach((item) => {
      formdata.append('files', item)
    })
    formdata.append('importType', '0')
    formdata.append('id', '' + this.impForm.id)
    formdata.append('wkid', wkid)
    request({
      url: '/tofly-lzd-data/data/import/' + this.impForm.id,
      method: 'post',
      data: formdata,
      timeout: 600000
    })
      .then((result) => {
        if (result.code === 1) {
          this.$message.success('临时库数据集生成成功')
          //this.buildNetwork()
          request({
            url: '/tofly-lzd-data/data/getDataPreviewCount',
            method: 'get'
          }).then((res) => {
            this.priviewInfo = '管点:' + res.result['点表'] + '，管线' + res.result['线表'] + '条'
          })
        }
      })
      .catch((err) => {
        this.$message.error('临时数据集生成失败')
        console.log(err)
      })
      .finally(() => {
        loading.close()
      })
  }
  /**
   * 该方法用于预览excel表格数据
   */
  previewExcel() {
    if (this.files.length === 0) {
      this.$message.warning('请上传管网数据表')
      return
    }
    if (!this.impForm.id) {
      this.$message.warning('请选择导入层级')
      return
    }
    const loading = this.$loading({
      text: '后台处理中',
      lock: true,
      spinner: 'el-icon-loading',
      background: 'rgba(0, 0, 0, 0.7)'
    })
    const id = this.impForm.id
    const formdata = new FormData()
    this.files.forEach((item) => {
      formdata.append('files', item)
    })
    formdata.append('id', id)

    request({
      url: '/tofly-lzd-data/data/previewImportData/' + id,
      method: 'post',
      data: formdata
    })
      .then((result) => {
        if (result.code === 1) {
          this.$message.success('excel预览成功')
          //点表
          this.importInfo = '导入管点0个'
          if (result.result['点表'].length > 0) {
            const pointcolumns = Object.getOwnPropertyNames(result.result['点表'][0]).map((item) => {
              return { prop: item, label: item, showOverflowTooltip: true }
            })
            this.impForm.pointColumns = pointcolumns
            this.impForm.pointData = result.result['点表']
            this.importInfo = '导入管点' + result.result['点表'].length + '个'
          }
          //线表
          let lineinfo = '，管线0条'
          if (result.result['线表'].length > 0) {
            const linecolumns = Object.getOwnPropertyNames(result.result['线表'][0]).map((item) => {
              return { prop: item, label: item, showOverflowTooltip: true }
            })
            this.impForm.lineColumns = linecolumns
            this.impForm.lineData = result.result['线表']
            lineinfo = '，管线' + result.result['线表'].length + '条'
          }
          this.importInfo += lineinfo
        }
      })
      .catch((err) => {
        this.$message.error('导入excel出错')
        console.log(err)
      })
      .finally(() => {
        loading.close()
      })
  }

  /**
  导入excel表，创建二三维数据集【正式库】  
   */
  zsbuildDatasets() {
    const dataUser = this.$store.state.project.project.dataUser
    if (this.files.length === 0) {
      this.$message.warning('请上传管网数据表')
      return
    }
    if (!this.impForm.id) {
      this.$message.warning('请选择导入层级')
      return
    }
    if (!dataUser || dataUser === '') {
      this.$message.warning('未绑定空间数据库，请检查')
      return
    }
    const wkid = this.$store.state.project.project.wkid
    if (!wkid || wkid === '') {
      this.$message.warning('请选择导入层级')
      return
    }
    const workSpace = this.$store.state.project.project.workSpace
    if (!workSpace || workSpace === '') {
      this.$message.warning('未绑定工作空间，请检查')
      return
    }
    const loading = this.$loading({
      text: '后台处理中',
      lock: true,
      spinner: 'el-icon-loading',
      background: 'rgba(0, 0, 0, 0.7)'
    })
    const formdata = new FormData()
    this.files.forEach((item) => {
      formdata.append('files', item)
    })
    formdata.append('importType', '1')
    formdata.append('id', '' + this.impForm.id)
    formdata.append('wkid', wkid)
    formdata.append('dataUser', dataUser)
    formdata.append('workSpace', workSpace)
    request({
      url: '/tofly-lzd-data/data/import/' + this.impForm.id,
      method: 'POST',
      data: formdata,
      timeout: 600000
    })
      .then((result) => {
        this.$message.success('正式库数据集生成成功')
        //this.buildNetwork()
      })
      .catch((err) => {
        this.$message.error('正式库数据集生成失败')
        console.log(err)
      })
      .finally(() => {
        loading.close()
      })
  }
  /**
    重建三维网络【临时库】
   */
  buildNetwork() {
    request({
      url: '/tofly-lzd-data/data/createNetwork?importType=0',
      method: 'POST'
    })
      .then((result) => {
        if (result.code === 1) {
          this.$message.success('三维网络生成成功')
          //this.buildModelTiles()
        }
      })
      .catch((err) => {
        this.$message.error('三维网络生成失败')
        console.log(err)
      })
  }
  /**
    重建三维网络【正式库】
   */
  zsbuildNetwork() {
    const dataUser = this.$store.state.project.project.dataUser
    if (!dataUser || dataUser === '') {
      this.$message.warning('未绑定空间数据库，请检查')
      return
    }
    const workSpace = this.$store.state.project.project.workSpace
    if (!workSpace || workSpace === '') {
      this.$message.warning('未绑定工作空间，请检查')
      return
    }
    request({
      url: '/tofly-lzd-data/data/createNetwork?importType=1&dataUser=' + dataUser + '&workSpace=' + workSpace,
      method: 'POST',
      timeout: 600000
    })
      .then((result) => {
        if (result.code === 1) {
          this.$message.success('三维网络生成成功')
          this.zsbuildModelTiles()
        }
      })
      .catch((err) => {
        this.$message.error('三维网络生成失败')
        console.log(err)
      })
  }
  /**
    制作场景缓存【临时库】
   */
  buildModelTiles() {
    request({
      url: '/tofly-lzd-data/data/modelSlice3d?importType=0',
      method: 'POST'
    })
      .then((result) => {
        if (result.code === 1) {
          this.$message.success('场景缓存生成成功')
          this.publishService()
        }
      })
      .catch((err) => {
        this.$message.error('场景缓存生成失败')
        console.log(err)
      })
  }
  /**
    制作场景缓存【正式库】
   */
  zsbuildModelTiles() {
    const dataUser = this.$store.state.project.project.dataUser
    if (!dataUser || dataUser === '') {
      this.$message.warning('未绑定空间数据库，请检查')
      return
    }
    request({
      url: '/tofly-lzd-data/data/modelSlice3d?importType=1&dataUser=' + dataUser,
      method: 'POST'
    })
      .then((result) => {
        if (result.code === 1) {
          this.$message.success('场景缓存生成成功')
          this.zspublishService()
        }
      })
      .catch((err) => {
        this.$message.error('场景缓存生成失败')
        console.log(err)
      })
  }
  /**
    发布服务【临时库】
   */
  publishService() {
    request({
      url: '/tofly-lzd-data/data/publishService?importType=0',
      method: 'POST'
    })
      .then((result) => {
        if (result.code === 1) {
          this.$message.success('服务发布成功')
          this.addScene(result.result + '/realspace').then((layers) => {
            this.$message.success('三维管线模型加载完成')
          })
        }
      })
      .catch((err) => {
        this.$message.error('服务发布失败')
        console.log(err)
      })
  }
  /**
    发布服务
   */
  zspublishService() {
    request({
      url: '/tofly-lzd-data/data/publishService?importType=1',
      method: 'POST'
    })
      .then((result) => {
        if (result.code === 1) {
          this.$message.success('服务发布成功')
          this.addScene(result.result + '/realspace').then((layers) => {
            this.$message.success('三维管线模型加载完成')
          })
        }
      })
      .catch((err) => {
        this.$message.error('服务发布失败')
        console.log(err)
      })
  }
  /**更新发布标识 */
  updatePubcliSign(id) {
    const dataUser = this.$store.state.project.project.dataUser
    if (!dataUser || dataUser === '') {
      this.$message.warning('未绑定空间数据库，请检查')
      return
    }
    request({
      url: `/tofly-lzd-data/data/updateStatus/${id}`,
      method: 'get',
      params: { id }
    })
      .then((result) => {
        if (result.code === -1) {
          this.$message.error('更新发布标识失败')
          return
        }
        this.$message.success('更新发布标识成功')
        this.getPbsTree()
      })
      .catch((err) => {
        console.log(err)
      })
  }
  addScene(url) {
    //@ts-ignore
    const viewer = window.impViewer
    return viewer.scene.open(url, undefined, {
      autoSetView: false
    })
  }
  /**
   * 根据工程id删除数据
   */
  deleteData(row) {
    const dataUser = this.$store.state.project.project.dataUser
    if (!dataUser || dataUser === '') {
      this.$message.warning('未绑定空间数据库，请检查')
      return
    }
    const workSpace = this.$store.state.project.project.workSpace
    if (!workSpace || workSpace === '') {
      this.$message.warning('未绑定工作空间，请检查')
      return
    }
    const id = row.id
    this.$confirm('是否删除该节点')
      .then(() => {
        const loading = this.$loading({
          text: '后台处理中',
          lock: true,
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })
        request({
          url:
            '/tofly-lzd-data/data/deleteData/' +
            id +
            '?importType=1&id=' +
            id +
            '&dataUser=' +
            dataUser +
            '&workSpace=' +
            workSpace,
          method: 'POST'
        })
          .then((result) => {
            if (result.code === 1) {
              this.$message.success('数据删除成功')
              this.getPbsTree()
            }
          })
          .catch((err) => {
            this.$message.error('数据删除失败')
            console.log(err)
          })
          .finally(() => {
            loading.close()
          })
      })
      .catch(() => {
        this.$message.info('取消删除')
      })
  }
  OnlineAccess() {
    this.dialogVisible = true
    this.getlist()
    this.getAreaInfo()
    // const obj = await this.$PortApi.getAreaInfo_api();//公司名称
    // this.prjOptions = obj.data.result;
    // console.log(this.prjOptions, '公司名称');
  }
  /**
   * 在线获取-项目公司列表信息
   */
  getAreaInfo() {
    request({
      url: '/tofly-sxgk/outpiper/getAreaInfo',
      method: 'GET',
      params: {}
    }).then((result) => {
      if (result.code !== 1) {
        return
      }
      const list = [{ name: '全部', value: '' }]
      result.result.forEach((item) => {
        list.push({ name: item.name, value: item.name })
      })
      this.prjOptions = list
    })
  }
  onPageChange(pagination) {
    this.pagination = { ...this.pagination, ...pagination }
    this.getlist()
  }
  /**
   * 在线获取- 文件下载
   */
  downLoadFile(row) {
    let filename = row.files[0].fileSourceName
    let fileurl
    if (row.files[0].localFileUrl != null) {
      fileurl = row.files[0].localFileUrl
      let url =
        IP +
        '/base/file/downloadFile?remotePath=' +
        fileurl +
        '&fileName=' +
        filename +
        '&access_token=' +
        this.$store.getters.token
      window.open(url, '_parent')
    } else {
      let id = row.files[0].id.toString()
      request({
        url: '/tofly-sxgk/pipepr/downloadRemote',
        method: 'GET',
        params: { fileIdsStr: id }
      }).then((result) => {
        if (result.code !== 1) return
        if (result) {
          fileurl = result.result[0].url
          let url =
            IP +
            '/base/file/downloadFile?remotePath=' +
            fileurl +
            '&fileName=' +
            filename +
            '&access_token=' +
            this.$store.getters.token
          window.open(url, '_parent')
        }
      })
    }
  }
  /**
   * 获取图纸在线表单
   */
  getlist() {
    let params = {
      submitStatus: this.radio,
      areaName: this.areaName,
      proName: '',
      queryPara: this.queryPara,
      dataSource: this.radio2,
      current: this.pagination.current,
      size: this.pagination.size
    }
    request({
      method: 'get',
      url: '/tofly-sxgk/outpiper/page',
      params: params
    }).then((res) => {
      //      pagesizes: [10, 25, 50, 100],
      // pagesize: 10,
      // currentPage: 1,
      // totalNum: 0,
      const { records, size, total, current } = res.result
      //this.onlineRecords = records
      this.pagination.size = size
      this.pagination.current = current
      this.pagination.total = total
      let obj = {
        2: '设计',
        1: '普查',
        3: '竣工'
      }
      const status = {
        0: '已提交',
        1: '未提交'
      }
      this.onlineRecords = records.map((item) => {
        Object.keys(item).forEach((val) => (item[val] = item[val] || '暂无'))
        return {
          ...item,
          dataSource: obj[item.dataSource],
          submitStatus: status[item.submitStatus]
        }
      })
    })
  }
  /**
   * 加载地图
   */
  addToMap() {
    var configItem = this.AppX.appConfig.gisResource[this.baseTerrain]
    var url = configItem.config[this.terrain].url
    var layerTitle = configItem.config[this.terrain].name
    // var url =
    //   "https://yeepms.yeec.com.cn/iserver/services/3D-sxgk_dem/rest/realspace/datas/TF_PAPN_DEM@sxgk_base";
    // var layerTitle = "dixing";
    var viewer = new Cesium.Viewer('viewer', {
      terrainProvider: new Cesium.CesiumTerrainProvider({
        url: url,
        requestWaterMask: true,
        requestVertexNormals: true,
        credit: layerTitle,
        isSct: true
      }),
      navigation: true,
      contextOptions: {
        webgl: {
          alpha: false,
          depth: true,
          stencil: true,
          antialias: true,
          premultipliedAlpha: true,
          preserveDrawingBuffer: true, //通过canvas.toDataURL()实现截图需要将该项设置为true
          failIfMajorPerformanceCaveat: false
        },
        allowTextureFilterAnisotropic: true
      },
      timeline: false,
      animation: false,
      infoBox: false,
      selectionIndicator: false //设置绿色框框不可见
    })
    //this.$store.state.cesiumMap.mapContainerId = 'cesiumContainer'
    window.impViewer = viewer
    viewer._cesiumWidget._creditContainer.style.display = 'none' //去掉logo
    //this.isInit = true
    //this.panels.viewer = window.impViewer = viewer;
    //this.$store.commit('viewer',viewer)
    // const viewerInit = new ViewerInitEvent(viewer);
    // viewerInit.init();
    this.initCesiumStatus()
    //viewer.scene.logarithmicDepthBuffer = false;
    //高动态范围渲染
    //viewer.scene.highDynamicRange = false;
    this.initTianditu()
    this.initBaseMap()

    const initPosition = this.AppX.appConfig.initPosition
    const carto = Cesium.Cartographic.fromDegrees(
      parseFloat(initPosition.lon),
      parseFloat(initPosition.lat),
      parseFloat(initPosition.height)
    )
    const cartes3 = Cesium.Cartographic.toCartesian(carto)

    // const cartes3 = new Cesium.Cartesian3(
    //   -2204482.2366905585,
    //   5150077.372278957,
    //   3152769.164041396
    // );
    const camera = cartes3
    viewer.camera.setView({
      destination: new Cesium.Cartesian3(camera.x, camera.y, camera.z),
      orientation: {
        heading: 0,
        pitch: Cesium.Math.toRadians(-90),
        roll: 0
      }
    })
    this.$emit('afterMapLoad')
    setTimeout(
      function () {
        //this.addInitScene()
      }.bind(this),
      5000
    )
  }
  /**初始化基础底图*/
  initBaseMap() {
    this.baseMapConfig()
    let layerInfo = this.baselayer
    layerInfo.forEach((item) => {
      if (item.show) {
        const gisItem = this.AppX.appConfig.gisResource[item.type].config[item.name]
        if (!gisItem) {
          return true
        }
        const url = gisItem.url
        if (this.mapService.indexOf(item.type) > -1) {
          window.impViewer.imageryLayers.addImageryProvider(
            new Cesium.SuperMapImageryProvider({
              url: url,
              credit: item.name
            })
          )
        } else if ((item.type = 'mvt')) {
          window.impViewer.scene.addVectorTilesMap({
            url: url,
            name: item.name
          })
        }
      }
    })

    // window.impViewer.imageryLayers.addImageryProvider(
    //   new Cesium.SuperMapImageryProvider({
    //     url: "https://yeepms.yeec.com.cn/iserver/services/map-sxgk/rest/maps/hnyy_type",
    //     credit: "typetheme",
    //   })
    // );
  }
  /**
   * 地图服务配置
   */
  baseMapConfig() {
    const source = this.AppX.appConfig.gisResource
    const mapList = this.mapService
    const baseLayer = []
    for (let name in source) {
      if (mapList.indexOf(name) > -1) {
        const config = source[name].config
        for (let key in config) {
          const item = config[key]
          baseLayer.push({
            name: key,
            type: name,
            show: item.isDisplay === '0' ? false : true
          })
        }
        // for (let i = 0; i < config.length; i++) {
        //   const item = config[i];
        //   baseLayer.push({
        //     name: item.key,
        //     type: name,
        //     show: item.isDisplay === "0" ? false : true,
        //   });
        // }
      }
    }
    this.baselayer = baseLayer
  }

  /**
   * 加载初始化场景
   */
  addInitScene() {
    var scenes = this.AppX.appConfig.gisResource[this.baseScene]
    if (scenes && scenes.config) {
      this.scenesIndex = 0
      Object.keys(scenes.config).forEach(
        function (keyName, index) {
          const item = scenes.config[keyName]
          var promise = window.impViewer.scene.open(item.url, undefined, {
            autoSetView: false
          })
          Cesium.when(
            promise,
            function (layers) {
              this.scenesIndex += 1
              for (var i = 0; i < layers.length; i++) {
                var ly = layers[i]
                ly.selectEnabled = false
                ly.clearMemoryImmediately = false
                ly.cullEnabled = false
                //ly.lodRangeScale=0.01
                var model = BaseConfig.layers[ly.name]
                if (BaseConfig.sjpipeLayers.indexOf(ly.name) > -1) {
                  let style3d = new Cesium.Style3D()
                  style3d.altitudeMode = 0
                  style3d.bottomAltitude = 0 - this.AppX.appConfig.downDepth
                  ly.style3D = style3d
                  //ly.visibleDistanceMax=800;
                  ly.maxVisibleAltitude = BaseConfig.pipeMaxVisibel
                }
                //普查管线初始隐藏
                if (BaseConfig.pcpipeLayers.indexOf(ly.name) > -1) {
                  let style3d = new Cesium.Style3D()
                  style3d.altitudeMode = 0
                  style3d.bottomAltitude = 0 - this.AppX.appConfig.downDepth
                  ly.style3D = style3d
                  ly.visible = false
                  ly.maxVisibleAltitude = BaseConfig.pipeMaxVisibel
                }
                if (BaseConfig.pipeSelectLayers.indexOf(ly.name) > -1) {
                  ly.selectedColor = Cesium.Color.DARKRED
                  ly.selectColorType = 1
                }
                if (BaseConfig.pipeLineLayer.indexOf(ly.name) > -1) {
                  ly.lodRangeScale = 20
                }
                if (model) {
                  let style3d = new Cesium.Style3D()
                  style3d.altitudeMode = 0
                  style3d.bottomAltitude = model.bottomAltitude
                  ly.visible = model.visible
                  ly.style3D = style3d
                  //ly.brightness = model.brightness;
                  //ly.contrast = model.contrast;
                  //ly.hue = model.hue;
                  //ly.saturation = model.saturation;
                  //ly.gamma = model.gamma;
                  //if (Cesium.defined(model.maxVisibleAltitude)) ly.maxVisibleAltitude = model.maxVisibleAltitude;
                  //if(Cesium.defined(model.maxVisibleDistance)) ly.visibleDistanceMax=model.maxVisibleDistance;
                }
                ly.refresh()
              }
              if (!this.AppX.runtimeConfig.activeView.scene.pickPositionSupported) {
                console.error('不支持深度纹理,无法拾取位置！')
              }
            }.bind(this),
            function (e) {
              console.error('加载SCP失败，请检查网络连接状态或者url地址是否正确？')
            }
          )
        }.bind(this)
      )
    }
  }
  /**
   * 该方法用于初始化cesium属性
   */
  initCesiumStatus() {
    //开启地形深度测试
    window.impViewer.scene.globe.depthTestAgainstTerrain = true
    //关闭灯光
    window.impViewer.scene.globe.enableLighting = false
    //globeAlpha导致月球始终可见
    window.impViewer.scene.moon.show = false
    //地球表面双面显示
    window.impViewer.scene.globe.backFaceCulling = false
    //开启地下模式
    window.impViewer.scene.undergroundMode = true
    window.impViewer.scene.screenSpaceCameraController.minimumZoomDistance = -1000
    window.impViewer.terrainProvider.isCreateSkirt = false //关闭地形裙边
    //设置地球表面颜色
    window.impViewer.scene.globe.baseColor = new Cesium.Color(0, 0, 0, 1)
    //帧率工具
    window.impViewer.scene.debugShowFramesPerSecond = false
    const nowDate = new Date(Date.now())
    nowDate.setHours(16) //设置系统时间为12点,时差12小时
    nowDate.setMinutes(0)
    window.impViewer.clock.currentTime = Cesium.JulianDate.fromDate(nowDate)
    window.impViewer.cesiumWidget.screenSpaceEventHandler.removeInputAction(
      Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK
    )
  }
  /**
   * 系统初始化加载天地图
   */
  initTianditu() {
    const layerType = 'vec_w'
    const poiType = 'cva_w'
    const layerName = layerType.split('_')[0]
    const poiName = poiType.split('_')[0]
    const token = this.$store.state.cesiumMap.tdttoken
    const url =
      'https://t{s}.tianditu.gov.cn/' +
      layerType +
      '/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=' +
      layerName +
      '&TILEMATRIXSET=w&TILEMATRIX={TileMatrix}&TILEROW={TileRow}&TILECOL={TileCol}&STYLE=default&FORMAT=tiles&tk=' +
      token
    const poiurl =
      'https://t{s}.tianditu.gov.cn/' +
      poiType +
      '/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=' +
      poiName +
      '&TILEMATRIXSET=w&TILEMATRIX={TileMatrix}&TILEROW={TileRow}&TILECOL={TileCol}&STYLE=default&FORMAT=tiles&tk=' +
      token
    const imagelayers = window.impViewer.imageryLayers
    const layerlen = imagelayers.length
    const subdomains = ['0', '1', '2', '3', '4', '5', '6', '7']
    //中台
    const imglayer = new Cesium.WebMapTileServiceImageryProvider({
      //影像底图
      url: new Cesium.Resource({
        url: url,
        headers: {
          Accept: 'image/avif,image/webp,image/apng,image/svg+xml,image/*,*/*;q=0.8'
        }
      }),
      subdomains,
      credit: 'tianditu_base',
      layer: 'tdtVecLayer',
      style: 'default',
      maximumLevel: 17,
      format: 'image/jpeg',
      tileMatrixSetID: 'GoogleMapsCompatible', //使用谷歌的瓦片切片方式
      show: true
    })

    const poilayer = new Cesium.WebMapTileServiceImageryProvider({
      //影像底图
      url: new Cesium.Resource({
        url: poiurl,
        headers: {
          Accept: 'image/avif,image/webp,image/apng,image/svg+xml,image/*,*/*;q=0.8'
        }
      }),
      subdomains: subdomains,
      credit: 'tianditu_poi',
      layer: 'tdtCvaLayer',
      style: 'default',
      format: 'image/jpeg',
      maximumLevel: 17,
      tileMatrixSetID: 'GoogleMapsCompatible', //使用谷歌的瓦片切片方式
      show: true
    })
    imagelayers.addImageryProvider(imglayer)

    imagelayers.addImageryProvider(poilayer)
  }
  /**刷新地图 */
  refreshViewer() {
    window.impViewer.render()
  }
  /**服务发布按钮点击事件 */
  publicService() {
    this.isPublicDialogShow = true
    this.publicConfig = []
  }
  /**发布服务 */
  submitPublicService() {
    if (this.publicConfig.length === 0) {
      this.$message.error('请勾选发布选项')
      return
    }
    if (this.publicConfig.indexOf('重建三维网络') > -1) {
      this.zsbuildNetwork()
    }
    if (this.publicConfig.indexOf('发布地图服务') > -1) {
    }
    if (this.publicConfig.indexOf('更新发布标识') > -1) {
      this.updatePubcliSign(this.listSelect.id)
    }
  }
  /**表格勾选事件 */
  selectChange(selection) {
    this.listSelect = selection
  }
}
</script>

<style lang="scss" scoped>
.tdbutton {
  padding: 5px;
}
.eluploadcontainer {
  >>> .el-upload-list {
    height: 100px;
    border: 1px solid #dcdfe6;
    margin-top: 10px;
  }
}
.fullDialog {
  >>> .el-dialog {
    max-width: 100vw !important;
    .el-dialog__body {
      height: 100%;
    }
  }
  .impotMain {
    margin-top: -5px;
    padding: 0 0 0 20px;
    >>> .el-tabs {
      height: 100%;
      .el-tabs__content {
        height: calc(100% - 55px);
        .el-tab-pane {
          height: 100%;
        }
      }
    }
  }
}
.content-body {
  .el-table {
    >>> th > .cell {
      white-space: pre-line;
    }
    >>> .el-table__body {
      td.el-table__cell {
        padding: 0 !important;
        height: 34px;
      }
    }
  }
}
.content-footer {
  width: 100%;
  height: 55px;
  line-height: 35px;
  padding: 10px 20px;
}
.cesium_container {
  width: 100%;
  height: 100%;
  canvas {
    width: 100% !important;
    height: 100% !important;
    touch-action: none;
  }
  .cesium-viewer-bottom,
  .cesium-viewer-selectionIndicatorContainer,
  .cesium-viewer-infoBoxContainer,
  .cesium-viewer-toolbar,
  .cesium-viewer-zoomIndicatorContainer {
    display: none !important;
  }
  .cesium-viewer-navigationContainer {
    left: 0 !important;
  }
}
.refresjBtn {
  position: absolute;
  top: 10px;
  left: 10px;
}
</style>
