<template>
  <div
    class="data-container"
    :style="{ background: COLOR.DASHBOARD_BACKGROUND, color: COLOR.APP_COLOR }"
  >
    <tcStyle @yschange="yschange" v-if="showys"></tcStyle>
    <!-- -----------------------------------------------文件上传------------------------------------------------------------------------------------------- -->
    <div class="data-upload" id="data-container" v-if="showUpload">
      <!-- ------------------------------------------- -- 配置页------------------------------------------------------------------------------- -->
      <div class="tuceng_pz">
        <div class="tuceng_pz_son">
          <p>图层属性配置</p>
          <el-form ref="forms" :model="form" label-width="80px">
            <el-form-item label="服务名称">
              <el-input
                placeholder="请输入服务名称"
                style="width: 300px"
                v-model="form.serverName"
              ></el-input>
            </el-form-item>
            <el-form-item label="空间参考">
              <el-select
                style="width: 300px"
                v-model="form.spaceType"
                placeholder="请选择空间参考"
              >
                <el-option
                  v-for="(item, index) in getDictone"
                  :key="index"
                  :label="item.dictlabel"
                  :value="item.dictlabel"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="服务类型">
              <el-select
                style="width: 300px"
                v-model="form.severType"
                placeholder="请选择服务类型"
              >
                <el-option
                  v-for="(item, index) in getDicttwo"
                  :key="index"
                  :label="item.dictlabel"
                  :value="item.dictlabel"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="图层样式">
              <el-select v-model="form.styleName" placeholder="请选择图层样式">
                <el-option
                  v-for="(value, key) in getDictthree"
                  :key="key"
                  :label="value"
                  :value="value"
                ></el-option>
              </el-select>
              <el-button type="primary" @click="chuangjian">创建样式</el-button>
            </el-form-item>
          </el-form>
          <el-upload
            drag
            multiple
            :action="url + '/geoserver/uploadFile'"
            :headers="headers"
            :data="{ spaceType: form.spaceType, styleName: form.styleName }"
            :before-upload="onBeforeUpload"
            :on-success="Onsuccess"
            :on-error="Onerror"
            :disabled="disabled"
          >
            <img src="/images/img26.png" alt="" />
            <div class="el-upload__text">
              将shp文件拖到此处，或<em>点击上传</em>
            </div>
            <div slot="tip">请先配置图层属性再上传</div>
          </el-upload>
        </div>
      </div>
    </div>
    <!-- -----------------------------------------------table表格----------------------------------------------------------------------------------- -->
    <div class="data-table" v-if="showtable">
      <el-table height="890" :data="properties" style="width: 100%">
        <el-table-column prop="name" label="属性名称" width="180">
        </el-table-column>
        <el-table-column label="数据类型" :width="250">
          <template slot-scope="scope">
            <el-select
              class="data-table-dropdown"
              :popper-append-to-body="false"
              v-model="properties[scope.$index].type"
              placeholder="请选择"
            >
              <el-option
                v-for="item in fieldsType"
                :key="item.value"
                :label="item.name"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="字符长度" :width="250">
          <template slot-scope="scope">
            <el-input type="number" v-model="properties[scope.$index].length" />
          </template>
        </el-table-column>
        <el-table-column label="字段名称" :width="250">
          <template slot-scope="scope">
            <el-input v-model="properties[scope.$index].refName" />
          </template>
        </el-table-column>
        <el-table-column label="操作" :width="300">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="danger"
              round
              @click="handleDeleteFields(scope.$index, scope.row)"
              >删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- -------------------------------------------------地图-------------------------------------------------------------------------------------------------- -->
    <div v-if="showtable">
      <div class="data-map" ref="data-map" id="mapbox-container"></div>
      <div class="data-sub">
        <el-button type="parmary" @click="qxBtn">取消</el-button>
        <el-button type="primary" @click="onSubmit">提交</el-button>
      </div>
    </div>
    <Bottom v-if="showtable" />
    <!-- -----------------------------------------------------保存成功页-------------------------------------------------------------------------------------------------- -->
    <chenggong
      v-if="showchenggong"
      @change="changebtn"
      :showchenggong="showchenggong"
    ></chenggong>
  </div>
</template>

<script>
import mapboxgl from "mapbox-gl";
import * as turf from "@turf/turf";
import Bottom from "../../components/layout/Bottom";
import chenggong from "./success.vue";
import tcStyle from "./yangshi.vue";
import { globalApi } from "../../api/urlPatterns";
import {
  getDictone,
  getDicttwo,
  saveData,
  canelSave,
  publishLayer,
  getLayerStyle,
} from "../../api/datamange";
mapboxgl.accessToken =
  "pk.eyJ1Ijoic2hpY2hhbzEyMyIsImEiOiJja3FobnI1aDEwNGF6Mm9vOXVhNnBzZmFhIn0.2fZKiMqCQHxVY74QShMEGQ";

