<template>
  <div class="f_box">
    
    <div class="f_box_top2">
      <folderFileBoxVue
        :pid="pid"
        :userid="userid"
        :typeArray="typeArray"
        :folderid="folderid"
        :moFolderid="moFolderid"
        :data="data"
        @goCheckType="goCheckType"
      ></folderFileBoxVue>
    </div>

    <div class="f_box_top" v-loading="isLoading">
       
        <div class="t_title">
          <div class="t_title">
            <img style="width: 20px;margin-right: 5px;" src="../../../assets/listfolder2.svg" alt="">
            <el-tooltip class="item" effect="dark" :content="data.name" placement="top">
              <div class="perName">{{ data.name }}</div>    
            </el-tooltip>

          </div>
          <div style="margin-left: 6px;cursor: pointer;" @click="openCanEdit" v-if="userid == data.userid && data.isMo == '2'">
            <img style="width: 11px;" src="../../../assets/xiugai.svg" alt="">
          </div>
        </div>
        
        <div class="t_btn">
           <div v-if="data.isMo == '2'" @click="copyFolder">
            <img style="height: 14px; margin-right: 8px;" src="../../../assets/copyFlieG2.svg" alt="">
            复制
           </div>
           <div v-if="userid == data.userid && data.isMo == '2'"  @click="deleteFile(pid.split('/')[1])">
            <img style="width: 16px;margin-right: 8px;transform: scale(.9);" src="../../../assets/delFlieG.svg" alt="">
            删除
           </div>
        </div>
        <div class="detail">
          <div class="detail_box">
            {{ !data.detail ? '暂无描述' : data.detail }}
          </div>
        </div>

        <div 
        style="height: 1px;border-bottom: 1px #E8EBF0 solid; margin: 16px 0;"
        v-if="check1.length || check2.length || check3.length"
        ></div>

        <div 
        style="font-size: 12px;font-family: PingFang;color: #111824;margin-bottom: 12px;font-weight: 600;"
        v-if="check1.length || check2.length || check3.length"
        >标签</div>
        
        <div class="tag_box" v-if="data.userid == userid && data.isMo == '2'">
          <div class="tag" v-loading="tagLoading1">

              <div class="tags" v-if="check1.length || check2.length || check3.length">
                <div  v-for="(item,index) in tagData1" :key="index+'a'">
                    <span style="background: #F0F4FF;color: #3370FF;" v-if="check1.includes(item.id)">{{ TagList(item) }}</span>
                </div>
                <div  v-for="(item,index) in tagData2" :key="index+'b'">
                  <span style="background: #EDFBF3;color: #039855;" v-if="check2.includes(item.id)">{{ TagList2(item) }}</span>
                </div>
                <div v-for="(item,index) in tagData3" :key="index+'c'">
                  <span style="background: #FFFAEB;color: #DC6803;"  v-if="check3.includes(item.name)">{{ TagList3(item) }}</span>
                </div>
              </div>
              <!-- <div class="tags" v-if="check2.length">
               
              </div>

              <div class="tags" v-if="check3.length">
                
              </div> -->

          </div>
        <div style="height: 1;border-bottom: 1px #E8EBF0 solid;margin: 16px 0;"></div>


        <div style="font-size: 12px;font-family: PingFang;color: #111824;margin-bottom: 12px;font-weight: 600;">
          权限管理
        </div>

            <div class="flieTag">
              <div v-if="data.juri == 1">
                <img src="../../../assets/siyou1.svg" alt="">
                <span>私有</span>
              </div>
              <div v-if="data.juri == 2">
                <img src="../../../assets/siyou3.svg" alt="">
                <span>组织</span>
              </div>
              <div v-if="data.juri == 3">
                <img src="../../../assets/siyou2.svg" alt="">
                <span>公开</span>
              </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>
    </div>

      <el-dialog
        :visible.sync="canEdit"
        width="30%"
        title=""
        class="canEditCss"
        :before-close="handleClose">

          <div class="canEditTit" slot="title">
            <img src="../../../assets/listfolder2.svg" alt="">
            <span>编辑</span>
          </div>

          <div class="canEditFileName">文件名</div>
          <el-input v-model="fileDetail.name" placeholder="输入文件夹名字"></el-input>

          <div class="canEditFileName">描述</div>
          <el-input
            type="textarea"
            :autosize="{ minRows: 2, maxRows: 4}"
            placeholder="输入文件夹描述"
            v-model="fileDetail.detail">
          </el-input>

          <div class="canEditFileName">学科标签</div>
          <selectTag
            v-loading="tagLoading1"
            v-model="fileDetailCheck1"
            :options="tagData1"
            :placeholder="'请选择学科标签'"
            style="width: 65%"
          />
          <!-- @change="updateFolder()" -->
          
          <div class="canEditFileName">年级标签</div>
          <selectTag
            v-loading="tagLoading2"
            v-model="fileDetailCheck2"
            :options="tagData2"
            :placeholder="'请选择年级标签'"
            style="width: 65%; "
            clearable
          />
          <!-- @change="updateFolder()" -->

          <div class="canEditFileName">自定义标签：</div>
          <selectTag2
            v-loading="tagLoading3"
            v-model="fileDetailCheck3"
            :options="tagData3"
            :placeholder="'自定义标签'"
            style="width: 65%;"
            allow-create
            filterable
            clearable
            @change="handleTagChange"
            @deleteTag="deleteTag"
          />
          <!-- @change="handleTagChange" -->
          <div class="canEditFileName" style="margin-bottom: 9px;">权限管理</div>
          
          <div class="tag" >
              <div class="tag_check">
                <el-radio-group  v-model="fileDetail.juri" >
                  <el-radio label="1">私有</el-radio>
                  <el-radio label="2">组织</el-radio>
                  <el-radio label="3">公开</el-radio>
                </el-radio-group>
              </div>
          </div>
          <!-- disabled @change="updateFolder()" -->

        <span slot="footer" class="dialog-footer">
          <el-button @click="canEdit = false">取 消</el-button>
          <el-button type="primary" @click="modifyDetail">确 定</el-button>
        </span>
      </el-dialog>
  </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: {},
      fileDetail:{},
      fileDetailCheck1:[],
      fileDetailCheck2:[],
      fileDetailCheck3:[],

      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: {
    TagList(){
      return function(val) {
       if (this.check1.includes(val.id)) {
        for (let index = 0; index < this.check1.length; index++) {
          if (this.check1[index] == val.id) {
            return val.name
          }
        }
       }
      };
    },
    TagList2(){
      return function(val) {
       if (this.check2.includes(val.id)) {
        for (let index = 0; index < this.check2.length; index++) {
          if (this.check2[index] == val.id) {
            return val.name
          }
        }
       }
      };
    },
    TagList3(){
      return function(val) {
       if (this.check3.includes(val.name)) {
        for (let index = 0; index < this.check3.length; index++) {
          if (this.check3[index] == val.name) {
            return val.name
          }
        }
       }
      };
    },
    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: {
    openCanEdit(){
      this.canEdit = true;
      
      this.fileDetail = JSON.parse(JSON.stringify(this.data))
      this.fileDetailCheck1 = JSON.parse(JSON.stringify(this.check1))
      this.fileDetailCheck2 = JSON.parse(JSON.stringify(this.check2))
      this.fileDetailCheck3 = JSON.parse(JSON.stringify(this.check3))
      
      
      
    },
    modifyDetail(){
      if (!this.fileDetail.name.trim()) {
        this.$message.error("文件夹名字不能为空");
        return;
      }

      let type = this.pid.split("/");
      let params = {
        id: type[1],
        n: this.fileDetail.name,
        d: this.fileDetail.detail,
        st: this.fileDetailCheck1.join(","),
        ct: this.fileDetailCheck2.join(","),
        t: this.fileDetailCheck3.join(","),
        j: this.fileDetail.juri,
        folderid: this.folderid
      };
      // t: this.fileDetailCheck3.join(","),
// return console.log('params2',params);

      this.ajax
        .post(this.$store.state.fileApi + "updateFolder", [params])
        .then(res => {
          this.$message.success("修改成功");
          this.canEdit=false
          this.getData();
        })
        .catch(err => {
          console.error(err);
        });



      // this.updateFolder()
      // this.handleTagChange()
    },
    handleClose(done) {
      done();
    },
    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.fileDetail = JSON.parse(JSON.stringify(res.data[0][0]));

          this.fileDetailCheck1 = res.data[0][0].sub_tag
            ? res.data[0][0].sub_tag.split(",")
            : [];
          this.fileDetailCheck2 = res.data[0][0].class_tag
            ? res.data[0][0].class_tag.split(",")
            : [];
          this.fileDetailCheck3 = res.data[0][0].tag ? res.data[0][0].tag.split(",") : [];

          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(() => {});
    },
    goCheckType(val){
      this.$emit("checkType", val);
    },
    copyFolder() {
      this.isLoading = true;
      let params = [
        {
          n: this.data.name,
          fd: this.data.detail,
          uid: this.userid,
          folderid: this.folderid,
        }
      ];
      this.ajax
        .post(this.$store.state.fileApi + "copyFolder", params)
        .then(res => {
          this.isLoading = false;
          this.$message({
            message: "复制成功",
            type: "success"
          });
          this.$emit("checkType", this.pid.split("/")[0]);
        })
        .catch(err => {
          this.isLoading = false;
          this.$message.error("复制失败");
          console.error(err);
        });
    },
    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() {
      if (!this.data.name.trim()) {
        this.$message.error("文件夹名字不能为空");
        this.canEdit = true;
        return;
      }

      let type = this.pid.split("/");
      let params = {
        id: type[1],
        n: this.data.name,
        d: this.data.detail,
        st: this.check1.join(","),
        ct: this.check2.join(","),
        t: this.check3.join(","),
        j: this.data.juri,
        folderid: this.folderid
      };
      // return console.log('params',params);
      
      this.ajax
        .post(this.$store.state.fileApi + "updateFolder", [params])
        .then(res => {
          this.$message.success("修改成功");
          this.getData();
        })
        .catch(err => {
          console.error(err);
        });
    },
    handleTagChange(value) {
      // console.log('value',value);
      
      const tagArray = this.tagData3;
      const selectedTags = value.flatMap(tag =>
        tag.split(/[,，]/).map(t => t.trim())
      );

      // 去掉选中反而选中不带逗号的值
      const uniqueTags = [
        ...new Set(selectedTags.map(tag => tag.replace(/[,，].*/, "").trim()))
      ];

      const missingTags = uniqueTags.filter(
        selectedTag => !tagArray.some(tag => tag.name === selectedTag)
      );

      // console.log("Selected tags:", uniqueTags);
      // console.log("Missing tags:", missingTags);
      this.fileDetailCheck3 = uniqueTags;
      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;
  border-radius: 8px;
  box-sizing: border-box;
  display: flex;
  gap: 8px;
}

.f_box_top {
  padding: 10px;
  width: 272px;
  padding: 24px;
  flex-shrink: 0;
  box-sizing: border-box;
  height: 100%;
  border-radius: 8px;
  background-color: #fff;
  box-sizing: border-box;
}
.f_box_top2{
  height: calc(100% - 48px);
  flex: 1;
  max-width: calc(100% - 320px);
  display: flex;
  flex-direction: column !important;
  background-color: #fff;
  border-radius: 8px;
  padding: 24px;
}
.t_title{
  display: flex;
  font-weight: 600;
  font-size: 16px;
  /* width: 180px; */
  color: #111842;
}
/* .t_title p{
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
} */
.t_btn{
  display: flex;
  gap: 10px;
  color: #485264;
  padding-top: 8px;
  /* margin: 10px 0; */
}
.t_btn div{
  padding: 6px 12px;
  background: #f4f4f7;
  border-radius: 6px;
  box-sizing: border-box;
  border: 1 #e8ebf0 solid;
  font-size: 12.8px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  border: 1px #E8EBF0 solid;
}
.detail_box{
  font-size: 12.8px;
  color: #667085;
  padding-top: 12px;
  font-family: PingFang;
  -webkit-line-clamp: 5;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
}

.tags{
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  font-family: PingFang;
}
.tags div {
  margin-bottom: 10px;
}
.tags >>> span{
   
    height: 24.38px;
    line-height: 24.38px; 
    padding: 4px 10px;
    border-radius: 6px;
    border: none;
    box-sizing: border-box;
    font-size: 12.8px;
    margin-right: 8px;
}


.flieTag{
  font-size: 12px;
  font-family: PingFang SC;
  /* margin-top: 8px; */
  color: #667085;
  background-color: #F4F4F7;
  height: 55px;
  padding: 6px;
  border-radius: 8px;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 12.8px;
  box-sizing: border-box;
}
.flieTag div{
  display: flex;
  align-items: center;
}
.flieTag img{
  width: 14px;
  margin-right: 5px;
}


















.tag_box > .tag > .tag_title {
  /* margin-top: 10px; */
  display: flex;
  /* flex-direction: column; */
  flex-wrap: wrap;

}
.tag_title div{
  display: flex;
  width: 100%;
  flex-wrap: wrap;
}



.tag_box > .tag > .tag_check {
  display: flex;

}


/* .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;
  align-items: center;
  justify-content: center;
  background: url("../../../assets/icon/classroomObservation/del.svg") no-repeat;
  background-size: 100% 100%;
  box-sizing: border-box;
} */

/* .tag_check_box {
  width: 100%;
  display: flex;
  margin: 0 0 10px;
  flex-shrink: 0;
}
.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;
} */
.canEditCss >>> .el-dialog{
  border-radius: 8px;
  width: 500px !important;
}
.canEditCss >>> .el-dialog__body{
  padding-top: 0;
  padding-bottom: 10px !important;
}
.canEditCss >>> .el-dialog__header{
  background-color: rgb(251, 251, 252);
  border-radius: 8px 8px 0 0;
  font-family: Pingfang;
  border-bottom: .5px rgb(244, 246, 248) solid;
}
.canEditTit{
  display: flex;
  justify-content: flex-start;
  align-items: center;
}
.canEditTit img{
  width: 25px;
  margin-right: 10px;
}
.canEditFileName{
  font-size: 14px;
  color: #111824;
  font-family: PingFang;
  height: 21px;
  line-height: 21px;
  padding-top: 16px;
  margin-bottom: 4px;
}
.perName{
  flex-shrink: 0;
  min-width: 50px;
  max-width: 120px;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}
</style>
