<template>
  <div class="f_box">
    <div class="f_box_top" v-loading="isLoading">
      <div class="title">
        <div class="t_title">{{ data.name }}</div>
        <div class="t_btn">
          <!-- <div class="btn">复制文件夹</div> -->
          <div
            class="btn"
            @click="deleteFile(pid.split('/')[1])"
            v-if="userid == data.userid && data.isMo == '2'"
          >
            删除文件夹
          </div>
        </div>
      </div>
      <div class="detail">
        <textarea
          v-autoHeight="68"
          rows="2"
          class="binfo_input binfo_textarea"
          cols
          v-model="data.detail"
          placeholder="输入文件夹描述"
          v-if="canEdit"
        ></textarea>
        <div
          class="detail_box"
          v-html="data.detail ? data.detail : '暂无描述'"
          v-else
        ></div>
        <div class="editbox" v-if="userid == data.userid && data.isMo == '2'">
          <div class="edit_btn" @click="editConfirm">
            {{ canEdit ? "确定" : "编辑" }}
          </div>
        </div>
      </div>
      <div class="tag_box" v-if="data.userid == userid && data.isMo == '2'">
        <div class="tag">
          <div class="tag_title">标签：</div>
          <div class="tag_check">
            <selectTag
              v-loading="tagLoading1"
              v-model="check1"
              :options="tagData1"
              :placeholder="'前选择学科标签'"
              style="width: calc(100% / 2 - 10px / 2); margin-right: 10px;"
                @change="updateFolder()"
            />
            <selectTag
              v-loading="tagLoading2"
              v-model="check2"
              :options="tagData2"
              :placeholder="'前选择年级标签'"
              style="width: calc(100% / 2 - 10px / 2); margin-right: 10px;"
              @change="updateFolder()"
              clearable
            />
             <selectTag2
              v-loading="tagLoading3"
              v-model="check3"
              :options="tagData3"
              :placeholder="'自定义标签'"
              style="width: 100%; margin-top: 10px;"
              @change="handleTagChange"
              allow-create
              filterable
              clearable
              @deleteTag="deleteTag"
            />
            <!-- <el-select
              v-loading="tagLoading3"
              v-model="check3"
              placeholder="自定义标签"
              clearable
              filterable
              multiple
              collapse-tags
              allow-create
              style="width: 100%; margin-top: 10px;"
              @change="handleTagChange"
            >
              <el-option
                v-for="(item, index) in tagData3"
                :key="index"
                :label="item.name"
                :value="item.name"
              >
                <div class="selectBox">
                  <span>{{ item.name }}</span>
                  <div class="controlsBox">
                    <span
                      class="delSelect"
                      @click.stop="deleteTag(item.id, item.name)"
                    ></span>
                  </div>
                </div>
              </el-option>
            </el-select> -->
          </div>
        </div>
        <div class="tag">
          <div class="tag_title">权限管理：</div>
          <div class="tag_check">
            <el-radio-group v-model="data.juri" @change="updateFolder()">
              <el-radio label="1">私有</el-radio>
              <el-radio label="2">组织内</el-radio>
              <el-radio label="3">全部</el-radio>
            </el-radio-group>
          </div>
        </div>
      </div>
      <div class="tag_box" v-else-if="data.isMo == '2'">
        <div class="tag_check">
          <div class="tag_check_box" v-if="this.check1.length">
            <span>学科：</span>
            <span>{{ getTagName(1) }}</span>
          </div>
          <div class="tag_check_box" v-if="this.check2.length">
            <span>年级：</span>
            <span>{{ getTagName(2) }}</span>
          </div>
          <div class="tag_check_box" v-if="this.check3.length">
            <span>自定义：</span>
            <span>{{ getTagName(3) }}</span>
          </div>
        </div>
      </div>
      <folderFileBoxVue :pid="pid" :userid="userid" :typeArray="typeArray" :folderid="folderid"  :moFolderid="moFolderid" :data="data"></folderFileBoxVue>
    </div>
  </div>
</template>

<script>
import selectTag from './components/selectTag.vue';
import selectTag2 from './components/selectTag2.vue';
import folderFileBoxVue from './folderFileBox.vue';

