<template>
  <ModuleBase ref="base" :type="data.type">
    <template #content>
      <div>
        <div class="tag-edit">
          <template v-for="(tag, i) in data.dynamicTags">
            <el-input
              v-if="tag.isEditing"
              :key="'input-' + i"
              :ref="'inputRefs-' + i"
              v-model="tag.editName"
              class="input-new-tag"
              @blur="handleSave(i)"
              @keydown.enter.native="handleSave(i)"
              @keydown.escape.native="handleCancel(i)"
            />
            <el-tag
              v-else
              :key="'tag-' + i"
              closable
              :style="getTagStyle(tag)"
              class="dynamic-tag"
              @close="handleClose(i)"
              @dblclick.native="handleEdit(i)"
            >
              {{ tag.name }}
            </el-tag>
          </template>

          <el-input
            v-if="inputVisible"
            ref="saveTagInput"
            v-model="inputValue"
            class="input-new-tag"
            @keyup.enter.native="handleInputConfirm"
            @blur="handleInputConfirm"
          />
          <el-button
            v-else
            class="button-new-tag"
            :disabled="data.dynamicTags.length >= 16"
            @click="showAddLabelTextInput"
            >+ 添加标签</el-button
          >
        </div>
      </div>
      <hr style="margin: 16px 0; border-top: 1px solid #ededed" />
      <div class="tag-manager">
        <div class="tag-manager-box">
          <div class="left-area">
            <span class="tag-manager-title">常用标签 </span>
            <span class="tag-manager-text" :style="{ color: closable ? '#165dff' : '' }" @click="editCommonTags()">
              <SvgIcon icon-class="setup" size="14" />管理
            </span>
            <span
              class="tag-manager-text"
              :style="{ color: editLanguage ? '#165dff' : '' }"
              @click="editCommonTagsLanguage"
            >
              <SvgIcon icon-class="multilingual" size="14" />设置多语言
            </span>
          </div>
          <div class="right-area">
            <MultilingualFill
              v-if="multilingualVisible"
              :visible.sync="multilingualVisible"
              :text="editMultilingualTags.name"
              :translations="editMultilingualTags.mult_language_list"
              @SubmitTranslation="handleMultilingualTranslation"
            />
            <el-upload
              class=""
              action="no"
              :auto-upload="true"
              :before-upload="beforeUpload"
              :http-request="customUpload"
              :show-file-list="false"
              accept=".xls"
            >
              <el-button icon="el-icon-upload2">上传标签</el-button>
            </el-upload>
            <el-input v-model="labelName" placeholder="输入关键字" class="search-box">
              <el-button slot="append" icon="el-icon-search" @click="getLabelList()" />
            </el-input>
          </div>
        </div>
        <div class="tag-manager-common tag-edit">
          <el-tag
            v-for="(tag, i) in commonTags"
            :key="i"
            effect="plain"
            size="medium"
            :closable="closable"
            :style="{ cursor: 'pointer', 'background-color': editLanguage ? '#F2F3F3' : '' }"
            @close="handleCloseCommonTag(tag.id)"
            @click="viewToDynamicTags(i)"
          >
            {{ tag.name }}
          </el-tag>
        </div>
        <p v-if="loading">加载中...</p>
        <div class="block">
          <el-pagination
            background
            :current-page="cur_page"
            :page-sizes="[20, 40, 60, 80]"
            :page-size="page_capacity"
            layout="total, prev, pager, next, sizes, jumper"
            :total="total_count"
            @prev-click="changePage"
            @next-click="changePage"
            @current-change="changePage"
            @size-change="changePageSize"
          />
        </div>
      </div>
    </template>
  </ModuleBase>
