<template>
  <div
    class="form-container"
    v-loading="loading"
    element-loading-text="拼命加载中"
    element-loading-spinner="el-icon-loading"
    element-loading-background="rgba(0, 0, 0, 0.8)"
  >
    <div
      style="
        height: 50px;
        margin-bottom: 40px;
        font-size: 16px;
        color: #fff;
        font-weight: bold;
        border-bottom: 1px solid rgba(255, 255, 255, 0.1);
      "
    >
      <span
        style="font-weight: 1000; font-size: 20px; cursor: pointer"
        @click="$router.push({ path: '/upload_type_selected' })"
        ><i class="el-icon el-icon-back"></i
      ></span>
      导入ShpFile数据
    </div>
    <div class="title">
      <el-steps :active="currentStep" align-center>
        <el-step
          title="文件上传"
          description="选择ShpFile格式模板文件并配置服务基础信息"
        ></el-step>
        <el-step
          title="信息配置"
          description="根据中文字段名称配置英文注释用于服务发布"
        ></el-step>
        <el-step
          title="创建完成"
          description="服务创建完成在服务列表中查看服务"
        ></el-step>
      </el-steps>
    </div>
    <div class="first-step" v-if="currentStep == 1">
      <div class="upload-iocn-box">
        <div class="upload-icon-bg2"></div>
        <div class="upload-icon-bg">
          <p class="upload-iocn">
            <img src="/images/upload.png" alt="" />
          </p>
          <p class="upload-icon-text">
            只能选择后缀（.zip）格式压缩文件<br />（文件大小不能超过50MB）
          </p>
          <p>
            <el-upload
              class="upload-demo"
              :action="''"
              :on-preview="handlePreview"
              :before-upload="beforeUpload"
              multiple
              :limit="3"
              :on-exceed="handleExceed"
              :file-list="fileList"
            >
              <el-button size="small" type="primary">选择文件</el-button>
            </el-upload>
          </p>
          <p style="margin-top: 10px; color: #ccc">
            {{ file ? file.name : null }}
          </p>
        </div>
      </div>
      <div class="form-box">
        <el-form
          ref="forms"
          :model="form"
          :rules="rules"
          label-width="120px"
          size="small"
        >
          <el-form-item label="服务名称" prop="serverName">
            <el-input
              placeholder="请输入服务名称"
              style="width: 360px"
              v-model="form.serverName"
              @change="servernameChange"
            ></el-input>
          </el-form-item>
          <el-form-item label="空间参考" prop="spaceType">
            <el-select
              style="width: 360px"
              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="服务类型" prop="severType">
            <el-select
              style="width: 360px"
              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"
              style="width: 280px"
              placeholder="请选择图层样式"
            >
              <el-option
                v-for="(value, key) in getDictthree"
                :key="key"
                :label="value"
                :value="value"
              ></el-option>
            </el-select>
            <el-button type="primary" @click="createStyle">创建样式</el-button>
          </el-form-item>

          <el-form-item style="margin-top: 60px; text-align: right">
            <el-button
              type="default"
              @click="$router.push({ path: '/upload_type_selected' })"
              >取消</el-button
            >
            <el-button
              type="primary"
              size="small"
              icon="el-icon-check"
              @click.native="onSubmit('form')"
              >创建</el-button
            >
          </el-form-item>
        </el-form>
      </div>
    </div>

    <div
      class="second-step"
      v-loading="loading"
      element-loading-text="拼命加载中"
      element-loading-spinner="el-icon-loading"
      element-loading-background="rgba(0, 0, 0, 0.8)"
      v-if="currentStep == 2"
    >
      <div class="table-container">
        <el-table
          :data="tableHeader"
          height="320"
          border
          size="mini"
          style="width: 100%"
        >
          <el-table-column prop="name" label="原始字段名称" width="180">
          </el-table-column>
          <el-table-column prop="type" label="数据类型" width="180">
          </el-table-column>
          <el-table-column prop="length" label="数据长度"> </el-table-column>
          <el-table-column label="英文名称">
            <template slot-scope="scope">
              <el-input v-model="scope.row.en_name" size="mini"></el-input>
              <p
                style="color: #ff0000; font-size: 12px"
                v-if="!regExp.test(scope.row.en_name)"
              >
                使用小写字母、数字、下划线的组合
              </p>
            </template>
          </el-table-column>
          <el-table-column label="中文注释">
            <template slot-scope="scope">
              <el-input v-model="scope.row.cn_name" size="mini"></el-input>
            </template>
          </el-table-column>

          <el-table-column label="删除">
            <template slot-scope="scope">
              <el-button
                size="mini"
                icon="el-icon-delete"
                type="warning"
                @click="delColumn(scope)"
              ></el-button>
            </template>
          </el-table-column>
        </el-table>

        <div
          style="
            text-align: right;
            position: absolute;
            bottom: 20px;
            width: calc(100% - 160px);
          "
        >
          <el-button
            type="default"
            size="large"
            @click="$router.push({ path: '/upload_type_selected' })"
            >取消</el-button
          >
          <el-button
            type="primary"
            size="large"
            icon="el-icon-check"
            @click.native="createService"
            >创建</el-button
          >
        </div>
      </div>
    </div>

    <div class="third-step" v-if="currentStep == 3">
      <el-result
        icon="success"
        title="服务创建成功"
        subTitle="服务创建成功，请在服务列表中心查看服务"
      >
        <template slot="extra">
          <el-button
            type="primary"
            size="medium"
            @click="$router.push({ path: '/ServiceList' })"
            >服务列表</el-button
          >
        </template>
      </el-result>
    </div>

    <StyleConfig @yschange="styleUpdate" v-if="StyleConfigShow"></StyleConfig>
  </div>
