<template>
  <div id="equip_pro">
    <div class="title">设备实例本地名称</div>
    <el-tabs v-model="activeName" @tab-click="handleClick">
      <el-tab-pane label="属性" name="first">
        <div class="property">
          <div class="base-property">
            <div>
              <span>W</span>
              <el-input
                style="width: 74px; margin-left: 6px"
                size="mini"
                v-model="width"
                @input="changeWidth"
                placeholder="请输入内容"
              ></el-input>
            </div>
            <div>
              <span>H</span>
              <el-input
                style="width: 74px; margin-left: 6px"
                size="mini"
                v-model="height"
                @input="changeHeight"
                placeholder="请输入内容"
              ></el-input>
            </div>
          </div>
          <div class="base-property base-property-left">
            <div>
              <span>R</span>
              <el-input
                style="width: 74px; margin-left: 6px"
                size="mini"
                disabled
                @input="changeWidth"
                placeholder="请输入内容"
              ></el-input>
            </div>
          </div>
          <div class="imgUpdate">
            <div class="img-tit">设计图</div>
            <div class="btn-list">
              <el-upload
                class="avatar-uploader"
                action="https://jsonplaceholder.typicode.com/posts/"
                :show-file-list="false"
                :before-upload="beforeAvatarUpload"
              >
                <Button type="default">上传文件</Button>
              </el-upload>
            </div>
          </div>
          <div class="imgUpdate">
            <div class="img-tit">附加数据</div>
            <div class="textarea">
              <el-input type="textarea" @input="changeAnotherMsg" v-model="anotherMsg" :rows="2" placeholder="请输入内容">
              </el-input>
            </div>
          </div>
        </div>
      </el-tab-pane>
      <el-tab-pane label="信息点" name="second">
        <div class="msgPoint-box">
          <Input
            class="baseItemInput"
            :width="200"
            iconType="search"
            placeholder="搜索信息点"
            v-model="getPressMsg"
            @pressEnter="pressEnter"
            @clear="pressEnter"
          />
          <div
            class="msgPoint-list"
            ref="localDom"
            v-show="!pressMsgData.length"
          >
            <div class="type-list" v-for="(item, key) in msgData" :key="key">
              <div class="type-title" @click="clips(item)">
                <i
                  v-bind:class="[
                    item.showChildren ? 'caret-icon-active' : 'caret-icon',
                    'el-icon-caret-bottom',
                  ]"
                ></i>
                <span>{{ item.tagName }}</span>
              </div>
              <el-collapse-transition>
                <ul class="list" v-show="item.showChildren">
                  <li v-for="(a, b) in item.children" :key="'i' + b">
                    <Checkbox
                      :checked="a.checked ? 'checked' : 'uncheck'"
                      @change="changeCheck(a)"
                    />
                    <p>{{ a.name }}</p>
                  </li>
                </ul>
              </el-collapse-transition>
            </div>
          </div>
          <ul class="msgPoint-list-press" v-show="pressMsgData.length">
            <li v-for="(a, b) in pressMsgData" :key="b">
              <Checkbox
                :checked="a.checked ? 'checked' : 'uncheck'"
                @change="changeCheck(a)"
              />
              <p>{{ a.name }}</p>
            </li>
          </ul>
        </div>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>
<script>
import { queryEquipMsg, queryDict } from "@/api/editer";
import bus from "@/bus/bus";

