<template>
  <div class="bim-setting-viewpoint">
    <el-button class="btn-create" type="primary" @click="CreateViewpoint" @keyup.prevent @keydown.enter.prevent>创建视点</el-button>

    <div style="margin-top: 10px">
      <el-card class="viewpoint-list scroll-box" v-if="viewpointList.length > 0">
        <div v-for="(item, index) in viewpointList" :key="index" class="viewpoint-item" @click="ZoomViewpoint(item)">
          <div class="viewpoint-content">
            <el-image :src="item.imgPath" alt class="viewpoint-image" :preview-src-list="[item.imgPath]" />
            <el-tooltip :content="item.remark" v-if="item.remark">
              <span class="viewpoint-title">{{ item.name }}</span>
            </el-tooltip>
            <span class="viewpoint-title" v-else>{{ item.name }}</span>
          </div>
          <div class="viewpoint-actions">
            <el-tooltip content="默认视点">
              <el-icon @click="DefaultViewpoint(item, index)" :color="item.isOvert?'#409eff':'#ccc'">
                <SuccessFilled v-if="item.isOvert" />
                <CircleCheck v-if="!item.isOvert" />
              </el-icon>
            </el-tooltip>
            <el-tooltip content="编辑名称">
              <el-icon @click="editViewPoint(item, index)" :color="'#409eff'">
                <Edit />
              </el-icon>
            </el-tooltip>
            <el-tooltip content="删除">
              <el-icon @click="DelViewpoint(item, index)" :color="'#409eff'">
                <Delete />
              </el-icon>
            </el-tooltip>
          </div>
        </div>
      </el-card>
      <el-empty description="暂无视点数据" v-else />
    </div>
    <div class="pagination-container">
      <el-pagination v-model:current-page="pagination.current" v-model:page-size="pagination.pageSize" :page-sizes="[10, 20, 30, 50]" :total="pagination.total" layout="total, prev, pager, next" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
    </div>
    <el-dialog title="保存视点" :width="400" v-model="visible" :before-close="handleCancel" class="dialog-bim-setting-viewpoint" :destroy-on-close="true" :close-on-click-modal="false" :modal="false" :class="{ 'mobile-Model': isMobile }">
      <el-form :model="form" :rules="formRules" ref="form" label-width="80px">
        <el-form-item label="视点名称" prop="title">
          <el-input v-model="form.title" placeholder="请输入视点名称" :rules="[{ required: true, message: '请输入视点名称' }]" @keydown.stop @keyup.stop @keypress.stop/>
        </el-form-item>
        <el-form-item label="缩略图">
          <el-image style="width: 100%" :src="previewImage" :preview-src-list="[previewImage]" />
        </el-form-item>
        <el-form-item label="备注">
          <el-input type="textarea" v-model="form.remark" :rows="4" placeholder="备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="SaveViewpoint">确定</el-button>
      </template>
    </el-dialog>

    <el-dialog title="视点重命名" class="body-noscroll" v-model="visibleRenamed" width="400px" :before-close="() => (visibleRenamed = false)">
      <el-form ref="formRenamedRef" :rules="rulesRenamed" :model="formRenamed" label-width="80px">
        <el-form-item label="漫游名称" prop="name">
          <el-input v-model="formRenamed.name" maxlength="20" placeholder="请输入名称"></el-input>
        </el-form-item>
        <el-form-item label="备注">
          <el-input type="textarea" v-model="formRenamed.remark" :rows="4" placeholder="备注"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="visibleRenamed = false">取消</el-button>
          <el-button type="primary" @click="handSaveRenamed">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { _isMobile } from "@/utils/public";