</template>

<script>
import axios from "axios";
import { getMethodCommon, postMethodCommon } from "../../api/Api";
import { globalApi } from "../../api/urlPatterns.js";
import StyleConfig from "../data_manage/yangshi";
import {
  getDictone,
  getDicttwo,
  getLayerStyle,
  checkServerName,
  uploadFile,
} from "../../api/datamange";

export default {
  name: "data_upload",
  components: {
    StyleConfig,
  },
  data() {
    return {
      loading: false,
      StyleConfigShow: false,
      headers: {
        Authorization: localStorage.getItem("X-Token") || "",
      },
      form: {
        serverName: null,
      },
      rules: {
        serverName: [
          { required: true, message: "请输入服务名称", trigger: "blur" },
        ],
        spaceType: [
          { required: true, message: "请选择参考系", trigger: "blur" },
        ],
        severType: [
          { required: true, message: "请输选择服务类型", trigger: "blur" },
        ],
      },
      getDictone: [],
      getDicttwo: [],
      getDictthree: [],
      fileList: [],
      file: null,
      currentStep: 1,
      tableHeader: [],
      regExp: /^[a-z0-9_]+$/,
    };
  },
  created() {
    getDictone().then((res) => {
      this.getDictone = res.data.data;
    });
    getDicttwo().then((res) => {
      this.getDicttwo = res.data.data;
    });
    getLayerStyle().then((res) => {
      this.getDictthree = res.data.data.style.names;
    });
  },
  methods: {
    //校验服务名
    servernameChange() {
      checkServerName(this.form.serverName).then((res) => {
        if (res.data.code == 200) {
          if (res.data.data > 0) {
            this.$message.error("服务名称已存在,请重新输入");
            this.form.serverName = "";
          }
        }
      });
    },
    delColumn(scope) {
      this.tableHeader.splice(scope.$index, 1);
    },
    styleUpdate() {
      getLayerStyle().then((res) => {
        this.getDictthree = res.data.data.style.names;
      });

      this.StyleConfigShow = false;
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handlePreview(file) {
      console.log(file);
    },
    handleExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${
          files.length + fileList.length
        } 个文件`
      );
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`);
    },
    beforeUpload(file) {
      console.log(file);
      this.file = file;
      let extension = file.name.substring(file.name.lastIndexOf(".") + 1);
      let size = file.size / 1024 / 1024;
      if (extension !== "zip") {
        this.$message.warning("只能上传后缀是.zip的文件");
        return false;
      }
      if (size > 100) {
        this.$message.warning("文件大小不得超过100M");
        return false;
      }
      return false;
    },
    handleFileChange(file, fileList) {
      let f = { ...file };
    },

    onSubmit() {
      this.loading = true;
      if (this.file == null) {
        this.$message({ type: "warning", message: "请选择文件!" });
        return false;
      }
      this.$refs["forms"].validate((valid) => {
        if (valid) {
          let formData = new FormData();
          formData.append("file", this.file);
          formData.append("serverName", this.form.serverName);
          formData.append("spaceType", this.form.spaceType);
          formData.append("severType", this.form.severType);
          let _this = this;
          //   axios
          //     .post(globalApi.BASE_URL + "/geoserver/uploadFile", formData, {
          //       headers: {
          //         "Content-Type": "multipart/form-data",
          //         Authorization: localStorage.getItem("X-Token") || "",
          //       },
          //     })
          uploadFile(formData)
            .then((res) => {
              if (res.data.code == 200) {
                this.loading = false;
                _this.tableName = res.data.data.tableName;
                _this.form.dataType = res.data.data.dataType;
                let arr = res.data.data.heads;
                _this.tableHeader = [];
                arr.forEach((item, index) => {
                  let obj = {
                    name: item.name,
                    type: item.type,
                    length: item.length,
                    en_name: item.name.toLowerCase(),
                    cn_name: item.name,
                  };
                  _this.tableHeader.push(obj);
                });
                _this.currentStep = 2;
              }
            })
            .catch((err) => {
              // 报错
              this.loading = false;
              //   console.log(err);
            });
        } else {
          return false;
        }
      });
    },
    createService() {
      this.loading = true;
      let valid = [];
      this.tableHeader.forEach((item, index) => {
        let isEn = this.regExp.test(item.en_name);
        valid.push(isEn);
      });
      let isEn = valid.find((item, index) => {
        return item != true;
      });

      if (isEn == false) {
        return;
      }

      let _this = this;
      let headerJsonString = {};
      let newHeader = [];
      this.tableHeader.forEach((item, index) => {
        headerJsonString[item.en_name.toLowerCase()] = item.cn_name;
        let obj = {
          name: item.name,
          type: item.type,
          length: item.length,
          refName: item.en_name,
        };
        newHeader.push(obj);
      });

      let formData = {
        dataType: this.form.dataType,
        severType: this.form.severType,
        spaceType: this.form.spaceType,
        tableName: this.tableName,
        newHeads: newHeader,
        styleName: this.form.styleName,
        serverName: this.form.serverName,
        refRelation: JSON.stringify(headerJsonString),
      };

      postMethodCommon("/geoserver/saveData", formData)
        .then((res) => {
          if (res.data.code == 200) {
            getMethodCommon("/geoserver/publishLayer/" + _this.tableName).then(
              (response) => {
                this.loading = false;
                _this.$message({
                  type: "success",
                  message: "上传服务成功",
                });
                _this.currentStep = 3;
              }
            );
          }
        })
        .catch((err) => {
          //   console.log(err);
          //   this.$message.error(err);
          this.loading = false;
        });
    },
    handleSuccess(response, file, fileList) {
      console.log("response", response);
      this.tableName = response.msg;
    },
    createStyle() {
      this.StyleConfigShow = true;
      // this.$router.push({'path':'/layer_style_config'})
    },
  },
};
</script>

