<template>
  <div class="page-nzy-manage">
    <div class="page-left" :style="{height:contentHeight+'px',width:contentWidth+'px'}">
      <div class="nzy-tools">
        <el-form label-width="120px" :model="searchParam">
          <el-row :gutter="10">
            <el-col :span="6">
              <el-form-item label="批次索引：">
                <el-input v-model="searchParam.pcbh" placeholder="请输入批次索引"  clearable></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="批次名称：">
                <el-input v-model="searchParam.pch" placeholder="请输入项目名称"  clearable></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="类型：">
                <el-select v-model="searchParam.lx" style="width: 100%;">
                  <el-option value="" label="全部" />
                  <el-option value="单独选址" label="单独选址" />
                  <el-option value="批次用地" label="批次用地" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="批准文号：">
                <el-input v-model="searchParam.pwh" placeholder="请输入批准文号"  clearable></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="10">
            <el-col :span="6">
              <el-form-item label="批准日期：">
                <el-date-picker
                  v-model="pcrqDateRange"
                  type="daterange"
                  value-format="yyyy-MM-dd"
                  unlink-panels
                  start-placeholder="批准开始时间"
                  end-placeholder="批准结束时间"
                  :shortcuts="shortcuts"
                  style="width:100%"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="批次总面积：">
                <el-input v-model="searchParam.pzmj" placeholder="请输入批次总面积（公顷）"  clearable></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="是否农民建房：">
                <el-select style="width: 100%;" v-model="searchParam.nmjf">
                  <el-option value="是" label="是"></el-option>
                  <el-option value="否" label="否"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <div class="btn-group">
                <el-button type="primary" @click="onSearchHandle">查询</el-button>
                <div class="panel-dropdown">
                  <el-dropdown>
                    <el-button type="success">
                      导入文件<i class="el-icon-arrow-down el-icon--right"></i>
                    </el-button>
                    <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;
                        </el-upload>
                      </el-dropdown-item>
                    </el-dropdown-menu>
                  </el-dropdown>
                </div>
                <el-button type="primary" @click="downloadTemplate" style="margin-left: 12px">模板下载</el-button>
              </div>
            </el-col>
          </el-row>
        </el-form>

      </div>
      <div class="nzy-table">
        <el-table
            border
            :data="tableData.data"
            :height="contentHeight-260"
            :header-cell-style="tableHeaderStyle"
            :cell-style="tableRowStyle"
            ref="report-table"
            >
          <el-table-column
              type="index"
              width="80"
              label="序号">
          </el-table-column>
          <el-table-column
              prop="pcbh"
              label="批次索引">
          </el-table-column>
          <el-table-column
              prop="pch"
              label="批次名称">
          </el-table-column>
          <el-table-column
              prop="lx"
              label="类型">
          </el-table-column>
          <el-table-column
              prop="pwh"
              label="批准文号">
          </el-table-column>
          <el-table-column
              prop="pzrq"
              label="批准日期">
          </el-table-column>
          <el-table-column
              prop="pzmj"
              label="批准总面积（公顷）">
          </el-table-column>
          <el-table-column
              prop="nmjf"
              label="是否农民建房">
          </el-table-column>
          <el-table-column
              width="260"
              label="操作">
            <template slot-scope="scope">
              <div style="line-height: 34px;">
                <el-button
                  @click.native.prevent="openDetail(scope.row)"
                  plain
                  type="primary"
                  size="mini">
                  查看
                </el-button>
                <el-button
                  @click.native.prevent="openDetail(scope.row, true)"
                  style="margin: 0px 10px;"
                  plain
                  type="primary"
                  size="mini">
                  编辑
                </el-button>
                <el-popconfirm
                  title="该条数据确定删除吗？"
                  @confirm="deleteHandle(scope.$index, scope.row)"
                >
                  <el-button
                    plain
                    type="danger"
                    slot="reference"
                    size="mini">
                    删除
                  </el-button>
                </el-popconfirm>
              </div>
            </template>
          </el-table-column>
        </el-table>
        <Page style="float: right;margin-top: 10px;"
              show-total
              :total="tableData.total"
              :page-size="searchParam.size"
              @on-change="pageChange"
              @on-page-size-change="sizeChange"
              show-sizer />
      </div>
    </div>
    <el-dialog
      :visible.sync="detailShow"
      title="项目详情"
      top="5vh"
      width="80%"
    >
      <detail ref="details" @init="onSearchHandle" :contentWidth="contentWidth-menusWidth" :contentHeight="contentHeight"/>
    </el-dialog>
  </div>
