<template>
  <div class="testdiv">
    <div class="divborder newSearchDiv">
      <div class="searchBtn">
        <Button
          type="primary"
          class="success"
          icon="md-add-circle"
          @click="addparent()"
        >
          {{ $t("5500093") }}
        </Button>
        <Button
          type="primary"
          class="fourWord"
          icon="md-download"
          @click="loadexcel()"
        >
          {{ $t("1005") }}
        </Button>
        <Upload
          style="display: inline-block"
          ref="upload"
          name="excel-file"
          :action="action"
          :headers="headers"
          :show-upload-list="false"
          :on-format-error="handleFormatError"
          :on-success="handleSuccess"
          :on-error="handleError"
          :format="['xlsx']"
        >
          <Button type="primary" class="fourWord" icon="md-cloud-upload">
            {{ $t("1006") }}
          </Button>
        </Upload>
      </div>
    </div>
    <Modal :title="$t('5500093')" v-model="addtopmodal" :styles="modalStyle1">
      <div class="modal_body addmodal_body">
        <div class="abs-zone">
          <div class="filter">
            <label style="width: 80px">
              <span><i class="must_i">*</i>{{ this.$t("300080") }}：</span>
            </label>
            <Input
              :placeholder="this.$t('100042')"
              style="width: 180px"
              v-model="topname"
            />
          </div>
        </div>
      </div>
      <div slot="footer">
        <Button @click="cancel()">{{ $t("1033") }}</Button>
        <Button type="primary" @click="addtop()">{{ $t("1011") }}</Button>
      </div>
    </Modal>
    <Modal :title="$t('800078')" v-model="addmodal" :styles="modalStyle1">
      <div class="modal_body addmodal_body">
        <div class="abs-zone" v-if="editZoneDisplayBoolean">
          <div class="filter">
            <label style="width: 80px">
              <span><i class="must_i">*</i> {{ this.$t("300080") }}：</span>
            </label>
            <Input
              :placeholder="this.$t('100042')"
              style="width: 180px"
              v-model="beforeSubmitNodeTitleString"
            />
          </div>
        </div>
      </div>
      <div slot="footer">
        <Button @click="submitNameEditFunc(0)">{{ $t("1033") }}</Button>
        <Button type="primary" @click="submitNameEditFunc(1)">{{
          $t("1011")
        }}</Button>
      </div>
    </Modal>
    <div class="divborder">
      <div class="core">
        <Tree ref="tree" :data="treeContents" :render="renderContent"></Tree>
      </div>
    </div>
  </div>
</template>

<script>
import axios from "@/libs/api.request";

