<template>
  <div class="metadata-list-container">
    <el-container>
      <div class="func-content">
        <el-button type="primary" @click="openAddSingleDataDialog">数据录入</el-button>
        <el-dropdown placement="bottom-start" v-show="true">
          <el-button type="primary">
            数据导入
            <i class="el-icon-arrow-down el-icon--right"></i>
          </el-button>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item v-if="params.type == 0">
              <el-upload class="upload-demo" ref="upload"
                accept="csv, application/vnd.ms-excel, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
                :action="''" :auto-upload="true" :show-file-list="false" :limit="1"
                :before-upload="beforeUploadBeforeExcel">
                <el-button>Excel</el-button>
              </el-upload>
            </el-dropdown-item>

            <el-dropdown-item>
              <el-upload class="upload-demo" ref="upload" accept=".json" :action="''" :auto-upload="true"
                :show-file-list="false" :limit="1" :before-upload="beforeUploadBeforeGeoJSON">
                <el-button>GeoJSON</el-button>
              </el-upload>
            </el-dropdown-item>

            <el-dropdown-item>
              <el-upload class="upload-demo" ref="upload" accept=".zip" :action="''" :auto-upload="true"
                :show-file-list="false" :limit="1" :before-upload="beforeUploadBeforeShape">
                <el-button>Shapefile</el-button>
              </el-upload>
            </el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
        <el-button type="primary" @click="openShareData">数据分享</el-button>
      </div>
      <div class="list-content">
        <MetadataList ref="metadatalist" v-bind="{
          tableLoading: tableLoading,
          tableData: tableData,
          dataTotal: dataTotal,
          updateData: searchData,
          changePage: changePage,
          modelParams: params,
        }"></MetadataList>
      </div>
    </el-container>
    <SingleData v-bind="{
      isShow: isShowAddSingleDataDialog,
      edit: true,
      title: '增加内容',
      beforeClose: beforeCloseAddSingleDataDialog,
      updateData: searchData,
      modelParams: params,
    }"></SingleData>
    <FileImport v-bind="{
      isShow: isShowFileImportDialog,
      title: fileImportTitle,
      fileType: fileType,
      beforeClose: beforeCloseFileImportDialog,
      updateData: searchData,
      modelParams: params,
      file: upload_file,
    }"></FileImport>
    <el-dialog :class="'interfaceList'" title="数据分享" width="800px" :visible.sync="isShareShow"
      :close-on-click-modal="false" :before-close="closeShareData">
      <el-row>
        <el-col :span="6" style="border-right:1px solid #eeeeee;">
          <div class="title">行政区划选择</div>
          <div style="height:310px;overflow:hidden;overflow-y:auto;">
            <el-tree ref="regionTree" :data="regionList" show-checkbox node-key="areaCode"
              :default-expanded-keys="[130000]" @check="regionCheck" :props="defaultRegionListProps"></el-tree>
          </div>
        </el-col>
        <el-col :span="1" style="border:1px solid transparent">
          <span></span>
        </el-col>
        <el-col :span="16">
          <div class="title">接口分享列表</div>
          <div style="height:310px;overflow:hidden;overflow-y:auto;line-height:20px">
            <span style="font-weight:bold">通用：</span>
            <br />请求方式：post
            <br />请求参数：modelId、areaCode、pageSize、page。
            <br />请求头口令：token
            <br />
            <br />
            <span style="font-weight:bold" v-if="interfaceList.length != 0">接口列表：</span>
            <el-row v-for="(item, index) in interfaceList" :key="index">
              <span v-if="item.level == 1 || item.level == 2">{{ item.areaName }}：</span>
              <span v-if="item.level == 3">{{ item.cityName + item.countyName }}：</span>
              <br />
              {{ interfaceShareAddress }}?modelId={{ params.modelId }}&areaCode={{ item.areaCode }}
            </el-row>
          </div>
        </el-col>
      </el-row>

      <span slot="footer" class="dialog-footer">
        <el-button @click="wordDownload">文档下载</el-button>
        <el-button @click="closeShareData">取 消</el-button>
        <el-button class="fuzhi" type="primary">复 制</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import api from "@/api/content";