</template>
<script>
import Detail from "./nzy/Detail";
import JSZip from 'jszip'
import mapshaper from 'mapshaper';
import { saveAs } from 'file-saver'
const {
  exportFileContent
} = mapshaper.internal
export default {
  name: "Nzy",
  props:{
    contentWidth:Number,
    contentHeight:Number
  },
  components:{Detail},
  data() {
    return {
      menus:JSON.parse(window.sessionStorage.getItem('yzt-user')),
      menusWidth:700,
      detailShow:false,
      tableData:{
        data:[],
      },
      pcrqDateRange: [],
      searchParam: {
        pcbh: '',
        pch: '',
        lx: '',
        pwh: '',
        pzrqStart: '',
        pzrqEnd: '',
        pzmj: '',
        nmjf: '',
        current: 1,
        size: 10
      }
    }
  },
  created () {
    this.queryByPage();
  },
  methods: {
    onSearchHandle () {
      this.detailShow = false
      this.searchParam['current'] = 1
      this.queryByPage()
    },
    pageChange:function (page){
      this.searchParam.current=page;
      this.queryByPage()
    },
    sizeChange:function (size){
      this.searchParam.size=size;
      this.queryByPage()
    },
    //查询报批项目信息
    queryByPage () {
      let _this = this;
      if (this.pcrqDateRange && this.pcrqDateRange.length > 0) {
        this.searchParam.pzrqStart = this.pcrqDateRange[0]
        this.searchParam.pzrqEnd = this.pcrqDateRange[1]
      } else {
        this.searchParam.pzrqStart = ''
        this.searchParam.pzrqEnd = ''
      }
      const params = {
        ...this.searchParam
      }
      if (params['pwh']) {
        params['pwh'] = encodeURI(this.searchParam['pwh'])
      }
      this.$ajax.get('/api/stnzy/page', params, this, true).then(res => {
        if (res.status === 200) {
            _this.tableData.data= res.records;
            _this.tableData.total = res.total;
        }
      })
    },
    openDetail(row, isEditor = false){
      this.detailShow = true;
      this.$nextTick(() => {
        this.$refs['details'].initDetailData(row, isEditor)
      })
    },
    deleteHandle (index, row) {
      const params = {pch: row['pch']}
      this.$ajax.get('/api/stnzy/deleteByPch', params, this, true).then(res => {
        if (res) {
          this.$Message.success('删除成功！')
          this.queryByPage()
        }
      })
    },
    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;
      }
    },
    doInput(file){
      let params = new FormData();
      params.append("file", file);
      const loading = this.$loading({
        lock: true,
        text: '正在导入中',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      this.$ajax.post('/api/stnzy/upload', params, this).then(res => {
        loading.close();
        if (res.success) {
          this.$Message.success("导入成功！");
          if (Array.isArray(res.data)) {
            res.data.forEach(pcbh => {
              this.$ajax.get('/api/pewg/importFromNzydk', { pcbh }, this).then((res) => {
                // 可选：每个导入后提示
                this.$Message.success(`pcbh: ${pcbh} 导入批而未供成功:${res.data}`);
              }).catch(() => {
                this.$Message.error(`pcbh: ${pcbh} 导入批而未供失败`);
              });
            });
          }
          this.queryByPage && this.queryByPage(); // 成功后刷新数据
        } else {
          if (res.data && Array.isArray(res.data)) {
            res.data.forEach(msg => this.$Message.error(msg));
          } else {
            this.$Message.error(res.message || "导入失败！");
          }
        }
      }).catch(error => {
        loading.close();
        this.$Message.error("上传失败，请重试！");
        console.error(error);
      });
    },
    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))
    },
    downloadTemplate() {
      // 模板下载地址
      window.open(window.ApplicationConfig.templateUrls.nzy);
    }
  }
}
</script>
<style scoped lang="scss">
.page-nzy-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{
      .btn-group {
        display: flex;
      }
      .panel-dropdown{
        margin-left: 10px;
        border-radius: 4px 4px 4px 4px;
        .el-dropdown{
          width: 100%;
        }
      }
    }
  }
  .page-detail{
    background: #FFFFFF;
    border-radius: 0px 0px 0px 0px;
    position: absolute;
    z-index: 999;
    right: 0px;
  }
  .page-map{
    //position: absolute;
    //background:#434;
  }
}
</style>