const imgBaseUrl = window.__systemConf.imgServeUri;
// 图上传路径
const imgServeUpload = window.__systemConf.imgServeUpload;
export default {
  props: ["InfoPointList", "EquipData", "equipHeight", "Width", "Height","AnotherMsg"],
  data() {
    return {
      width: 0,
      height: 0,
      activeName: "first",
      width: "",
      height: "",
      msgData: [], //存储二级树
      pressMsgData: [], // 搜索后得信息点数组
      getPressMsg: "", //输入信息
      local: "", //局部加载
      anotherMsg: "", // 附加信息
    };
  },
  methods: {
    // 折叠信息点操作
    clips(item) {
      item.showChildren = !item.showChildren;
    },
    // 点击切换
    handleClick(tab, event) {
      // 设置高度
      if (tab.paneName == "second") {
        const box = document.getElementsByClassName("msgPoint-list")[0];
        const box2 = document.getElementsByClassName("msgPoint-list-press")[0];
        box.style.height = this.equipHeight;
        box2.style.height = this.equipHeight;
      }
    },
    // 设置宽
    changeWidth(val) {
      bus.$emit("updateStyle", "sWidth", val);
    },
    // 设置高
    changeHeight(val) {
      bus.$emit("updateStyle", "sHeight", val);
    },
    // 设置附加信息
    changeAnotherMsg(val) {
      bus.$emit("updateStyle", "anotherMsg", val);
    },
    beforeAvatarUpload(file) {
      let that = this;
      const fileReader = new FileReader();
      fileReader.readAsDataURL(file); //读取图片
      const ftype = file.type;
      const fname = file.name;
      const uploadKey = file.uid;
      const imgType = ftype.split(".")[ftype.length - 1];
      fileReader.addEventListener("load", function () {
        // 读取完成
        let res = fileReader.result;
        //将canvas的base64位图片转换成图片png的file
        var blob = that.dataURLtoBlob(res, ftype);
        //将其转换成file对象
        let file = new File([blob], fname, {
          type: ftype,
          lastModified: Date.now(),
        }); //blob转file

        // try sending
        let reader = new FileReader();
        let fileType = file.name.split(".");
        let imgType = fileType[fileType.length - 1];
        let CreateTime = that.formatDate(new Date(file.lastModified));
        reader.onloadend = function () {
          // 这个事件在读取结束后，无论成功或者失败都会触发
          if (reader.error) {
          } else {
            // 构造 XMLHttpRequest 对象，发送文件 Binary 数据
            var xhr = new XMLHttpRequest();
            xhr.open(
              /* method */
              "POST",
              /* target url */
               imgServeUpload +
                uploadKey +
                "." +
                imgType
            );
            xhr.send(reader.result);
            xhr.onreadystatechange = function () {
              if (xhr.readyState == 4) {
                if (xhr.status == 200) {
                  that.url = imgBaseUrl + uploadKey + "." + imgType;
                  bus.$emit(
                    "updateStyle",
                    "url",
                    imgBaseUrl + uploadKey + "." + imgType
                  );
                }
              }
            };
          }
        };
        reader.readAsArrayBuffer(file);
      });
    },
    dataURLtoBlob(dataURI, type) {
      var binary = atob(dataURI.split(",")[1]);
      var array = [];
      for (var i = 0; i < binary.length; i++) {
        array.push(binary.charCodeAt(i));
      }
      return new Blob([new Uint8Array(array)], { type: type });
    },
    formatDate(now) {
      let year = now.getFullYear();
      let month = now.getMonth() + 1;
      let date = now.getDate();
      let hour = now.getHours();
      let minute = now.getMinutes();
      let second = now.getSeconds();
      return (
        year +
        "-" +
        month +
        "-" +
        (date > 10 ? date : "0" + date) +
        " " +
        hour +
        ":" +
        (minute > 10 ? minute : "0" + minute) +
        ":" +
        (second > 10 ? second : "0" + second)
      );
    },
    // 切换选中选项
    changeCheck(item) {
      item.checked = !item.checked;
      // 添加设备信息点
      Object.assign(item, {
        equipId: this.EquipData.attachObjectIds[0],
      });
      bus.$emit("changeEquipMsgPoint", item);
    },
    // 搜索回车操作
    pressEnter() {
      const list = [];
      if (!this.getPressMsg) {
        this.pressMsgData = [];
        return;
      }
      // 对信息点相同得提取出来
      this.msgData.forEach((item) => {
        item.children.forEach((a) => {
          if (a.name.includes(this.getPressMsg)) {
            list.push(a);
          }
        });
      });
      this.pressMsgData = list;
    },
  },
  watch: {
    EquipData(val) {
      this.msgData = []; //存储二级树
      this.pressMsgData = []; // 搜索后得信息点数组
      this.getPressMsg = ""; //输入信息
      // 启动局部 loading

      this.local = this.$loading({
        el: this.$refs.localDom,
        type: "local",
        size: "min",
      });

      const data = {
        Type: val.properties.classCode,
      };
      queryDict(data)
        .then((res) => {
          let arr = [];
          // 勾选设备中选中的对象
          const msgData = res.content;
          // 设置已经勾选数据
          if (this.InfoPointList && this.InfoPointList.length) {
            msgData.map((item) => {
              item.checked = false;
              this.InfoPointList.forEach((a) => {
                if (a.id == item.id) {
                  item.checked = true;
                }
              });
              return item;
            });
          } else {
            msgData.map((item) => {
              item.checked = false;
              return item;
            });
          }
          //  生成二级树
          msgData.forEach((item) => {
            const itemTag = item.secondTag
              ? item.secondTag
              : item.firstTag
              ? item.firstTag
              : "--";
            if (arr.length) {
              let index = -1;
              arr.forEach((aItem) => {
                if (aItem.tag == itemTag) {
                  index = 1;
                  aItem.children.push(item);
                  aItem.number++;
                }
              });

              if (index == -1) {
                const tag = item.secondTag
                  ? item.secondTag
                  : item.firstTag
                  ? item.firstTag
                  : "--";
                const tagName = item.secondName
                  ? item.secondName
                  : item.firstName
                  ? item.firstName
                  : "--";
                let obj = {
                  tagName: tagName,
                  tag: tag,
                  children: [item],
                  number: 1,
                  showChildren: true,
                };
                arr.push(obj);
              }
            } else {
              const tag = item.secondTag
                ? item.secondTag
                : item.firstTag
                ? item.firstTag
                : "--";
              const tagName = item.secondName
                ? item.secondName
                : item.firstName
                ? item.firstName
                : "--";
              let obj = {
                tagName: tagName,
                tag: tag,
                children: [],
                number: 1,
                showChildren: true,
              };
              obj.children.push(item);
              arr.push(obj);
            }
          });
          this.msgData = arr;
          this.$loading.close(this.local);
        })
        .catch((err) => {
          console.log("接口报错", err);
          this.$loading.close(this.local);
        });
    },
    Width(val) {
      this.width = val;
    },
    Height(val) {
      this.height = val;
    },
    AnotherMsg(val) {
      this.anotherMsg = val;
    },
  },
  mounted() {},
};
</script>
<style lang="less" scoped>
ul,
li,
p {
  margin: 0;
  padding: 0;
  list-style-type: none;
}
#equip_pro {
  .title {
    height: 47px;
    border-bottom: 1px solid #979797;
    color: #646c73;
    font-size: 16px;
    padding-left: 12px;
    box-sizing: border-box;
  }
  .property {
    .base-property {
      display: flex;
      align-items: center;
      justify-content: space-around;
    }
    .base-property-left {
      display: flex;
      align-items: center;
      justify-content: flex-start;
      padding-left: 12px;
      padding-top: 12px;
      box-sizing: border-box;
    }
    .imgUpdate {
      border-top: 1px solid #e4e5e7;
      width: 100%;
      margin-bottom: 16px;
      padding: 0 12px 0 12px;
      box-sizing: border-box;
      .img-tit {
        margin: 12px 0 12px 0;
        color: #646a73;
        font-size: 12px;
      }
    }
  }
  .msgPoint-box {
    width: 100%;
    height: 100%;
    padding: 0 12px 0 12px;
    box-sizing: border-box;
    .msgPoint-list {
      margin-top: 20px;
      height: 100%;
      overflow-y: scroll;
      .type-list {
        .type-title {
          cursor: pointer;
          margin-bottom: 10px;
          span {
            margin-left: 12px;
          }
        }
        ul {
          width: 100%;
          padding-left: 28px;
          li {
            display: flex;
            height: 40px;
            align-items: center;
            justify-content: flex-start;
            cursor: pointer;
            p {
              margin-left: 12px;
            }
            &:hover {
              background: #f5f6f7;
            }
          }
        }
      }
    }
    .msgPoint-list-press {
      margin-top: 12px;
      overflow-y: scroll;
      li {
        display: flex;
        height: 40px;
        align-items: center;
        justify-content: flex-start;
        cursor: pointer;
        p {
          margin-left: 12px;
        }
        &:hover {
          background: #f5f6f7;
        }
      }
    }
  }
  .caret-icon {
    animation: nowhirling 0.2s linear forwards;
  }
  .caret-icon-active {
    animation: whirling 0.2s linear forwards;
  }
  @keyframes whirling {
    0% {
      transform: rotate(-90deg);
      -ms-transform: rotate(-90deg); /* Internet Explorer */
      -moz-transform: rotate(-90deg); /* Firefox */
      -webkit-transform: rotate(-90deg); /* Safari 和 Chrome */
      -o-transform: rotate(-90deg); /* Opera */
    }
    100% {
      transform: rotate(0deg);
      -ms-transform: rotate(0deg); /* Internet Explorer */
      -moz-transform: rotate(0deg); /* Firefox */
      -webkit-transform: rotate(0deg); /* Safari 和 Chrome */
      -o-transform: rotate(0deg); /* Opera */
    }
  }
  @keyframes nowhirling {
    0% {
      transform: rotate(0deg);
      -ms-transform: rotate(0deg); /* Internet Explorer */
      -moz-transform: rotate(0deg); /* Firefox */
      -webkit-transform: rotate(0deg); /* Safari 和 Chrome */
      -o-transform: rotate(0deg); /* Opera */
    }
    100% {
      transform: rotate(-90deg);
      -ms-transform: rotate(-90deg); /* Internet Explorer */
      -moz-transform: rotate(-90deg); /* Firefox */
      -webkit-transform: rotate(-90deg); /* Safari 和 Chrome */
      -o-transform: rotate(-90deg); /* Opera */
    }
  }
}
</style>