import Clipboard from "clipboard";
export default {
  props: {
    params: {
      type: Object,
      default: null,
    }
  },
  data() {
    return {
      isShowAddSingleDataDialog: false,
      isShowFileImportDialog: false,
      upload_file: null,
      fileType: "",
      fileImportTitle: "",

      formData: null,
      formDataDefault: {
        centerLat: "",
        centerLon: "",
        content: "",
        locations: "",
        title: "",
        type: 0,
        jsonStr: "",
      },
      tableData: [],
      currentPage: 0,
      pageSize: 20,
      dataTotal: 0,
      tableLoading: true,

      isShareShow: false,
      defaultRegionListProps: {
        children: 'children',
        label: 'areaName'
      },
      regionList: [],
      // selectedRegion: [],
      interfaceList: [],
      interfaceShareAddress: systemConfig.interfaceShareAddress,
      clipboard: null
    };
  },
  components: {
    SingleData: () => import("@/components/MetadataListContainer/SingleData.vue"),
    FileImport: () => import("@/components/MetadataListContainer/FileImport.vue"),
    MetadataList: () => import("@/components/MetadataList.vue"),
  },
  created() {
    let that = this;
    $.getJSON("/static/config/hebei.json", function (result) {
      that.regionList = result;
    });
    this.searchData();

  },
  methods: {
    // 数据集目录查询（当前查询条件为字段值精确查询）
    searchData() {
      let that = this;
      let obj = {
        page: this.currentPage,
        pageSize: this.pageSize,
      };
      obj = Object.assign(obj, this.params);
      that.tableLoading = true;
      api
        .getContentListByModelId(obj)
        .then(function (result) {
          that.tableLoading = false;
          if (result.code == 200) {
            that.dataTotal = result.total;
            that.tableData = result.content;
            // 提示数据获取成功
            that.$message({
              message: "数据查询成功",
              type: "success",
            });
          } else {
            // 提示接口访问失败
            checkRequestCode(result);
            that.tableData = [];
            that.dataTotal = 0;
            that.tableLoading = false;
          }
        })
        .catch((err) => {
          that.tableData = [];
          that.dataTotal = 0;
          that.tableLoading = false;
          // 提示接口访问失败
          that.$message({
            type: "error",
            message: err
          });
        });
    },

    // 数据上传 GeoJSON
    beforeUploadBeforeGeoJSON(files) {
      let filedata = new FormData();
      filedata.append("file", files);
      this.upload_file = filedata;
      this.fileType = "GeoJSON";
      this.fileImportTitle = "GeoJSON文件上传";
      this.isShowFileImportDialog = true;
      return false;
    },

    // 数据上传 Excel
    beforeUploadBeforeExcel(files) {
      let filedata = new FormData();
      filedata.append("file", files);
      this.upload_file = filedata;
      this.fileType = "Excel";
      this.fileImportTitle = "Excel文件上传";
      this.isShowFileImportDialog = true;
      return false;
    },

    // 数据上传 Shapefile
    beforeUploadBeforeShape(files) {
      let filedata = new FormData();
      filedata.append("file", files);
      this.upload_file = filedata;
      this.fileType = "Shapefile";
      this.fileImportTitle = "Shapefile文件上传";
      this.isShowFileImportDialog = true;
      return false;
    },

    // 关闭文件上传Dailog
    beforeCloseFileImportDialog(judge) {
      if (judge) this.searchData();
      this.isShowFileImportDialog = false;
      this.fileImportTitle = "";
      this.upload_file = null;
    },

    // 打开 增加内容
    openAddSingleDataDialog() {
      this.isShowAddSingleDataDialog = true;
    },

    // 关闭 增加内容窗口前
    beforeCloseAddSingleDataDialog(type) {
      this.isShowAddSingleDataDialog = false;
    },

    // 改变分页
    changePage(pageNum, pageSize) {
      let that = this;
      return new Promise((resolve, reject) => {
        that.currentPage = pageNum - 1;
        if (pageSize) that.pageSize = pageSize;
        resolve();
      });
    },

    // 打开分享
    openShareData() {
      let that = this;
      this.isShareShow = true;

      this.$nextTick(function () {
        if (!that.clipboard) {
          that.clipboard = new Clipboard(".fuzhi", {
            // 点击copy按钮，直接通过text直接返回复印的内容
            text: function () {
              return that.organizeText();
            },
          });
          that.clipboard.on("success", function (e) {
            that.$message({
              type: "success",
              message: "复制成功！",
            });
          });
          that.clipboard.on("error", function (e) {
            that.$message({
              type: "success",
              message: "复制失败！",
            });
          });
        }

      })
    },
    // 勾选区划 single
    regionCheck(item, statusObj) {
      let arr = statusObj.checkedKeys;
      let after = this.handleRegion(arr)
      let itemArr = this.$refs.regionTree.getCheckedNodes();
      this.interfaceList = itemArr.filter(function (item) {

        return after.indexOf(item.areaCode) > -1
      })
    },
    // 整理行政区划
    handleRegion(arr) {
      if (arr.length == 0) return [];
      let provinceArr = arr.filter(function (num1) {
        return num1 % 10000 == 0
      })
      let cityArr = arr.filter(function (num2) {
        return num2 % 100 == 0
      })
      let countryArr = arr.filter(function (num2) {
        return num2 % 100 != 0
      })
      if (provinceArr.length != 0) {
        return provinceArr;
      } else {
        if (cityArr.length != 0) {
          let resetCountryArr = countryArr.filter(function (num3) {
            let integer = parseInt(num3 / 100) * 100
            return !cityArr.some(function (num) {
              return num == integer
            })
          })
          return cityArr.concat(resetCountryArr);
        } else {
          return countryArr
        }
      }
    },

    // 关闭分享
    closeShareData() {
      this.isShareShow = false;
      this.interfaceList = [];
      this.$refs.regionTree.setCheckedKeys([]);
    },
    // 复制文字
    organizeText() {
      let str =
        `通用：
请求方式：post
请求参数：modelId、areaCode、pageSize、page。
请求头口令：token
        `
      for (let i = 0; i < this.interfaceList.length; i++) {
        const element = this.interfaceList[i];
        if (element.level != 3) {
          str +=
            `
${element.areaName}：
`
        } else {
          str +=
            `
${element.cityName}${element.countyName}：
`
        }
        str += `${this.interfaceShareAddress}?modelId=${this.params.modelId}&areaCode=${element.areaCode}`
      }
      return str
    },
    // 文档下载
    wordDownload() {
      let str = this.organizeText();
      let blob = new Blob([str], {
        type: "application/msword"
      });
      let url = URL.createObjectURL(blob);
      let link = document.createElement('a');
      link.setAttribute("href", url);
      link.setAttribute("download", `接口分享文档.doc`);
      link.style.visibility = 'hidden';
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    }
  },
  computed: {
    now_userState() {
      return this.$store.state.userState;
    },
  },
  watch: {
    params(newVal, oldVal) {
      this.searchData();
    }
  },
};
</script>