</template>
<script>
import { fileUpload } from '@/api/app';
import { getLabelData, labelColorList } from '@/views/book/courseware/data/label';
import { AddLabel, DeleteLabel, PageQueryLabelList, ImportLabel, UpdateLabel } from '@/api/project.js';
import ModuleMixin from '../../common/ModuleMixin';
export default {
  name: 'LabelPage',
  mixins: [ModuleMixin],
  data() {
    return {
      labelColorList,
      data: getLabelData(),
      inputVisible: false,
      inputValue: '',
      closable: false,
      commonTags: [], // 常用标签
      page_capacity: 20,
      cur_page: 1,
      total_count: 0,
      loading: false,
      labelName: '',
      editLanguage: false, // 编辑多语言
      editMultilingualTags: {},
      editLable: false,
    };
  },
  created() {
    this.getLabelList();
  },
  methods: {
    handleEdit(index, event) {
      this.data.dynamicTags
        .filter((x) => x.isEditing)
        .forEach((tag, i) => {
          if (tag.isEditing && i !== index) {
            this.$set(this.data.dynamicTags[i], 'isEditing', false);
            this.$set(this.data.dynamicTags[i], 'editName', null);
          }
        });

      this.$set(this.data.dynamicTags[index], 'isEditing', true);
      this.$set(this.data.dynamicTags[index], 'editName', this.data.dynamicTags[index].name);

      this.$nextTick(() => {
        const input = this.$refs[`inputRefs-${index}`];
        if (input && input.length > 0) {
          input[0].focus();
        }
      });

      this.editLable = true;
    },

    // 保存编辑
    handleSave(index) {
      if (!this.editLable) return;
      const en = this.data.dynamicTags[index];
      const newName = en.editName.trim();

      if (newName) {
        en.name = newName;
        UpdateLabel(en)
          .then(() => {
            this.$set(this.data.dynamicTags[index], 'isEditing', false);
            this.$set(this.data.dynamicTags[index], 'name', newName);
            this.$message.success('设置成功!');
            this.cur_page = 1;

            this.getLabelList();

            this.editLable = false;
          })
          .catch((e) => {
            console.error(e);
          });
      }
    },

    // 取消编辑
    handleCancel(index) {
      this.editLable = false;
      this.$set(this.data.dynamicTags[index], 'isEditing', false);
    },

    // 随机显示颜色
    getRandomColor() {
      let randomIndex = Math.floor(Math.random() * (this.labelColorList.length - 1)) + 1;
      return this.labelColorList[randomIndex].value;
    },
    // 删除动态标签
    handleClose(i) {
      this.data.dynamicTags.splice(i, 1);
    },
    // 显示编辑标签图标
    editCommonTags() {
      this.closable = !this.closable;
      this.editLanguage = false;
    },
    editCommonTagsLanguage() {
      this.editLanguage = !this.editLanguage;
      this.closable = false;
    },
    // 删除常用标签
    handleCloseCommonTag(id) {
      this.$confirm('确定要删除该标签吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          DeleteLabel({ id }).then(() => {
            this.data.dynamicTags = this.data.dynamicTags.filter((p) => p.id !== id);
            this.getLabelList();
            this.$message.success('删除成功!');
          });
        })
        .catch((e) => {
          console.error(e);
        });
    },
    // 显示新增标签输入框
    showAddLabelTextInput() {
      this.inputVisible = true;
      this.$nextTick(() => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
    // 新增标签
    handleInputConfirm() {
      let inputValue = this.inputValue.trim();
      let label_color = this.data.property.label_color;
      if (label_color === 'random') label_color = this.getRandomColor();
      let dynamicTags = this.data.dynamicTags;
      if (inputValue) {
        // 检查是否已存在相同标签
        const existingTag = dynamicTags.find((tag) => tag.name === inputValue);
        if (existingTag) {
          this.$message.warning('常用标签已包含该标签，无需重复添加');
        } else {
          // dynamicTags.push({
          //   name: inputValue,
          //   color: label_color,
          // });
          this.addLabel(inputValue, label_color);
        }
      }
      this.inputVisible = false;
      this.inputValue = '';
    },
    // 点击常用标签显示到动态标签里
    viewToDynamicTags(index) {
      let commonTagId = this.commonTags[index].id;
      let commonTagName = this.commonTags[index].name;
      if (this.closable) return;
      if (this.editLanguage) {
        this.openDialogLanguage(commonTagId);
        return;
      }
      if (this.data.dynamicTags.length >= 16) {
        this.$message.warning('最多添加16个标签!');
        return false;
      }
      // 检查是否已存在相同标签（不区分大小写）
      const existingTag = this.data.dynamicTags.find((tag) => tag.name === commonTagName);
      if (existingTag) {
        this.$message.warning('组件标签已包含该标签，无需重复加入');
      } else {
        let label_color = this.data.property.label_color;
        if (label_color === 'random') label_color = this.getRandomColor();
        this.data.dynamicTags.push({
          name: commonTagName,
          color: label_color,
          id: commonTagId,
          mult_language_list: this.commonTags[index].mult_language_list || [],
        });
      }
    },
    // 得到标签列表
    getLabelList() {
      let param_data = {
        page_capacity: this.page_capacity,
        cur_page: this.cur_page,
        name: this.labelName,
      };
      PageQueryLabelList(param_data)
        .then(({ total_count, label_list }) => {
          this.total_count = total_count;
          this.commonTags = label_list;
        })
        .catch(() => {
          // 如果请求失败，回退页码
          this.cur_page -= 1;
        })
        .finally(() => {
          this.loading = false;
        });
    },
    changePage(number) {
      this.cur_page = number;
      this.getLabelList();
    },
    changePageSize(size) {
      this.page_capacity = size;
      this.getLabelList();
    },
    // 存储标签到系统
    addLabel(name, color) {
      AddLabel({ name })
        .then((res) => {
          this.cur_page = 1;
          this.getLabelList();
          if (color) {
            this.data.dynamicTags.push({
              name,
              color,
              id: res.id,
              mult_language_list: [],
            });
          }
        })
        .catch((e) => {
          console.error(e);
        });
    },
    // 文件类型校验
    beforeUpload(file) {
      if (file.length > 0) {
        this.$message.warning('只能上传一个表格文件');
        return false;
      }
      const fileName = file.name;
      const suffix = fileName.slice(fileName.lastIndexOf('.') + 1, fileName.length).toLowerCase();
      //  , 'xlsx', 'csv'
      if (!['xls'].includes(suffix)) {
        this.$message.warning('文件格式不正确');
        return false;
      }
    },
    // 上传标签
    customUpload(file) {
      fileUpload('Mid', file, { isGlobalprogress: true }).then(({ file_info_list }) => {
        if (file_info_list.length > 0) {
          let file_id = file_info_list[0].file_id;
          ImportLabel({ file_id })
            .then(() => {
              this.$message.success('导入成功!');
              this.cur_page = 1;
              this.getLabelList();
            })
            .catch((e) => {
              this.$message.error(e);
              console.error(e);
            });
        }
      });
    },
    // 多语言弹窗
    openDialogLanguage(commonTagId) {
      this.multilingualVisible = true;
      let en = { mult_language_list: [] };
      if (this.commonTags.some((p) => p.id === commonTagId)) {
        en = this.commonTags.find((p) => p.id === commonTagId);
        en.mult_language_list.map((p) => (p.translation = p.name));
      }
      this.editMultilingualTags = en;
    },
    // 提交多语言译文
    handleMultilingualTranslation(translations) {
      let data = this.editMultilingualTags;
      if (!translations.some((p) => p.type === 'ZH')) {
        translations.push({ translation: data.name, type: 'ZH' });
      }
      data['mult_language_list'] = translations.map((p) => {
        return { name: p.translation, type: p.type };
      });
      UpdateLabel(data)
        .then(() => {
          this.$message.success('设置成功!');
          this.cur_page = 1;
          let _index = this.data.dynamicTags.findIndex((p) => p.id === data.id);
          if (_index > -1) {
            this.$set(this.data.dynamicTags, _index, data);
          }
          this.getLabelList();
        })
        .catch((e) => {
          console.error(e);
        });
    },
    // 样式调整
    getTagStyle(tag) {
      const style = { color: tag.color };

      if (this.data.unified_attrib) {
        if (this.data.unified_attrib.font_size) {
          style['font-size'] = this.data.unified_attrib.font_size;
        }
        if (this.data.unified_attrib.font) {
          style['font-family'] = this.data.unified_attrib.font;
        }
        // if (this.data.unified_attrib.text_color) {
        //   style['color'] = this.data.unified_attrib.text_color;
        // }
        // if (this.data.unified_attrib.line_height) {
        //   style['line-height'] = this.data.unified_attrib.line_height;
        // }
        if (this.data.unified_attrib.font_weight) {
          style['font-weight'] = this.data.unified_attrib.font_weight;
        }
      }

      return style;
    },
    setRichFormat(type, val) {
      if (!this.data.unified_attrib) {
        this.$set(this.data, 'unified_attrib', {});
      }

      switch (type) {
        case 'fontSize':
          this.$set(this.data.unified_attrib, 'font_size', val);
          break;
        case 'fontFamily':
          this.$set(this.data.unified_attrib, 'font', val);
          break;
        // case 'color':
        //   this.$set(this.data.unified_attrib, 'text_color', val);
        //   break;
        // case 'lineHeight':
        //   this.$set(this.data.unified_attrib, 'line_height', parseFloat(val));
        //   break;
        case 'bold':
          this.$set(this.data.unified_attrib, 'font_weight', val ? 'bold' : 'normal');
          break;
        default:
          break;
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.tag-edit {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;

  :deep .el-tag {
    height: 32px;
    padding: 0 10px;
    line-height: 31px;
    color: var(--color1);
    background-color: #fff;
    border-color: var(--color1);
    border-radius: 2px;

    .el-tag__close:hover {
      // color: #fff;
      background-color: #ddd;
    }

    .el-tag__close {
      color: var(--color1);
    }
  }

  .button-new-tag {
    height: 32px;
    background-color: #f2f3f3;
    border: 1px dashed #c9cdd4;
  }

  .input-new-tag {
    width: 90px;
  }
}

.tag-manager {
  display: flex;
  flex-direction: column;
  row-gap: 10px;

  .tag-manager-box {
    display: flex;
    column-gap: 10px;
    align-items: center;
    justify-content: space-between;
    font-size: 14px;
    font-weight: 500;
    color: #000;
    cursor: pointer;

    .left-area {
      display: flex;
      column-gap: 10px;
      align-items: center;

      .tag-manager-title {
        color: rgba(0, 0, 0, 65%);
        cursor: text;
      }

      .tag-manager-text {
        display: flex;
        column-gap: 2px;
        align-items: center;
      }
    }

    .right-area {
      display: flex;
      column-gap: 10px;

      .search-box {
        width: 200px;

        :deep input {
          background-color: #fff;
          border-color: #dcdcdc;
        }
      }
    }
  }
}
</style>
