<template>
  <div class="model666">
    <div class="box" v-draggable>
      <div class="boxHeader nav">
        <span></span>
        <span class="boxHeaderTitle">模型选择</span>
        <span>
          <i class="el-icon-close" @click="close"></i>
        </span>
      </div>
      <div class="boxBody custom_scroll_bar">
        <div style="display: flex;justify-content: space-between;">
          <el-input size="small" suffix-icon="el-icon-search" placeholder="输入关键字进行过滤" @input="searchContent"
            v-model="filterText">
          </el-input>
          <div class="modelSet">
            <el-button type="primary" @click="modelSet" size="small">默认模型参数设置</el-button>
          </div>
          <!--<el-button type="primary" @click="searchContent('type')" size="small">搜类型</el-button>-->
          <!--<el-button type="primary" @click="searchContent('junbiao')" size="small">搜军标</el-button>-->
        </div>
        <template v-if="searchRes.length">
          <div class="el-collapse-item__content">
            <template v-for="model in searchRes">
              <div class="itemBox" @click="editModel(model)">
                <div class="imgbox">
                  <img :src="model.poster_url" alt=""></img>
                </div>
                <span>{{ model.model_name }}</span>
              </div>
            </template>
          </div>
        </template>
        <template v-else>
          <el-collapse v-model="activeName" accordion v-if="!filterText" @change="openModel">
            <template v-for="item in modelTypeList">
              <el-collapse-item :title="item.type_name" :name="item.type_id">
                <template v-for="model in item.children">
                  <!-- @dblclick="selectModel(model)" -->
                  <div class="itemBox" @click="editModel(model)" >
                    <div class="imgbox" :class="{ selectModel: editModelId == model.model_id }">
                      <el-image :src="model.poster_url" alt=""></el-image>
                      <!-- + '?' + Math.random() -->
                    </div>
                    <span>{{ model.model_name }}</span>
                  </div>
                </template>
                <template v-if="!item.children || item.children.length == 0">
                  <div style="height: 60px;visibility: hidden"></div>
                </template>
              </el-collapse-item>
            </template>
          </el-collapse>
        </template>
      </div>
    </div>
  </div>
</template>

<script>
import { getModelType } from "../../api/gisAPI";
import {
  getSelectedNode,
  cusAddNodes,
  getNodeData,
  nodeType,
} from "../Tree/treeNode";
import { addSource } from "@/api/gisAPI";
import { leftClick } from "../Tree/entityClick";
import { getIP } from "../../utils";

