<template>
  <div id="TPcontainer">
    <el-container>
      <el-aside width="160px" style="text-align: left">
        <el-menu router :default-active="this.$route.path">
          <el-submenu index="1">
            <template slot="title">
              <i class="el-icon-menu"></i>基础配置</template
            >
            <el-menu-item-group>
              <el-menu-item
                :index="'/home/' + name + '/' + key + '/' + id + '/drawtool'"
                class="{'isActive': !active}"
              >绘图工具</el-menu-item
              >
              <el-menu-item
                :index="'/home/' + name + '/' + key + '/' + id + '/position'"
                class="{'isActive': !active}"
              >定位方式</el-menu-item
              >
              <el-menu-item
                :index="'/home/' + name + '/' + key + '/' + id + '/basemap'"
                class="{'isActive': !active}"
              >地图配置</el-menu-item
              >
            </el-menu-item-group>
          </el-submenu>
          <el-submenu index="0">
            <template slot="title">
              <i class="el-icon-menu"></i>数据表
              <el-button
                size="mini"
                type="primary"
                id="buttonStyle"
                plain
                @click="addTable"
                v-if="getInfo == '1'"
              >+</el-button
              >
            </template>
            <el-menu-item
              v-for="(item, i) in tables"
              :key="i"
              :index="
                '/home/' + name + '/' + key + '/' + id + '/' + i + '/tablecon'
              "
            >{{ item.name }}</el-menu-item
            >
          </el-submenu>
        </el-menu>
      </el-aside>
      <el-container>
        <div id="buttomC">
          <el-button
            v-if="getInfo == '1'"
            id="buttonS"
            type="primary"
            @click="uploadConfig()"
          >提交</el-button
          >
          <el-button id="buttonS" type="primary" @click="toMain()"
          >取消并返回上页</el-button
          >
        </div>
        <el-main style="margin-top: 55px">
          <router-view class="view"></router-view>
        </el-main>
      </el-container>
    </el-container>
  </div>
</template>

<script>
/* eslint-disable */
import { store } from "@/components/vuex/store.js";
import { ajax as request } from "@/request.js";
import Qs from "qs";

