<template>
  <div class="page-gd-manage">
    <div v-show="menusShow" class="page-left" :style="{height:contentHeight+'px',width:menusWidth+'px'}">
      <div class="nzy-tools">
        <div class="panels">
          <div class="panel-dropdown" style="background: #F5FBFF">
            <el-dropdown>
              <div class="el-dropdown-link">
                <img src="@/assets/images/datamanage/sc.png"/>
                导入文件
                <img src="@/assets/images/datamanage/sc-i.png"/>
              </div>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item>
                  <el-upload
                      class="upload-demo"
                      action=""
                      :before-upload="beforeUpload"
                      multiple
                      :limit="3"
                      :on-exceed="2"
                      accept=".zip">
                    &nbsp;&nbsp;批量导入&nbsp;&nbsp;
                  </el-upload>
                </el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </div>
          <div class="panel-dropdown" style="background: #FFFBF1">
            <el-dropdown>
              <div class="el-dropdown-link">
                <img src="@/assets/images/datamanage/xz.png"/>
                导出文件
                <img src="@/assets/images/datamanage/xz-i.png"/>
              </div>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item>
                  <div @click="doExportExcel">
                    导出项目Excel
                  </div>
                </el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </div>
        </div>
        <div class="panels">
          <div class="panel-input">
            <span>批准文号：</span>
            <el-input v-model="paramsList.dkbh" placeholder="请输入内容" clearable></el-input>
          </div>
          <div class="panel-input">
            <span>关键字：</span>
            <el-input v-model="paramsList.dkmc" placeholder="项目名称/用地单位名称/所属板块" clearable></el-input>
          </div>
        </div>
        <div class="panels">
          <div class="panel-input">
            <span>绘制范围：</span>
            <div class="fw"  title="框选绘制" @click="createBoxEvent">
              <i style="font-size: 20px" class="iconfont yh-Frame"/>
            </div>
            <div class="fw" title="自定义绘制"  @click="createDrawInteraction">
              <i style="font-size: 24px" class="iconfont yh-huizhi1"/>
            </div>
            <div class="fw" title="图斑拾取" @click="sqFeatrue">
              <i style="font-size: 24px" class="iconfont  yh-shiqu"/>
            </div>
            <div class="fw" title="清除绘制" @click="clearLayer">
              清除
            </div>
          </div>
          <div class="panel-input">
            <span>缓冲距离：</span>
            <el-input placeholder="请输入内容" v-model="input2">
              <template slot="append">米</template>
            </el-input>
            <el-button type="primary"  style="margin-left: 8px;height: 36px" @click="getBpxmList">查询</el-button>
          </div>
        </div>
      </div>
      <div class="nzy-table">
        <el-table
            border
            :data="tableData.data"
            :height="contentHeight-260"
            :header-cell-style="tableHeaderStyle"
            :cell-style="tableRowStyle"
            :row-click="rowClick"
            ref="report-table"
        >
          <el-table-column
              type="index"
              width="80"
              label="序号"/>
          <el-table-column
              prop="pzwh"
              width="100"
              label="临时用地批准文号"/>
          <el-table-column
              prop="xmmc"
              label="建设项目名称"
             />
          <el-table-column
              prop="pzsj"
              label="用地批准时间">
            <template slot-scope="scope">
              {{new Date(scope.row.pzsj).toLocaleDateString("af")}}
            </template>
          </el-table-column>
          <el-table-column
              width="150"
              label="操作">
            <template slot-scope="scope">
              <div style="line-height: 34px;">
                <el-button
                    @click.native.prevent="openDetail(scope.$index, scope.row)"
                    plain
                    type="primary"
                    size="mini">
                  查看
                </el-button>
                <el-button
                    @click.native.prevent="locationDk(scope.$index, scope.row)"
                    plain
                    type="success"
                    size="mini">
                  定位
                </el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
        <Page style="float: right;margin-top: 10px;"
              show-total
              :total="paramsList.total"
              :page-size="paramsList.size"
              @on-change="pageChange"
              @on-page-size-change="sizeChange"
              show-sizer />
      </div>
    </div>
    <div @click="()=>{menusWidth =0;menusShow=false;detailShow=false;$refs.baseMap.resetSize();}"
         style="top: calc(50% - 30px);left: calc( 700px - 20px);"
         title="收起"
         v-show="menusShow"
         class="menus-open"
    >
      <i class="iconfont yh-Frame2"/>
    </div>
    <div @click="()=>{menusWidth =700;menusShow=true;$refs.baseMap.resetSize();}"
         style="top: calc(50% - 30px);left: 0px;"
         title="展开"
         v-show="!menusShow"
         class="menus-open"
    >
      <!--      <img src="@/assets/images/datamanage/zd.png"/>-->
      <i class="iconfont yh-xiangyou"/>
    </div>
    <div v-show="detailShow" class="page-detail" :style="{height:contentHeight+'px',width:contentWidth-menusWidth+'px',left:menusWidth+'px'}">
      <detail ref="details" @initBpxm="getBpxmList" :contentWidth="contentWidth-menusWidth" :contentHeight="contentHeight" :project="currProject"/>
    </div>
    <div @click="()=>{detailShow=false;}"
         style="top: calc(50% - 30px);right: 0px"
         title="展开"
         v-show="detailShow"
         class="menus-open"
    >
      <i class="iconfont yh-Frame2"/>
    </div>
    <div class="page-map" :style="{height:contentHeight+'px',width: contentWidth-menusWidth-30+'px'}" >
      <base-map ref="baseMap" :overlayShow="true" @showDetail="showDetail" @drawShapeJson="drawShapeJsonEvent" :visibleLayerIds="visibleLayerId"/>
    </div>
  </div>