import { Delete, Picture, Edit } from "@element-plus/icons-vue";
import { viewpointGet, viewpointAdd, viewpointUpdateByName, viewpointDeleteById, updateDefaultViewPoint ,clearDefaultViewPoint} from "@/api/bim/bim.js";
import { ElMessage, ElMessageBox } from "element-plus";
import useUserStore from "@/store/modules/user";
export default {
  components: { Delete, Picture, Edit },
  props: {
    me: {
      type: Object,
      default: () => ({}),
    },
  },
  data() {
    return {
      viewpointList: [],
      visible: false,
      confirmLoading: false,
      form: {
        title: "",
        remark: "",
      },
      formRules: {
        title: [{ required: true, message: "请输入视点名称", trigger: "blur" }],
      },
      previewImage: "",
      imgBlobName: "",
      userName: "",
      projectMessage: {},
      isMobile: false,
      currentPrjId: null,
      currentComId: null,
      pagination: {
        current: 1,
        pageSize: 10,
        total: 0,
      },
      editData: {
        item: null,
        index: null,
      },
      visibleRenamed: false,
      rulesRenamed: {
        name: [
          {
            required: true,
            message: "请输入漫游名称",
          },
        ],
      },
      formRenamed: {
        name: "",
        remark: "",
      },
    };
  },
  mounted() {
    this.isMobile = _isMobile() ? true : false;
    const userStore = useUserStore();
    this.currentPrjId = userStore.currentPrjId;
    this.currentComId = userStore.currentComId;
    this.getList();
  },
  methods: {
    handleSizeChange(val) {
      this.pagination.pageSize = val;
      this.getList();
    },
    handleCurrentChange(val) {
      this.pagination.current = val;
      this.getList();
    },
    getList() {
      const that = this;
      viewpointGet({
        projectId: that.currentPrjId,
        viewType: 1,
        pageSize: this.pagination.pageSize,
        pageNum: this.pagination.current,
      }).then((d) => {
        if (d.code != 0) {
          ElMessage.info("获取视点列表失败!");
          return false;
        }
        that.pagination.total = d.data.pageInfo.totalCount;
        that.viewpointList = d.data.rows;
      });
    },
    CreateViewpoint() {
      const that = this;
      api.Public.saveScreenShot((res) => {
        that.imgBlobName = res;
        that.previewImage = res;
        that.visible = true;
      });
    },
    convertBase64UrlToBlob(urlData) {
      const fd = new FormData();
      var bytes = window.atob(urlData.split(",")[1]); //去掉url的头，并转换为byte
      //处理异常,将ascii码小于0的转换为大于0
      var ab = new ArrayBuffer(bytes.length);
      var ia = new Uint8Array(ab);
      for (var i = 0; i < bytes.length; i++) {
        ia[i] = bytes.charCodeAt(i);
      }
      const blob = new Blob([ab], {
        type: "image/png",
      });
      fd.append("file", blob, new Date().getTime() + ".png");
      return fd;
    },
    ZoomViewpoint(item) {
      const that = this;
      if (item.viewPosition != null) {
        api.Camera.setViewPort(JSON.parse(item.viewPosition));
      }
    },
    editViewPoint(item, index) {
      this.editData.item = item;
      this.editData.index = index;
      this.formRenamed.name = item.name;
      this.formRenamed.remark = item.remark;
      this.visibleRenamed = true;
    },
    handSaveRenamed() {
      this.$refs.formRenamedRef.validate((valid) => {
        if (valid) {
          let data = {
            id: this.editData.item.id,
            name: this.formRenamed.name,
            remark: this.formRenamed.remark,
          };
          viewpointUpdateByName(data).then((res) => {
            if (res.code == 0) {
              this.visibleRenamed = false;
              ElMessage.success("修改成功");
              this.getList();
            } else {
              ElMessage.error("修改失败");
            }
          });
        }
      });
    },
    DefaultViewpoint(item, index) {
      if (item.isOvert == 1) {
        clearDefaultViewPoint(item.id).then((res) => {
          if (res.code == 0) {
            this.visibleRenamed = false;
            ElMessage.success("修改成功");
            this.getList();
          } else {
            ElMessage.error("修改失败");
          }
        });
        return;
      }
      let data = {
        id: item.id,
        projectId: item.projectId,
        viewType: 1,
      };
      updateDefaultViewPoint(data).then((res) => {
        if (res.code == 0) {
          this.visibleRenamed = false;
          ElMessage.success("修改成功");
          this.getList();
        } else {
          ElMessage.error("修改失败");
        }
      });
    },
    DelViewpoint(item, index) {
      let that = this;
      ElMessageBox.confirm(`确定要删除漫游 “${item.name}” 吗？`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        viewpointDeleteById({ id: item.id }).then((res) => {
          if (res.code == 0) {
            that.getList();
            ElMessage.success("删除成功");
          } else {
            ElMessage.error("删除失败");
          }
        });
      });
    },
    SaveViewpoint() {
      const that = this;
      that.$refs.form.validate((valid) => {
        if (!valid) {
          return false;
        }
        const url = "/file/uploadBase64Image";
        that.$http.post(url, { base64Image: that.previewImage }).then((d) => {
          if (d.code != 200) {
            ElMessage.info("上传图片失败!");
            return false;
          }
          api.Camera.getViewPort((p) => {
            let obj = {
              name: this.form.title,
              remark: that.form.remark,
              imgPath: d.data.url,
              viewPosition: JSON.stringify(p),
              projectId: that.currentPrjId,
              comId: that.currentComId,
              modelId: api.m_model.keys().toArray().join(","),
              isOvert: 0,
              level: 0,
              sort: 0,
              viewType: 1,
              processId: 0,
              parentId: 0,
            };
            viewpointAdd({ vo: obj }).then((result) => {
              if (result.code == 0) {
                ElMessage.success("已保存!");
                that.form = {
                  title: [],
                  remark: "",
                };
                that.resetScane();
                that.$refs.form.resetFields();
                that.visible = false;
                that.getList();
              } else {
                ElMessage.error("保存失败!");
              }
            });
          });
        });
      });
    },
    resetScane() {
      api.Camera.stopViewPortRoam();
      api.Model.location(api.m_model.keys().toArray()[0]);
    },
    handleCancel() {
      this.visible = false;
    },
  },
};
</script>

<style lang="scss">
.bim-setting-viewpoint {
  width: 340px;
  padding: 0px 10px 10px;
  .btn-create {
    position: absolute;
    top: 10px;
    right: 40px;
  }
  .pagination-container {
    margin-top: 10px;
    margin-bottom: 20px;
  }
  .viewpoint-list {
    margin-bottom: 10px;
    max-height: 500px;
    overflow-y: auto;

    .viewpoint-item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 8px 0;
      border-bottom: 1px solid #eee;

      .viewpoint-content {
        display: flex;
        align-items: center;
        cursor: pointer;

        .viewpoint-image {
          width: 40px;
          height: 40px;
          object-fit: cover;
          margin-right: 10px;
        }

        .viewpoint-title {
          font-size: 14px;
        }
      }

      .viewpoint-actions {
        display: flex;
        align-content: center;
        .el-icon {
          margin-left: 10px;
          cursor: pointer;
          font-size: 20px;

          &:hover {
            color: var(--el-color-primary);
          }
        }
      }
    }
  }
}
.dialog-bim-setting-viewpoint {
  .el-dialog__body {
    overflow: hidden !important;
  }
}
</style>
