<template>
  <div>
    <el-dialog :visible="dialogVisible" title="创建练习" width="670px" @close="dialogClose">
      <el-form ref="form" :model="form" :rules="rules" label-width="90px">
        <el-form-item label="练习名称" prop="name">
          <el-input v-model="form.name" maxlength="100" placeholder="请输入练习名称" />
        </el-form-item>
        <el-form-item label="标签">
          <div class="label-list">
            <el-tag v-for="(item, i) in form.label_list" :key="`${item}${i}`" type="info" closable @close="closeTag(i)">
              {{ item }}
            </el-tag>
            <el-button class="label-item" icon="el-icon-plus" circle @click="showVisible" />
          </div>
        </el-form-item>
        <el-form-item label="简介">
          <el-input v-model="form.intro" type="textarea" maxlength="500" placeholder="请输入" rows="10" />
        </el-form-item>
        <el-form-item>
          <el-button @click="dialogClose">取消</el-button>
          <el-button type="primary" @click="createdExercise">确定</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <el-dialog :visible="visible" title="创建标签" width="300px" @close="dialogCloseLabel">
      <el-autocomplete
        v-model="label_name"
        class="inline-input"
        :fetch-suggestions="querySearch"
        placeholder="请输入内容"
      />
      <template #footer>
        <el-button @click="dialogCloseLabel">取消</el-button>
        <el-button type="primary" @click="addLabel">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { CreateExercise, GetLabelList, GetExerciseInfo, UpdateExercise } from '@/api/exercise';

export default {
  name: 'CreateExercise',
  props: {
    dialogVisible: {
      type: Boolean,
      default: false,
    },
    currentExerciseId: {
      type: String,
      default: '',
    },
  },
  data() {
    return {
      visible: false,
      label_name: '',
      label_list: [],
      form: {
        name: '',
        label_list: [],
        intro: '',
      },
      rules: {
        name: [
          {
            required: true,
            message: '请输入练习名称',
            trigger: 'blur',
          },
        ],
      },
    };
  },
  watch: {
    dialogVisible(val) {
      if (val) {
        this.getExerciseInfo();
      } else {
        this.form = {
          name: '',
          label_list: [],
          intro: '',
        };
      }
    },
  },
  created() {
    this.getLabelList();
  },
  methods: {
    /**
     * 标签搜索
     * @param {string} queryString 搜索内容
     * @param {Function} cb 回调函数
     */
    querySearch(queryString, cb) {
      let label_list = this.label_list;
      let results = (queryString ? label_list.filter(this.createFilter(queryString)) : label_list).map((item) => {
        return { value: item };
      });
      cb(results);
    },
    getExerciseInfo() {
      if (!this.currentExerciseId) return;
      GetExerciseInfo({ exercise_id: this.currentExerciseId }).then(({ exercise }) => {
        this.form = {
          name: exercise.name,
          label_list: exercise.label_list,
          intro: exercise.intro,
        };
      });
    },
    createFilter(queryString) {
      return (label) => {
        return label.toLowerCase().indexOf(queryString.toLowerCase()) === 0;
      };
    },
    addLabel() {
      if (this.label_name) {
        this.form.label_list.push(this.label_name);
        this.label_name = '';
      }
      this.visible = false;
    },
    /**
     * 删除标签
     * @param {number} i 标签索引
     */
    closeTag(i) {
      this.form.label_list.splice(i, 1);
    },
    showVisible() {
      this.visible = true;
    },
    dialogCloseLabel() {
      this.visible = false;
    },
    getLabelList() {
      GetLabelList({ store_type: 0 }).then(({ label_list }) => {
        this.label_list = label_list;
      });
    },
    dialogClose() {
      this.$emit('update:dialogVisible', false);
      this.$emit('close');
    },
    createdExercise() {
      this.$refs.form.validate((valid) => {
        if (!valid) return false;

        // 如果有当前练习题id，则为修改练习题
        if (this.currentExerciseId) {
          UpdateExercise({ id: this.currentExerciseId, ...this.form })
            .then(() => {
              this.$message.success('修改成功');
              this.dialogClose();
            })
            .catch(() => {});
          return;
        }

        CreateExercise(this.form)
          .then(({ id }) => {
            this.$message.success('创建成功');
            this.dialogClose();
            this.$router.push({ path: '/exercise', query: { id } });
          })
          .catch(() => {});
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.el-input,
.el-textarea,
.label-list {
  width: calc(100% - 40px);
}

.el-autocomplete {
  width: 100%;
}

.label-list {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
  padding: 4px;
  background-color: $fill-color;
  border-radius: 2px;

  .el-tag {
    display: flex;
    align-items: center;
    color: #000;
    background-color: #fff;

    :deep .el-tag__close {
      font-size: 16px;
      color: #000 !important;
    }
  }

  .el-button.label-item {
    width: 24px;
    height: 24px;
    padding: 4px;
    background-color: #fff;
  }
}
</style>