export default {
  name: "model",
  data() {
    return {
      treeObj: null,
      activeName: "",
      filterText: "",
      modelTypeList: [],
      data: [],
      defaultProps: {
        children: "children",
        label: "label",
      },
      type: "",
      allModels: [],
      searchRes: [],
      arrModel: [],
      editModelData: null,
      editModelId: null,
    };
  },
  methods: {
    modelSet() {
      this.$sendChanel("ModelSetTitle", "默认模型参数设置");
      this.$changeComponentShow(".ModelSetBox", true);
      this.$recvChanel("ModelSetContent", (data) => {
        if (data) {
          localStorage.setItem("ModelSetContent", JSON.stringify(data));
        }
      });
    },
    renderModel(that, data, model) {
      // let p_id = '模型图层'
      let selectedNode = getSelectedNode(this.treeObj);
      let p_id = selectedNode
              ? nodeType[selectedNode.source_type].allowChildren
                ? selectedNode.source_id
                : selectedNode.p_id
              : -1;
      let z
      if (data.positions.length >= 100) {
        that.$message.warning("添加模型数量过多，请减少数量后！");
        return;
      }
      if (data.positions.length > 0) {
        data.positions.forEach(async (position, index) => {
          let source_id = this.$md5(new Date().getTime() + model.model_name + index);
          if (data.type == "面") {
            z = data.rotate;
          } else if (data.type == "线") {
            z = data.rotate[index];
          } else if (data.type == "点") {
            z = 0
          }
          let DbOption = {
            source_id,
            source_name: model.model_name + index,
            source_type: "model",
            p_id,
          };
          let option = {
            id: source_id,
            position,
            name: model.model_name + index,
            show: true,
            scale: 1,
            url: model.model_url,
            maximumScale: 1,
            host: getIP(),
            rotate: {
              x: 0,
              y: 0,
              z
            }
          };
          let Model = await new YJ.Obj.Model(window.Earth1, option);
          window._entityMap.set(option.id, Model);
          Model.onClick = () => {
            leftClick(node);
          };
          let detailOption = JSON.parse(JSON.stringify(Model.options));
          detailOption.url = model.model_id + ".glb";
          let node = getNodeData(DbOption, detailOption);
          addSource(node).then((res) => {
            if ([0, 200].includes(res.code)) {
              // cusRenderNode(DbOption) DbOption.p_id
              cusAddNodes(this.treeObj, DbOption.p_id, [node]);
            }
          });
        });
      }
    },
    editModel(model) {
      let that = this
      let form = JSON.parse(localStorage.getItem("ModelSetContent"))
      if (form) {
        let url = model.model_url;
        let source_id = this.$md5(new Date().getTime() + model.model_name);
        let op = {}
        if (form.spacing) {
          op = {
            id: source_id,
            url,
            type: form.type,
            spacing: form.spacing
          }
        } else {
          op = {
            id: source_id,
            url,
            type: form.type,
          }
        }
        console.log('opopopopopopopopopopopopopop',op);
        
        let models = new YJ.Obj.BatchModel(window.Earth1, op, function (data) {
          that.renderModel(that, data, model);
        })
        this.close();
      } else {
        this.modelSet()
      }
    },
    searchContent(val) {
      if (val) {
        this.searchRes = this.allModels.filter((item) => {
          return item.model_name.indexOf(val) !== -1;
        });
      } else {
        this.searchRes = [];
      }
    },
    selectModel(model) {
      let model_p_id = "模型图层"
      console.log("选中了模型", model, this.type);
      this.close();
      if (this.type == "rightMenu") {
        this.$sendChanel("selectModel", model);
      } else if (this.type == "rightMenuChange") {
        this.$sendChanel("selectModelChange", model);
      } else {
        let selectedNode = getSelectedNode(this.treeObj);
        new YJ.Draw.DrawPoint(window.Earth1).start(async (err, position) => {
          if (err == null || err != false) {
            let source_id = this.$md5(new Date().getTime() + model.model_name);
            let p_id = selectedNode
              ? nodeType[selectedNode.source_type].allowChildren
                ? selectedNode.source_id
                : selectedNode.p_id
              : -1;
            let DbOption = {
              source_id,
              source_name: model.model_name,
              source_type: "model",
              p_id,
            };

            let option = {
              id: source_id,
              position,
              name: model.model_name,
              show: true,
              scale: 1,
              url: model.model_url,
              maximumScale: 1,
              host: getIP(),
            };
            let Model = await new YJ.Obj.Model(window.Earth1, option);
            window._entityMap.set(option.id, Model);
            Model.onClick = () => {
              leftClick(node);
            };
            let detailOption = JSON.parse(JSON.stringify(Model.options));
            detailOption.url = model.model_id + ".glb";
            let node = getNodeData(DbOption, detailOption);
            console.log(node);
            addSource(node).then((res) => {
              if ([0, 200].includes(res.code)) {
                // cusRenderNode(DbOption) DbOption.p_id
                cusAddNodes(this.treeObj, DbOption.p_id, [node]);
              }
            });
          }
        });
      }
    },
    openModel(val) {
      if (val) {
        let arr = this.arrModel
          .filter((item) => item.type_id == val)
          .map((item) => item.children)
          .flat();
        this.modelTypeList.forEach((item) => {
          if (item.type_id == val) {
            item.children = arr;
          }
        });
      }
    },
    open(key = "second") {
      this.searchRes = [];
      this.allModels = [];
      this.modelTypeList = [];
      this.arrModel = [];
      this.filterText = "";
      this.type = key;
      getModelType((res) => {
        if (res.list) {
          this.arrModel = res.list;
          this.modelTypeList = res.list.map(({ children, ...rest }) => rest);
          this.modelTypeList[0].children = res.list[0].children;
          console.log(this.modelTypeList);
          res.list.forEach((item) => {
            if (item.children)
              this.allModels = this.allModels.concat(item.children);
          });
          // this.modelTotal = res.total.list[0].length
        }
      });
    },
    handleNodeClick(data) {
      console.log(data);
    },
    close() {
      this.searchRes = [];
      this.allModels = [];
      this.modelTypeList = [];
      this.activeName = "";
      // this.editModelData = null;
      this.editModelId = null;
      this.$changeComponentShow(".modelBox", false);
    },
  },
  mounted() {
    // this.open()
    this.$recvChanel("getTreeObj", (treeObj) => {
      this.treeObj = treeObj;
      // this.$removeChanel("getTreeObj")
    });
  },
};
</script>