<style lang="less" scoped>
.metadata-list-container {
  height: 100%;

  .el-container {
    height: calc(100%);
    flex-direction: column;
    background: #ffffff;
    border-radius: 5px;
    position: relative;

    .func-content {
      height: 40px;
      width: calc(100% - 100px);
      padding: 25px 50px;
      border-bottom: 1px solid #e8e8e8;

      .el-button {
        height: 40px;
        margin-right: 20px;
      }

      .upload-demo {
        display: inline-block;
      }
    }

    .list-content {
      width: calc(100% - 100px);
      height: calc(100% - 90px - 30px);
      padding: 25px 50px;
      padding-bottom: 0px;

      &.max-height {
        height: calc(100% - 30px);
      }
    }
  }

  .interfaceList {
    /deep/ .el-dialog__header {
      padding: 20px;
      border-bottom: 1px solid #eeeeee;
    }

    /deep/ .el-dialog__body {
      padding: 10px 20px;
      min-height: 280px;
      max-height: 480px;

      .title {
        height: 30px;
        font-size: 16px;
      }
    }

    /deep/ .el-dialog__footer {
      padding: 20px;
      border-top: 1px solid #eeeeee;
    }
  }
}

.el-dropdown-menu {
  width: 120px;
  text-align: center;

  .el-dropdown-menu__item {
    position: relative;
    height: 36px;

    .upload-demo {
      position: absolute;
      left: 0px;
      width: 100%;

      /deep/ .el-upload {
        width: 100%;
      }

      .el-button {
        width: 100%;
        border: 0px solid;
        background: transparent;
      }
    }

    &:hover .el-button {
      background-color: #ecf5ff;
      color: #66b1ff;
    }
  }
}
</style>