export default {
  name: "DataManage",
  components: {
    Bottom,
    chenggong,
    tcStyle,
  },
  watch: {
    // properties: {
    //   handler: function () {
    //     // console.log(this.properties);
    //   },
    //   deep: true,
    // },
    form: {
      handler: function () {
        // console.log(this.form);
        if (
          this.form.spaceType != "" &&
          this.form.severType != "" &&
          this.form.styleName != "" &&
          this.form.serverName != ""
        ) {
          this.disabled = false;
        }
      },
      deep: true,
    },
  },
  data() {
    return {
      disabled: true,
      url: globalApi.BASE_URL,
      headers: {
        Authorization: localStorage.getItem("X-Token") || "",
      },
      form: {
        spaceType: "",
        severType: "",
        styleName: "",
        serverName: "",
      },
      showys: false,
      showUpload: true,
      showtable: false,
      showchenggong: false,
      properties: [
        {
          name: "111",
          type: "",
          refName: "",
          length: 20,
        },
      ],
      fieldsType: [
        {
          name: "字符串",
          value: "Char",
        },
        {
          name: "数字",
          value: "number",
        },
      ],
      mapData: {},
      map: null,
      tableName: "", //表名
      dataType: "", //数据类型
      styleName: "", // 图层样式
      getDictone: [], //空间参考字典
      getDicttwo: [], //服务类型字典
      getDictthree: [], //图层样式字典
    };
  },
  created() {
    getDictone().then((res) => {
      this.getDictone = res.data.data;
    });
    getDicttwo().then((res) => {
      this.getDicttwo = res.data.data;
    });
    getLayerStyle().then((res) => {
      // console.log(res);
      this.getDictthree = res.data.data.style.names;
    });
  },
  methods: {
    chuangjian() {
      this.showys = true;
      this.showUpload = false;
    },
    yschange() {
      getLayerStyle().then((res) => {
        // console.log(res);
        this.getDictthree = res.data.data.style.names;
      });
      this.showys = false;
      this.showUpload = true;
    },
    // 成功页转跳
    changebtn() {
      this.showchenggong = false;
      this.showUpload = true;
      this.$router.push("/ServiceList");
    },
    // 文件上传前
    onBeforeUpload(file) {
      console.log(1);
      let _this = this;
      let [name, format] = file.name.split(".");
      if (".zip".includes(format)) {
        const { space, service, styleName, serverName } = _this.form;
        if (
          space != "" &&
          service != "" &&
          styleName != "" &&
          serverName != ""
        ) {
          // 前端解析  临时流程 后期会改
          let fileReader = new FileReader();
          fileReader.readAsArrayBuffer(file);
          fileReader.onload = function () {
            window.shp.parseZip(this.result).then((geojson) => {
              // console.log("geojson", geojson);
              if (
                Object.prototype.toString.call(geojson) === "[object Array]"
              ) {
                alert("每个压缩包只能包含一个shp文件！");
              } else if (
                Object.prototype.toString.call(geojson) === "[object Object]"
              ) {
                if (!geojson.features) {
                  this.$message.error("不是shp文件！");
                }
                _this.mapData = geojson;
              }
            });
          };
        } else {
          this.$message.error("请先配置图层属性再上传");
          return false;
        }
      } else {
        alert("暂不支持该类型数据文件");
        return false;
      }
    },
    // 上传成功
    Onsuccess(response, file) {

      console.log("上传成功", this.form);
      if (response.code == 200) {
        let properties = response.data.heads;
        this.tableName = response.data.tableName;
        this.dataType = response.data.dataType;
        this.styleName = response.data.styleName;
        properties.map((res) => {
          res.refName = res.name;
        });
        this.properties = properties;
        this.$message.success("上传成功");
        this.showtable = true;
        this.showUpload = false;
        this.$nextTick(function () {
          this.initMap();
        });
      }
    },
    // 上传失败
    Onerror(err, file) {
      this.$message.error("文件上传失败");
      this.showtable = false;
      this.showUpload = true;
    },
    // 提交
    onSubmit() {
      saveData({
        severType: this.form.severType,
        spaceType: this.form.spaceType,
        tableName: this.tableName,
        newHeads: this.properties,
        dataType: this.dataType,
        styleName: this.styleName,
        serverName: this.form.serverName,
      }).then((res) => {
        // console.log(res);
        if (res.data.code == 200) {
          this.$message.success("保存成功");
          publishLayer(this.tableName).then((res) => {
            // console.log("1111111111111111111111", res);
          });
          this.showchenggong = true;
          this.showtable = false;
        }
      });
    },
    qxBtn() {
      canelSave(this.tableName).then((res) => {
        // console.log(res);
        if (res.data.code == 200) {
          this.showUpload = true;
          this.showtable = false;
          this.properties = [];
          this.$message.success("取消成功");
          this.form = {
            spaceType: "",
            severType: "",
            styleName: "",
            serverName: "",
          };
        } else {
          this.$message.erroe("取消失败");
        }
      });
    },
    // table页删除
    handleDeleteFields($index, row) {
      // console.log($index, row);
      this.$confirm("确认删除？")
        .then((_) => {
          this.properties.forEach((res, index) => {
            if ($index == index) {
              this.properties.splice(index, 1);
            }
          });
        })
        .catch((_) => {});
    },
    // 加载地图
    initMap() {
      let _this = this;
      this.map = new mapboxgl.Map({
        container: "mapbox-container",
        style: "mapbox://styles/shichao123/clf3b1bxk007801moo0nnl87k",
        center: [118, 25],
        zoom: 14,
        language: "zh-cmn",
        projection: "globe",
      });
      this.map.on("load", () => {
        _this.addGeoJsonLayer();
      });
    },
    addGeoJsonLayer() {
      let geojson = this.mapData;
      let center = turf.center(geojson).geometry.coordinates;
      this.map.addSource("source-01", {
        type: "geojson",
        data: geojson,
      });
      this.map.addLayer({
        id: "layer-01",
        type: "fill",
        source: "source-01",
        // "source-layer": "mvt",
        layout: {
          visibility: "visible",
        },
        paint: {
          "fill-color": "#ABC6EF",
          "fill-outline-color": "#3bb2d0",
          "fill-opacity": 0.6,
        },
      });
      this.map.flyTo({
        center: center,
        zoom: 10,
        speed: 5,
      });
    },
  },
};
</script>