export default {
  props: {
    pid: {
      type: String
    },
    userid: {
      type: String
    },
    typeArray: {
        type: Array,
    },
    folderid: {
      String: String
    },
    moFolderid: {
      String: String
    }
  },
  components: {
    folderFileBoxVue,
    selectTag,
    selectTag2
  },
  data() {
    return {
      data: {},
      isLoading: false,
      canEdit: false,
      tagLoading1: false,
      tagLoading2: false,
      tagLoading3: false,
      tagData1: [],
      tagData2: [],
      tagData3: [],
      check1: [],
      check2: [],
      check3: []
    };
  },
  watch: {
    pid(newValue, oldValue) {
      this.data = {};
      this.getData();
      this.getTag(1); // 获取标签
      this.getTag(2); // 获取标签
      this.getTag(3); // 获取标签
    }
  },
  computed: {
    getTagName() {
      return function(type) {
        const tagDataMap = {
          1: { data: this.tagData1, check: this.check1, key: "id" },
          2: { data: this.tagData2, check: this.check2, key: "id" },
          3: { data: this.tagData3, check: this.check3, key: "name" }
        };
        const { data, check, key } = tagDataMap[type] || {};
        return data
          ? data
              .filter(item => check.includes(item[key]))
              .map(item => item.name)
              .join("，")
          : "";
      };
    }
  },
  directives: {
    autoHeight: {
      update(el, binding) {
        const { value } = binding;
        if (value && typeof value === "number") {
          el.style.height = `${value}px`;
        } else {
          el.style.height = "auto";
        }
      },
      componentUpdated(el) {
        el.style.height = `${el.scrollHeight + 10}px`;
      }
    }
  },
  mounted() {
    this.getTag(1); // 获取标签
    this.getTag(2); // 获取标签
    this.getTag(3); // 获取标签
    this.getData();
  },
  methods: {
    getData() {
      this.isLoading = true;
      let type = this.pid.split("/");
      let params = {
        id: type[1]
      };
      this.ajax
        .post(this.$store.state.api + "getKnowledgeDetail", [params])
        .then(res => {
          this.isLoading = false;
          this.data = res.data[0][0];
          this.check1 = res.data[0][0].sub_tag
            ? res.data[0][0].sub_tag.split(",")
            : [];
          this.check2 = res.data[0][0].class_tag
            ? res.data[0][0].class_tag.split(",")
            : [];
          this.check3 = res.data[0][0].tag ? res.data[0][0].tag.split(",") : [];
        })
        .catch(err => {
          this.isLoading = false;
          console.error(err);
        });
    },
    getTag(type) {
      const tagLoadings = [
        this.tagLoading1,
        this.tagLoading2,
        this.tagLoading3
      ];
      tagLoadings[type - 1] = true;

      let params = {
        type: type,
        uid: this.userid
      };
      this.ajax
        .post(this.$store.state.api + "getKnowledgeTag", [params])
        .then(res => {
          tagLoadings[type - 1] = false;
          this[`tagData${type}`] = res.data[0];

          const checkKey = `check${type}`;
          if (type == 3) {
            this[checkKey] = this[checkKey].filter(tag =>
              this[`tagData${type}`].some(item => item.name === tag)
            );
          } else {
            this[checkKey] = this[checkKey].filter(tag =>
              this[`tagData${type}`].some(item => item.id === tag)
            );
          }
        })
        .catch(err => {
          tagLoadings[type - 1] = false;
          console.error(err);
        });
    },
    deleteFile(id) {
      this.$confirm("确定删除文件夹吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          let params = [{ ids: id, folderids: this.folderid }];
          this.ajax
            .post(this.$store.state.fileApi + "deleteFolder", params)
            .then(res => {
              this.$message({
                message: "删除成功",
                type: "success"
              });
              this.$emit("checkType", this.pid.split("/")[0]);
            })
            .catch(err => {
              this.$message.error("删除失败");
              console.error(err);
            });
        })
        .catch(() => {});
    },
    editConfirm() {
      if (!this.canEdit) {
        this.canEdit = true;
        this.data.detail += "*1*/123/";
        this.$nextTick(() => {
          this.data.detail = this.data.detail.replace("*1*/123/", "");
          this.$refs.binfo_textarea.focus();
        });
      } else {
        this.canEdit = false;
        this.updateFolder();
      }
    },
    updateFolder() {
      let type = this.pid.split("/");
      let params = {
        id: type[1],
        d: this.data.detail,
        st: this.check1.join(","),
        ct: this.check2.join(","),
        t: this.check3.join(","),
        j: this.data.juri,
        folderid: this.folderid
      };
      this.ajax
        .post(this.$store.state.fileApi + "updateFolder", [params])
        .then(res => {
          this.$message.success("修改成功");
          this.getData();
        })
        .catch(err => {
          console.error(err);
        });
    },
    handleTagChange(value) {
      const tagArray = this.tagData3;
      const missingTags = value.filter(
        selectedTag => !tagArray.some(tag => tag.name === selectedTag)
      );

      console.log("Selected tags:", value);
      console.log("Missing tags:", missingTags);

      missingTags.forEach(tag => this.addTag(tag));
      this.updateFolder();
    },
    addTag(name) {
      let params = {
        n: name,
        uid: this.userid,
        type: 3,
        j: 3
      };
      this.ajax
        .post(this.$store.state.api + "addTag", [params])
        .then(res => {
          this.getTag(3);
        })
        .catch(err => {
          console.error(err);
        });
    },
    deleteTag(id, n) {
      this.$confirm("确定删除这个标签吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.check3 = this.check3.filter(t => t != n);
          this.updateFolder();
          let params = {
            id: id
          };
          this.ajax
            .post(this.$store.state.api + "deleteTag", [params])
            .then(res => {
              this.$message.success("删除成功");
              this.getTag(3);
            })
            .catch(err => {
              console.error(err);
            });
        })
        .catch(() => {});
    }
  }
};
</script>