export default {
  name: "Meta",
  data: function () {
    return {
      getInfo: sessionStorage.getItem("getInfo"),
      key: "",
      name: "",
      id: "-1",
      active: true,
      contextMenuTarget: null,
      contextMenuVisible: false,
    };
  },
  methods: {
    initConfig() {
      let config1 = sessionStorage["Data"];
      if (config1) {
        config1 = JSON.parse(config1);
        this.$store.dispatch("updateData", { config: config1 });
      } else if (this.id != "-1") {
        let that = this;
        request({
          url: "/xml/requesting",
          method: "post",
          params: {
            id: that.id,
          },
        }).then(function (response) {
          if (response.data.data) {
            //获取数据存入config
            var jsondata = JSON.parse(response.data.data);
            // jsondata = that.changeC(jsondata);
            that.$store.dispatch("updateData", { config: jsondata });
            sessionStorage["Data"] = JSON.stringify(that.$store.state.config);
          } else if (response.data.status == "401") {
            that.$alert(response.data.message);
            that.$router.push({ path: "/login" });
          }
        });
      }
    },
    toMain() {
      sessionStorage.removeItem("Data");
      var config1 = {
        meta: {
          drawtool: {},
          position: [],
          basemap: [],
        },
        tables: [],
      };
      this.$store.dispatch("updateData", { config: config1 });
      // 检查当前路径，避免重复导航
      if (this.$route.path !== "/main") {
        this.$router.push({ path: "/main" }).catch(err => {
          // 忽略 NavigationDuplicated 错误
          if (err.name !== 'NavigationDuplicated') {
            console.error('路由导航错误:', err)
          }
        })
      }
    },
    addTable() {
      this.$router.push({
        path:
          "/home/" + this.name + "/" + this.key + "/" + this.id + "/creattable",
      });
    },
    uploadConfig() {
      let that = this;
      this.$confirm("确认提交任务？", "提示", {
        cancelButtonText: "取消",
        confirmButtonText: "确定",
        type: "warning",
      })
        .then(() => {
          //移除isgroup
          // var datadeleteIsGroup = that.changeE(that.$store.state.config);
          var datadeleteIsGroup = that.$store.state.config;
          for (var i = 0; i < datadeleteIsGroup.tables.length; i++) {
            for (
              var j = 0;
              j < datadeleteIsGroup.tables[i].fields.length;
              j++
            ) {
              delete datadeleteIsGroup.tables[i].fields[j].group;
              if (datadeleteIsGroup.tables[i].fields[j].identity == true) {
                datadeleteIsGroup.tables[i].fields[j].autoIncrement = true;
              } else {
                datadeleteIsGroup.tables[i].fields[j].autoIncrement = "";
              }
            }
          }
          if (datadeleteIsGroup.meta.drawtool.length == 0) {
            that.$alert("请选择绘图工具！", "提示", {
              confirmButtonText: "确定",
            });
            return;
          }
          if (datadeleteIsGroup.meta.position.length == 0) {
            that.$alert("请选择定位方式！", "提示", {
              confirmButtonText: "确定",
            });
            return;
          }
          if (datadeleteIsGroup.meta.basemap.length == 0) {
            that.$alert("请添加地图图层！", "提示", {
              confirmButtonText: "确定",
            });
            return;
          }
          if (datadeleteIsGroup.tables.length == 0) {
            that.$alert("请添加数据表！", "提示", {
              confirmButtonText: "确定",
            });
            return;
          }

          // 修改datadeleteIsGroup内容
          const newConfig = {
            name: "测试任务",
            key: "test",
            config: {
              meta: {
                drawtool: datadeleteIsGroup.meta.drawtool,
                position: datadeleteIsGroup.meta.position,
                basemap: datadeleteIsGroup.meta.basemap.map(item => ({
                  ...item,
                  url: ""
                }))
              },
              tables: datadeleteIsGroup.tables.map(table => ({
                ...table,
                fields: table.fields.map(field => ({
                  ...field,
                  index: field.index || "",
                  name: field.name || "",
                  type: field.type || "",
                  selector: field.selector || [],
                  select: field.select || "",
                  mode: field.mode || "",
                  parentID: field.parentID || "",
                  resultType: field.resultType || "",
                  geometry: field.geometry || "",
                  required: field.required || "",
                  identity: field.identity || "",
                  uploadName: field.uploadName || "",
                  autoDate: field.autoDate || "",
                  show: field.show || "",
                  enable: field.enable || "",
                  script: field.script || "",
                  associate: field.associate || "",
                  collection: field.collection || "",
                  autoIncrement: field.autoIncrement || ""
                }))
              }))
            },
            id: "1",
            introduction: "aaa",
            taskUploadTime: "23:00"
          };

          if (this.id == "-1") {
            request({
              url: "/task/createTask",
              method: "post",
              params: {
                configString: JSON.stringify(newConfig),
              },
            }).then(function (response) {
              if (response.data.success) {
                //清空config和本地缓存
                sessionStorage.removeItem("Data");
                sessionStorage.removeItem("daytaskNum");
                sessionStorage.removeItem("taskUploadTime");
                var config1 = {
                  meta: {
                    drawtool: {},
                    position: [],
                    basemap: [],
                  },
                  tables: [],
                };
                that.$store.dispatch("updateData", { config: config1 });
                // 检查当前路径，避免重复导航
                if (that.$route.path !== "/main") {
                  that.$router.push({ path: "/main" }).catch(err => {
                    // 忽略 NavigationDuplicated 错误
                    if (err.name !== 'NavigationDuplicated') {
                      console.error('路由导航错误:', err)
                    }
                  })
                }
                that.$notify.success({
                  title: "提示",
                  message: "提交成功",
                });
              } else if (response.data.status == "401") {
                that.$alert(response.data.message);
                that.$router.push({ path: "/login" });
              } else {
                that.$notify.error({
                  title: "提示",
                  message: "提交失败" + "," + response.data.message,
                });
              }
            });
          } else {
            request({
              url: "/task/updateTask",
              method: "post",
              params: {
                id: that.id,
                configString: JSON.stringify(newConfig),
              },
            }).then(function (response) {
              if (response.data.success) {
                //清空config和本地缓存
                sessionStorage.removeItem("Data");
                var config1 = {
                  meta: {
                    drawtool: {},
                    position: [],
                    basemap: [],
                  },
                  tables: [],
                };
                that.$store.dispatch("updateData", { config: config1 });
                that.$notify.success({
                  title: "提示",
                  message: "提交成功",
                });
              } else if (response.data.status == "401") {
                that.$alert(response.data.message);
                that.$router.push({ path: "/login" });
              } else {
                that.$notify.error({
                  title: "提示",
                  message: "提交失败" + "," + response.data.message,
                });
              }
            });
            request({
              url: "/task/checkTaskXmlMD5Code",
              method: "post",
              params: {
                id: that.id,
              },
            }).then(function (response) {
              // 检查当前路径，避免重复导航
              if (that.$route.path !== "/main") {
                that.$router.push({ path: "/main" }).catch(err => {
                  // 忽略 NavigationDuplicated 错误
                  if (err.name !== 'NavigationDuplicated') {
                    console.error('路由导航错误:', err)
                  }
                })
              }
              if (response.data.success) {
                that.$alert(response.data.message, "提示", {
                  confirmButtonText: "确定",
                });
              } else if (response.data.status == "401") {
                that.$alert(response.data.message);
                that.$router.push({ path: "/login" });
              }
            });
          }
        })
        .catch(() => {});
    },
  },
  components: {},
  mounted() {
    let menu = document.getElementsByClassName("el-menu")[0];
    let menuitem = menu.children[1];
    this.contextMenuTarget = menuitem;
    this.initConfig();
  },
  computed: {
    tables() {
      return this.$store.state.config.tables;
    },
  },
  watch: {
    //用watch监听变化
    $route: {
      handler(to, from) {
        this.name = to.params.name;
        this.id = to.params.id;
        if (to.params.key) {
          this.key = to.params.key;
        }
      },
      immediate: true,
    },
  },
  store,
};
</script>

<style>
#buttomC {
  top: 15px;
  right: 25px;
  position: absolute;
}

.el-header {
  background-color: #b3c0d1;
  color: #264672;
  text-align: center;
  line-height: 50px;
}
.el-aside {
  height: 100vh;
  background-color: #d3dce6;
  color: #264672;
  text-align: center;
  line-height: 200px;
}
.right-menu {
  position: fixed;
  background: #fff;
  border: solid 1px rgba(0, 0, 0, 0.2);
  border-radius: 3px;
  z-index: 999;
}
.right-menu a {
  width: 75px;
  height: 28px;
  line-height: 28px;
  text-align: center;
  display: block;
  color: #1a1a1a;
}
.right-menu a:hover {
  background: #eee;
  color: #fff;
}
.right-menu {
  border: 1px solid #eee;
  box-shadow: 0 0.5em 1em 0 rgba(0, 0, 0, 0.1);
  border-radius: 1px;
}
a {
  text-decoration: none;
}
.right-menu a {
  padding: 2px;
}
.right-menu a:hover {
  background: #42b983;
}
.v-modal {
  background: #fff;
}
</style>