<style scoped>
.form-container {
  width: 1200px;
  padding: 20px 20px;
  height: 700px;
  background: #162258;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

.title {
  width: 100%;
  height: 160px;
  font-size: 18px;
  font-weight: bold;
  color: #fff;
  text-indent: 20px;
}
::v-deep .el-upload-dragger {
  background: none;
  border: 1px solid #108eff;
  color: #fff;
  margin: 20px auto;
  width: 400px;
  padding: 20px;
}
::v-deep .el-upload-dragger .el-upload__text {
  color: #ccc;
}
::v-deep .el-upload-list__item-name {
  height: 30px;
}

::v-deep .el-input__inner {
  background: none;
  border-radius: 0px;
  border-color: #108eff;
  color: #ccc;
}

::v-deep .el-form-item__label {
  color: #ccc;
}
.form-box {
  width: calc(50% - 100px);
  height: calc(100% - 280px);
  float: left;
  margin-left: 100px;
  margin-top: 20px;
}

.table-container {
  width: 1040px;
  margin: 0px auto;
}

.upload-iocn-box {
  width: calc(50% - 280px);
  height: calc(100% - 380px);
  float: left;
  text-align: center;
  position: relative;
  background: #162258;
  margin-top: 25px;
  margin-left: 120px;
}

.upload-icon-bg {
  width: 100%;
  height: 100%;
  position: absolute;
  top: 0px;
  left: 0px;
  background: #162258;
  z-index: 2;
}

.upload-iocn-box::after {
  content: "";
  width: 40px;
  height: 40px;
  background: #108eff;
  position: absolute;
  top: -3px;
  left: -3px;
  z-index: 1;
  border-radius: 1px;
}

.upload-iocn-box::before {
  content: "";
  width: 40px;
  height: 40px;
  background: #108eff;
  position: absolute;
  top: -3px;
  right: -3px;
  border-radius: 1px;
  z-index: 1;
}

.upload-icon-bg2::after {
  content: "";
  width: 40px;
  height: 40px;
  background: #108eff;
  position: absolute;
  bottom: -3px;
  left: -3px;
  border-radius: 1px;
  z-index: 1;
}

.upload-icon-bg2::before {
  content: "";
  width: 40px;
  height: 40px;
  background: #108eff;
  position: absolute;
  bottom: -3px;
  right: -3px;
  border-radius: 1px;
  z-index: 1;
}

.upload-iocn-box img {
  width: 140px;
}
.upload-iocn {
  margin-top: 10px;
}
.upload-icon-text {
  font-size: 14px;
  color: #ccc;
  margin: 20px 0px;
}

::v-deep .el-button {
  border-radius: 0px;
}
::v-deep .el-step__icon-inner {
  text-align: center;
  text-indent: 0px;
}

::v-deep .el-step__title.is-process {
  color: #fff;
}
::v-deep .el-step__description.is-process {
  color: #fff;
}

::v-deep .el-table {
  background: none;
}

::v-deep .el-form-item__label {
}

::v-deep .el-form-item {
  margin-bottom: 25px;
}

::v-deep .el-result__title p {
  color: #fff;
}

::v-deep .el-result__subtitle p {
  color: #ccc;
}

::v-deep .el-table td.el-table__cell,
.el-table th.el-table__cell.is-leaf {
}

::v-deep .el-table th.el-table__cell {
  background: #162258;
  color: #fff;
}

::v-deep .el-table tr {
  background: #162258;
  color: #fff;
}

::v-deep .el-table .el-table__body tr:hover > td {
  background-color: rgba(255, 255, 255, 0.1) !important;
}

::v-deep .el-table .el-table__body tr.current-row > td {
  background-color: rgba(255, 255, 255, 0.1) !important;
}
</style>