<style lang="scss">
.model666 {
  user-select: none;
  width: 100vw;
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;


  .box {
    width: 30vw;
    height: 21vw;
    display: flex;
    flex-direction: column;
    position: absolute;
    left: 50%;
    top: 45%;
    transform: translate(-50%, -50%);
    margin-top: 16px;
    background: linear-gradient(180deg, rgba(0, 255, 255, 0.2) 0%, rgba(0, 255, 255, 0) 100%), rgba(0, 0, 0, 0.6);
    padding: 10px;
    border: 1.5px solid rgba(0, 255, 255, 1);

    .boxHeader {
      display: flex;
      justify-content: space-between;
      color: #fff;
      font-size: 18px;
      padding: 0.5vh 0;
      padding-top: 6px;
      padding-bottom: 22px;

      .boxHeaderTitle {
        display: inline-block;
        width: 230px;
        height: 34px;
        background: url('../../assets/images/titlebg.png');
        background-size: 100% 100%;
        background-repeat: no-repeat;
        text-align: center;
        line-height: 34px;
      }

      i {
        cursor: pointer;
      }
    }

    .boxBody {
      height: 500px;
      flex: auto;
      overflow-y: auto;

      .modelSet {
        .el-button {
          background: rgba(var(--color-sdk-base-rgb), 0.2);
          border: 1px solid rgba(var(--color-sdk-base-rgb), 0.5);
        }

      }

      .selectModel {
        border: 1px solid red !important;
      }

      .itemBox {
        width: 20%;
        display: flex;
        flex-wrap: wrap;
        flex-direction: column;
        align-items: center;
        color: #fff;
        cursor: pointer;

        .imgbox {
          width: 100px;
          height: 100px;
          padding: 5px;
          background: url('../../assets/images/modelbg.png');
          background-size: 100% 100%;
          background-repeat: no-repeat;
          box-sizing: border-box;
          text-align: center;
          border: 1px solid rgba(0, 0, 0, 0);
        }

        img {
          height: 90px;
          width: 90px;
          vertical-align: middle;
        }

        span {
          text-align: center;
          width: 100px;
          overflow: hidden;
          /* 确保超出容器的文本被裁剪 */
          white-space: nowrap;
          /* 确保文本在一行内显示 */
          text-overflow: ellipsis;
          /* 使用省略号表示文本超出 */
        }
      }

      .el-collapse-item__content {
        padding-top: 20px;
      }

      .el-input {
        width: 50%;
        margin-bottom: 18px;

      }

      .el-input__inner {
        background-color: transparent;
        border: 1px solid rgba(0, 255, 255, 0.5);
        color: #fff;
      }

      .el-input__inner::placeholder {
        color: rgba(173, 241, 255, 1);
      }
    }

    .boxBody::-webkit-scrollbar {
      background: transparent;
    }

    .boxBody::-webkit-scrollbar-thumb {
      background: rgba(0, 255, 255, 1) !important;
    }

    .boxBody::-webkit-scrollbar-track {
      background: rgba(0, 51, 51, .1) !important;
      border-radius: 10px;
    }
  }
}
</style>