<style scoped>
.f_box {
  width: 100%;
  /* height: 100%; */
  position: relative;
}

.f_box_top {
  padding: 10px;
  width: 100%;
  box-sizing: border-box;
}

.f_box_top .btn {
  display: flex;
  cursor: pointer;
  align-items: center;
  height: 30px;
  padding: 0 8px;
  background: rgb(0, 97, 255);
  color: #fff;
  box-sizing: border-box;
  border-radius: 4px;
  font-size: 14px;
  align-items: center;
}

.f_box_top .btn + .btn {
  margin-left: 10px;
}

.f_box_top > .title {
  width: 100%;
  display: flex;
  align-items: center;
}

.f_box_top > .title > .t_title {
  font-size: 22px;
  font-weight: bold;
}

.f_box_top > .title > .t_btn {
  margin-left: auto;
  display: flex;
  align-items: center;
}

.binfo_input {
  width: 100%;
  margin: 0;
  padding: 12px 14px;
  display: block;
  min-width: 0;
  outline: none;
  box-sizing: border-box;
  background: none;
  border: none;
  border-radius: 4px;
  background: #fff;
  font-size: 16px;
  resize: none;
  font-family: "Microsoft YaHei";
  min-height: 48px;
  /* border: 1px solid #3682fc00; */
  border: 1.5px solid #cad1dc;
}

.binfo_textarea {
  border: 1.5px solid #cad1dc;
  font-size: 16px;
  resize: none;
  /* background: #f6f6f6; */
  font-family: "Microsoft YaHei";
}

.binfo_input:focus-visible {
  border: 1.5px solid #3681fc !important;
}

.f_box_top > .detail {
  width: 100%;
  margin-top: 10px;
  color: #6d6d6d;
}

.f_box_top > .detail > .detail_box {
  width: 100%;
  white-space: break-spaces;
  word-break: break-all;
}

.f_box_top > .detail > .editbox {
  display: flex;
  align-items: center;
  justify-content: flex-end;
}

.f_box_top > .detail > .editbox > .edit_btn {
  color: #3681fc;
  cursor: pointer;
  margin-top: 5px;
}

.tag_box {
  margin: 10px 0 0 0;
  display: flex;
  align-items: flex-start;
  width: 100%;
}
.tag_box > .tag {
  width: calc(100% / 2 - 20px / 2);
  display: flex;
  align-items: flex-start;
  line-height: 40px;
}

.tag_box > .tag + .tag {
  margin-left: 20px;
}

.tag_box > .tag > .tag_title {
  min-width: fit-content;
}
.tag_box > .tag > .tag_check {
  display: flex;
  flex-wrap: wrap;
}

.tag_box > .tag > .tag_check >>> .el-radio-button__inner,
.el-radio-group,
.tag_box > .tag > .tag_check >>> .el-radio__input,
.tag_box > .tag > .tag_check >>> .el-radio__label,
.tag_box > .tag > .tag_check >>> .el-radio {
  display: flex;
  align-items: center;
  height: 40px;
}

.selectBox {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.controlsBox {
  display: flex;
  align-items: center;
  width: auto;
  height: 100%;
  display: flex;
}

.delSelect {
  width: 16px;
  height: 16px;
  /* display: none; */
  align-items: center;
  justify-content: center;
  background: url("../../../assets/icon/classroomObservation/del.svg") no-repeat;
  background-size: 100% 100%;
  box-sizing: border-box;
  /* transform: translateY(7px); */
}

.tag_check_box {
  width: 100%;
  display: flex;
  margin: 0 0 10px;
  flex-wrap: nowrap;
}
.tag_check_box > span:nth-child(1) {
  min-width: 65px;
  text-align-last: justify;
}
.tag_check_box > span:nth-child(2) {
  word-break: break-all;
}
</style>
