<template>
  <div>
    <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 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="https://jsonplaceholder.typicode.com/posts/" :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="primary">本地文件</el-button>
          <el-button size="small" type="primary" @click="OnlineAccess">在线获取</el-button>
        </el-upload>
      </el-form-item>
      <el-form-item>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-button type="primary" style="width:100%" @click="buildDatasets">预览</el-button>
          </el-col>
          <el-col :span="12">
            <el-button type="primary" style="width:100%" @click="zsbuildDatasets">提交</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>
</template>

<script lang='ts'>
/**
 *@description 该功能为管网数据在线入库
 *@author lishun <876330731@qq.com>
 */
import { Vue, Prop, Watch, Component } from 'vue-property-decorator'
import request, { IP } from '@/utils/request'
import PbsTree from './components/PbsTree.vue'
import { getDefaultPagination } from '@/utils/constant'
import { pageSizes } from '@/utils/constant'
import { IPagination } from '@/api/common'
@Component({
  name: 'DataImport',
  components: { PbsTree }
})
export default class DataImport extends Vue {
  impForm = {
    prjName: '',
    stage: 'SJ',
    paperName: '',
    paperUnit: '',
    paperPerson: '',
    origin: ''
  }
  pageSizes = pageSizes
  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' }]
  }
  /**
   * PBS结构树层级ID
   */
  selectProjID = 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 = []
  /**
   * 上传文件
   */
  fileList = []
  /**
   * 最终提交的上传文件
   */
  files = []
  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) {
    debugger
    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
    }
  }
  onExceed(files, fileList) {
    this.$message.warning(
      `当前限制选择 2 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`
    )
  }
  treeNodeClick(info) {
    if (!info) return
    this.selectProjID = info.id
  }
  /**
  导入excel表，创建二三维数据集  
   */
  buildDatasets() {
    if (this.files.length === 0) {
      this.$message.warning('请上传管网数据表')
      return
    }
    if (!this.selectProjID) {
      this.$message.warning('请选择导入层级')
      return
    }
    const formdata = new FormData()
    this.files.forEach((item) => {
      formdata.append('files', item)
    })
    formdata.append('importType', '0')
    formdata.append('id', '' + this.selectProjID)

    request({
      url: '/tofly-lzd-data/data/import/' + this.selectProjID,
      method: 'POST',
      data: formdata
    })
      .then((result) => {
        if (result.code === 1) {
          this.$message.success('生成数据集成功')
          this.buildNetwork()
        }
      })
      .catch((err) => {
        this.$message.error('生成数据集失败')
        console.log(err)
      })
  }
  /**
  导入excel表，创建二三维数据集【正式库】  
   */
  zsbuildDatasets() {
    if (this.files.length === 0) {
      this.$message.warning('请上传管网数据表')
      return
    }
    if (!this.selectProjID) {
      this.$message.warning('请选择导入层级')
      return
    }
    const formdata = new FormData()
    this.files.forEach((item) => {
      formdata.append('files', item)
    })
    formdata.append('importType', '1')
    formdata.append('id', '' + this.selectProjID)

    request({
      url: '/tofly-lzd-data/data/import/' + this.selectProjID,
      method: 'POST',
      data: formdata
    })
      .then((result) => {
        this.$message.success('生成数据集成功')
        this.buildNetwork()
      })
      .catch((err) => {
        this.$message.error('导入excel出错')
        console.log(err)
      })
  }
  /**
    重建三维网络【临时库】
   */
  buildNetwork() {
    request({
      url: '/tofly-lzd-data/data/createNetwork?importType=0',
      method: 'POST'
    })
      .then((result) => {
        console.log(result)
        if (result.code === 1) {
          this.$message.success('三维网络生成成功')
          this.buildModelTiles()
        }
      })
      .catch((err) => {
        this.$message.error('三维网络生成失败')
        console.log(err)
      })
  }
  /**
    重建三维网络【正式库】
   */
  zsbuildNetwork() {
    request({
      url: '/tofly-lzd-data/data/createNetwork?importType=1',
      method: 'POST'
    })
      .then((result) => {
        console.log(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() {
    request({
      url: '/tofly-lzd-data/data/modelSlice3d?importType=1',
      method: 'POST'
    })
      .then((result) => {
        console.log(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) => {
        console.log(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) => {
        console.log(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)
      })
  }
  addScene(url) {
    //@ts-ignore
    const viewer = window.viewer
    return viewer.scene.open(url, undefined, {
      autoSetView: false
    })
  }
  /**
   * 根据工程id删除数据
   */
  deleteData() {
    if (!this.selectProjID) {
      this.$message.success('请选择PBS结构树层级')
      return
    }
    request({
      url: '/tofly-lzd-data/data/deleteData/' + this.selectProjID + '?importType=1&id=' + this.selectProjID,
      method: 'POST'
    })
      .then((result) => {
        if (result.code === 1) {
          this.$message.success('数据删除成功')
        }
      })
      .catch((err) => {
        this.$message.error('数据删除成功')
        console.log(err)
      })
  }
  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]
        }
      })
    })
  }
}
</script>

<style lang="scss" scoped>
.eluploadcontainer {
  >>> .el-upload-list {
    height: 100px;
    border: 1px solid #dcdfe6;
    margin-top: 10px;
  }
}
.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;
}
</style>