</template>

<script>
import mapshaper from "mapshaper";
import BaseMap from "../../components/common/BaseMap";
import Detail from "./ssnyd/Detail";
const {
  importContent,
  setDatasetCRS,
  exportFileContent
} = mapshaper.internal
export default {
  name: "Lsyd",
  props:{
    contentWidth:Number,
    contentHeight:Number
  },
  components:{BaseMap,Detail},
  data() {
    return {
      compName: 'data-manage',
      visibleLayerId:['YHYZT_SSNYD'],
      menus:JSON.parse(window.sessionStorage.getItem('yzt-user')),
      menusWidth:700,
      menusShow:true,
      detailShow:false,
      tableData:{
        data:[],
      },
      currProject:null,
      paramsList:{dkbh:'',dkmc:'',page:1,size:15,total:0},
      fullscreenLoading: false,
      drawShapeJson:null,
    }
  },
  mounted(){
    this.getBpxmList();
  },
  methods: {
    createBoxEvent(){
      this.$refs.baseMap.createBoxEvent();
    },
    sqFeatrue(){
      this.$refs.baseMap.sqFeatrue();
    },
    //自定义绘制分析
    createDrawInteraction(){
      this.$refs.baseMap.drawInteractionEvent();
    },
    //清除绘制图层
    clearLayer(){
      this.$refs.baseMap.cleanLayer();
      this.drawShapeJson = null;
      this.getBpxmList();
    },
    drawShapeJsonEvent(json){
      if(json){
        this.drawShapeJson = json;
        this.getBpxmList();
        this.$message.success("绘制结束");
      }
    },
    pageChange:function (page){
      this.paramsList.page=page;
      this.getBpxmList()
    },
    sizeChange:function (size){
      this.paramsList.size=size;
      this.getBpxmList()
    },
    //查询报批项目信息
    getBpxmList(){
      let params = new FormData();
      params.append("page",this.paramsList.page);
      params.append("size",this.paramsList.size);
      params.append("dkbh",this.paramsList.dkbh);
      params.append("dkmc",this.paramsList.dkmc);
      if(this.drawShapeJson){
        params.append("shapes",JSON.stringify(this.drawShapeJson));
      }
      let _this = this;
      this.$ajax.post('/api/data/manage/ssnyd/getList', params, this, true).then(res => {
        const {success,data} = res;
        if(success){
          _this.tableData.data =[];
          _this.paramsList.total=0;
          if(data.list){
            _this.tableData.data= data.list;
            _this.paramsList.total = data.total;
          }
        }
      })
    },
    rowClick(row, column, event){
      this.currProject = row;
      this.detailShow =true;
    },
    openDetail(index,row){
      this.currProject = row;
      this.detailShow =true;
      this.$refs.details.activeName='first';
    },
    showDetail(item){
      let params = new FormData();
      params.append("guid",item.index_id);
      this.$ajax.post('/api/data/manage/gd/getGdDetail', params, this, true).then(res => {
        const {success,data} = res;
        if(success){
          this.openDetail(0,data);
        }
      })
    },
    locationDk(index,row){
      if(row.objectid){
        this.detailShow = false;
        let dkbhArr = row.objectid?row.objectid:'';
        let arr = "'"+dkbhArr+"'";
        this.$vm.$emit('locationGlobal', this.visibleLayerId[0], `objectid in (${arr})`)
        //this.$message.warning("暂无图形")
      }
    },
    tableRowStyle({row, rowIndex}) {
      if (rowIndex%2 === 1) {
        return 'text-align:center;background:#F7F8FA';
      }else{
        return 'text-align:center;';
      }
    },
    tableHeaderStyle(){
      return 'background:#E5EDFE; font-family:AlibabaPuHuiTiR; font-size:16px; color:rgba(51, 51, 51, 1);text-align:center;';
    },
    beforeUpload(file){
      if(file){
        if(file.name.endsWith("zip")){
          this.doInput(file)
        }
        return false;
      }
    },
    //处理内容变化记录信息
    recordInfo(type,name,content){
      let info = {};
      info.re_recorder = this.menus.userInfo.orgName;
      info.table_type = '设施农用地导入';
      info.re_content='';
      let _this = this;
      info.re_name = name;
      if(type=='input'){
        info.re_content ='导入项目文件名：'+content;
      }else{
        info.re_content ='导出文件名：'+content;
      }
      let params = new FormData();
      params.append('data',JSON.stringify(info))
      //执行持久化操作（记录入库）
      this.$ajax.post('/api/opera/record/insert',params, this, true).then(res => {
        const {success,data} = res;
        if(success){
          this.$message.success("操作成功！")
        }else{
          this.$message.error("操作失败！")
        }
      })
    },
    doInput(file){
      let params = new FormData();
      params.append("file",file);
      let _this = this;
      const loading = this.$loading({
        lock: true,
        text: '正在导入中',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      this.$ajax.post('/api/data/upload/ssnyd/zip', params, this).then(res => {
        const {success,data} = res;
        loading.close();
        if(success && data){
          this.recordInfo("input",'设施农用地成果导入',file.name);
        }
      })
    },
    doExportExcel(){
      try {
        const $e = this.$refs['report-table'].$el
        let $table = $e.querySelector('.el-table__fixed')
        if(!$table) {
          $table = $e
        }
        const wb = XLSX.utils.table_to_book($table, {raw:true})
        const wbout = XLSX.write(wb, {bookType: 'xlsx', bookSST:true, type: 'array'})
        saveAs(
            new Blob([wbout],{type: 'application/octet-stream'}),
            `设施农用地列表.xlsx`,
        )
        this.recordInfo("export","设施农用地导出","设施农用地列表.xlsx")
      } catch (e) {
        if (typeof console !== 'undefined') console.error(e)
      }
    },
    doExport(){
      let params = new FormData();
      params.append("dkbh",this.paramsList.dkbh);
      params.append("dkmc",this.paramsList.dkmc);
      if(this.drawShapeJson){
        params.append("shapes",JSON.stringify(this.drawShapeJson));
      }
      const loading = this.$loading({
        lock: true,
        text: '正在导出',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      this.$ajax.post('/api/data/manage/gd/exportGdShapeFile', params, this).then(res => {
        const {success, data} = res;
        if(success){
          if(data.length<=0) {
            loading.close();
            return;
          };
          const geos = {
            'type': 'FeatureCollection',
            'features': []
          }
          data.map(i=>{
            let geoT = {
              type: 'Feature',
              geometry: {},
              properties: {}
            }
            const geo = WkxGeometry.parse(i.geomText).toGeoJSON()
            geoT.geometry = { ...geo }
            delete i.shape
            delete i.geomText
            geoT['properties'] = i
            geos.features.push(geoT)
          })
          const dataset = importContent({ json: { filename: '供地项目.json', content: JSON.stringify(geos) }})
          setDatasetCRS(dataset, { prj: 'GEOGCS["GCS_China_Geodetic_Coordinate_System_2000",DATUM["D_China_2000",SPHEROID["CGCS2000",6378137.0,298.257222101]],PRIMEM["Greenwich",0.0],UNIT["Degree",0.0174532925199433]]' })
          this.saveDataset(dataset);
          loading.close();
        }else{
          this.$Message.error("查询异常，请联系管理员！");
          loading.close();
        }
      })
    },
    saveDataset(dataset, type = 'shapefile') {
      const fileContent = exportFileContent(dataset, { format: type })
      this.saveFileContent(fileContent)
    },
    saveFileContent(fileContent) {
      var zip = new JSZip()

      fileContent.forEach(i => {
        zip.file(i.filename, i.content)
      })
      zip.file('供地项目.cpg', 'UTF-8')
      zip.generateAsync({ type: 'blob' }, function updateCallback(metadata) {
        var msg = 'progression : ' + metadata.percent.toFixed(2) + ' %'
        if (metadata.currentFile) {
          msg += ', current file = ' + metadata.currentFile
        }
        console.log(msg)
      }).then((blob) => {
        // see FileSaver.js
        saveAs(blob, '供地项目.zip')
        console.log('done !')
      })
          .catch(error => console.error(error.stack))
    },
  }
}
</script>
<style scoped lang="scss">
.page-gd-manage{
  position: relative;
  display: flex;
  .page-left{
    background: #fff;
    border-radius: 0px 0px 0px 0px;
    z-index: 99;
    padding: 20px;
    border-right:2px solid #e9e3e3;
    .nzy-tools{
      .panels{
        width: 100%;
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 20px;
      }
      .panel-dropdown{
        width: 49%;
        border-radius: 4px 4px 4px 4px;
        .el-dropdown{
          width: 100%;
          .el-dropdown-link{
            cursor: pointer;
            width: 100%;
            display: flex;
            align-items: center;
            justify-content: space-around;

            font-family: AlibabaPuHuiTiM;
            font-weight: normal;
            font-size: 16px;
            color: #3C4859;
            line-height: 20px;
            text-align: center;
          }
        }
      }
      .panel-input{
        width: 49%;
        display: flex;
        align-items: center;
        justify-content: center;
        span{
          font-family: AlibabaPuHuiTiM;
          font-size: 14px;
          color: #404A5B;
          text-align: center;
          width: 130px;
        }
        .fw{
          width: 60px;
          height: 36px;
          display: flex;
          justify-content: center;
          align-items: center;
          border-radius: 4px;
          border: 1px solid #CCD1DC;
          color: #446AE7;
          margin-left: 8px;
          cursor: pointer;
        }
        ::v-deep{
          .el-input__inner{
            height: 36px;
            line-height: 36px;
          }
        }
      }
    }
  }
  .page-detail{
    background: #FFFFFF;
    border-radius: 0px 0px 0px 0px;
    position: absolute;
    z-index: 999;
    right: 0px;
  }
  .menus-open{
    width: 32px;
    height: 62px;
    background: #E8EEFF;
    box-shadow: 0px 2px 2px 0px rgba(55,90,178,0.2);
    border-radius: 4px 0px 0px 4px;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 6px;
    position: absolute;
    cursor: pointer;
    z-index: 999;
    i{
      color: #4880FF;
      font-size: 26px;
    }
  }
  .page-map{
    //position: absolute;
    //background:#434;
  }
}
</style>