export default {
  data() {
    const publicPath = axios.publicPath;
    return {
      headers: {
        token: localStorage.getItem("token"),
        timestamp: localStorage.getItem("timestamp"),
        nonce: localStorage.getItem("nonce"),
        sign: localStorage.getItem("sign"),
      },
      treeContents: [],
      map: {
        value: "value",
        label: "label",
        children: "children",
        levelid: "levelid",
        expand: true,
      },
      action: publicPath + "config/upload/submit?templateName=LevelSection",
      expand: true,
      root: null,
      editZoneDisplayBoolean: false,
      beforeSubmitNodeTitleString: "",
      edit_root: null,
      edit_node: null,
      edit_data: null,
      isadd: 0,
      addmodal: false,
      islastlevel: false,
      addtopmodal: false,
      topname: "",
    };
  },
  created() {
    this.doTreeContents();
  },
  computed: {
    modalStyle1() {
      return { top: "100px", width: "400px" };
    },
  },
  methods: {
    cancel() {
      this.addtopmodal = false;
    },
    addparent() {
      this.addtopmodal = true;
      this.topname = "";
    },
    addtop() {
      if (!this.topname) {
        this.$Message.error(this.$t("9000136"));
        return;
      }
      axios
        .request({
          url: "/config/ProjectLevelSection/AddLevelSection",
          data: {
            id: 0,
            title: this.topname,
          },
          method: "post",
        })
        .then((res) => {
          if (res.data.ret === 0) {
            this.$Message.error(this.$t(res.data.msg));
          } else {
            this.addtopmodal = false;
            this.$Message.success(this.$t(1));
            this.doTreeContents();
          }
        });
    },
    handleFormatError(file) {
      this.$Message.error(this.$t("950396") + file.name + this.$t("950397"));
    },
    handleSuccess(res) {
      console.log(res);
      if (res.ret == 1) {
        this.doTreeContents();
        this.$Message.success(this.$t("950398"));
      } else {
        if (typeof res.msg != "number") {
          inittip(res.msg);
        } else {
          this.$Message.error(this.$t(`${res.msg}`));
        }
      }
    },
    handleError() {
      this.$Message.error(this.$t("2010006") + "!");
    },
    doTreeContents() {
      axios
        .request({
          url: "/config/ProjectLevelSection/GetSectionTree",
          method: "get",
        })
        .then((res) => {
          this.treeContents = this.convertTree(res.data.data, this.map);
        });
    },
    loadexcel() {
      axios
        .request({
          url: "/config/ProjectLevelSection/GetTemplate",
          method: "get",
        })
        .then((res) => {
          if (res.data.ret == 1) {
            window.location.href = axios.publicPath + res.data.data;
          } else {
            this.$Message.error(this.$t(res.data.msg));
          }
        });
    },
    convertTree(tree, map) {
      const result = [];
      if (tree) {
        tree.forEach((item) => {
          const value = item[map.value];
          const label = item[map.label];
          const levelid = item[map.levelid];
          let children = item[map.children];
          const expand = true;
          if (children && Array.isArray(children) && children.length) {
            children = this.convertTree(children, map);
          }
          result.push({ value, label, children, expand, levelid });
        });
      }
      return result;
    },
    renderContent(h, { root, node, data }) {
      return h(
        "span",
        {
          style: {
            display: "inline-block",
            width: "550px",
          },
        },
        [
          h("span", [
            h("Icon", {
              props: {
                type: "ios-paper-outline",
              },
              style: {
                marginRight: "8px",
              },
            }),
            h("span", data.label),
          ]),
          h(
            "span",
            {
              style: {
                display: "inline-block",
                float: "right",
                marginRight: "32px",
              },
            },
            [
              h("Button", {
                props: {
                  icon: "md-add",
                },
                style: {
                  marginRight: "8px",
                  display: data.levelid === 0 ? "inline-block" : "none",
                },
                on: {
                  click: () => {
                    this.append(data);
                  },
                },
              }),
              h("Button", {
                props: {
                  icon: "md-create",
                },
                style: {
                  marginRight: "8px",
                },
                on: {
                  click: () => {
                    this.openEditName(root, node, data);
                  },
                },
              }),
              h("Button", {
                props: {
                  icon: "ios-close-circle",
                },
                style: {
                  marginRight: "8px",
                },
                on: {
                  click: () => {
                    this.remove(root, node, data);
                  },
                },
              }),
            ]
          ),
        ]
      );
    },
    append(data) {
      axios
        .request({
          url: "/config/ProjectLevelSection/CheckLevel?sectionId=" + data.value,
          method: "get",
        })
        .then((res) => {
          if (res.data.ret == 0) {
            this.$Message.error(this.$t("1590026"));
          } else {
            this.addmodal = true;
            this.editZoneDisplayBoolean = true;
            this.isadd = 1;
            this.beforeSubmitNodeTitleString = "";
            this.edit_data = data;
          }
        });
    },
    remove(root, node, data) {
      if (data.nodeKey == 0) {
        this.$Message.error(this.$t(9200005));
      } else {
        this.$Modal.confirm({
          title: this.$t("1018"),
          width: "290px",
          content: "",
          closable: true,
          okText: this.$t("1004"),
          onOk: () => {
            axios
              .request({
                url:
                  "/config/ProjectLevelSection/delLevelSection?id=" +
                  data.value,
                method: "post",
              })
              .then((res) => {
                if (res.data.ret === 0) {
                  this.$Message.error(this.$t(res.data.msg));
                } else {
                  const parentKey = root.find((el) => el === node).parent;
                  const parent = root.find((el) => el.nodeKey === parentKey)
                    .node;
                  const index = parent.children.indexOf(data);
                  parent.children.splice(index, 1);
                  this.$Message.success(this.$t(1));
                }
              });
          },
        });
      }
    },
    openEditName(root, node, data) {
      this.editZoneDisplayBoolean = true;
      this.edit_root = root;
      this.edit_node = node;
      this.edit_data = data;
      this.addmodal = true;
      if (this.isadd === 1) {
        this.beforeSubmitNodeTitleString = "";
      } else {
        this.beforeSubmitNodeTitleString = this.edit_node.node.label;
      }
    },
    submitNameEditFunc(x) {
      if (!x) {
        this.beforeSubmitNodeTitleString = "";
        this.editZoneDisplayBoolean = false;
        this.addmodal = false;
      } else if (this.isadd === 0) {
        if (this.beforeSubmitNodeTitleString === "") {
          this.$Message.error(this.$t("9000002"));
          return;
        }
        axios
          .request({
            url:
              "/config/ProjectOrganization/UpdateCurrentProjectCustomLevelById",
            data: {
              id: this.edit_node.node.value,
              title: this.beforeSubmitNodeTitleString,
            },
            method: "post",
          })
          .then((res) => {
            if (res.data.ret === 0) {
              this.$Message.error(this.$t(res.data.msg));
            } else {
              this.edit_node.node.label = this.beforeSubmitNodeTitleString;
              this.editZoneDisplayBoolean = false;
              this.addmodal = false;
              this.$Message.success(this.$t(1));
            }
          });
      } else if (this.isadd === 1) {
        if (this.beforeSubmitNodeTitleString === "") {
          this.$Message.error(this.$t("9000002"));
          return;
        }
        axios
          .request({
            url: "/config/ProjectLevelSection/AddLevelSection",
            data: {
              id: this.edit_data.value,
              title: this.beforeSubmitNodeTitleString,
            },
            method: "post",
          })
          .then((res) => {
            if (res.data.ret === 0) {
              this.$Message.error(this.$t(res.data.msg));
            } else {
              this.isadd = 0;
              this.editZoneDisplayBoolean = false;
              this.addmodal = false;
              this.$Message.success(this.$t(1));
              this.doTreeContents();
            }
          });
      }
    },
  },
};
</script>

<style  lang="less" scoped>
.core {
  height: 700px;
  border-radius: 5px;
  padding: 10px;
  overflow-y: auto;
  overflow-x: hidden;
  position: relative;
  background: #ffffff;
  .abs-zone {
    position: absolute;
    width: 100%;
    height: 100%;
    top: 0;
    left: 0;
    background: #ffffff;
    z-index: 1;
    .box {
      position: absolute;
      width: 100%;
      top: 50%;
      left: 0;
      margin-top: -32px;
      text-align: center;
    }
  }
}
.addmodal_body {
  width: 400px !important;
  padding: 0 20px;
  height: 50px !important;
}
.must_i {
  color: red;
  margin-left: 5px !important;
  margin-top: -5px !important;
}
</style>