<style scoped>
.data-container {
  width: 100%;
  position: relative;
  display: flex;
  flex-wrap: wrap;
}

.data-upload {
  position: absolute;
  width: 80%;
  left: 50%;
  top: 500px;
  transform: translate(-50%, -50%);
  display: flex;
  justify-content: space-around;
  align-items: center;
}

.data-upload img {
  width: 100px;
  height: 100px;
}
.tuceng_pz {
  width: 500px;
  border-color: #1da1f2;
}
.tuceng_pz .tuceng_pz_son {
  width: 500px;
  border: 1px solid #10a2e1;
  border-radius: 10px;
  padding: 10px 10px 10px 30px;
}
.tuceng_pz .tuceng_pz_son > p {
  text-align: center;
  font-size: 32px;
  color: #00b2ff;
  margin-bottom: 20px;
}
.tuceng_pz .tuceng_pz_son ::v-deep .el-input__inner {
  background-color: transparent;
  border: 1px solid #10a2e1;
  color: #fff;
}
.tuceng_pz .tuceng_pz_son ::v-deep .el-form-item__label {
  color: #10a2e1;
}
.data-table {
  width: 66%;
  height: 890px;
  color: #fafaff;
  box-sizing: border-box;
  margin: 20px;
  border-color: #1da1f2;
}

.data-map {
  width: 600px;
  height: 750px;
  margin-top: 60px;
}

.data-map .map {
  width: 100%;
  height: 100%;
}

::v-deep.data-map .mapboxgl-ctrl-bottom-left {
  display: none !important;
}
::v-deep.data-map .mapboxgl-ctrl-bottom-right {
  display: none !important;
}
.data-sub {
  margin-top: 30px;
  display: flex;
  justify-content: right;
}
</style>
<style>
.data-upload .el-upload-dragger {
  background: none;
  width: 420px;
  height: 150px;
}

.data-table .el-table td,
.data-table .el-table th .is-leaf,
.data-table .el-table--border,
.data-table .el-table--group,
.data-table .el-table,
.data-table .el-table__expanded-cell,
.data-table .el-table th.el-table__cell,
.data-table .el-table tr {
  border-color: #1da1f2;
  background-color: #090930;
  color: #fff222;
}

.data-table .el-table--border::after,
.data-table .el-table--group::after,
.data-table .el-table::before {
  background-color: transparent;
}

/*修改element-ui的table 在鼠标悬停hover时的高亮颜色*/
.data-table .el-table tbody tr:hover > td {
  background-color: black !important;
}

.data-table .el-input__inner,
.data-table .el-select-dropdown,
.data-table .el-scrollbar__thumb {
  position: relative;
  background-color: #090930;
}

.data-table .el-popper[x-placement^="bottom"] .popper__arrow::after {
  border-bottom-color: #090930;
}

.data-table .el-select-dropdown__item.hover,
.data-table .el-select-dropdown__item:hover {
  background-color: #333333;
}

.data-table .el-table .cell {
  overflow: revert;
}

.data-table .el-input__inner {
  color: #fafaff;
}

/* 谷歌 */
.data-table input::-webkit-outer-spin-button,
.data-table input::-webkit-inner-spin-button {
  -webkit-appearance: none;
  appearance: none;
  margin: 0;
}

火狐 .data-table input {
  -moz-appearance: textfield;
}
</style>