<template>
  <div class="addHot">
    <ai-detail>
      <template slot="title">
        <ai-title :title="isEdit?'编辑话题':'添加话题'" :isShowBack="true" :isShowBottomBorder="true"
                  @onBackClick="$emit('goBack')"></ai-title>
      </template>
      <template slot="content">
        <ai-card title="标题信息">
          <template #content>
            <el-form ref="baseForm" :model="baseForm" :rules="baseRules" label-width="80px" label-position="right">
              <el-form-item label="话题标题" prop="title">
                <el-input v-model.trim="baseForm.title" placeholder="请输入..." size="small" show-word-limit
                          :maxlength="100"></el-input>
              </el-form-item>
              <el-form-item label="封面图片" prop="thumbUrl">
                <ai-uploader :instance="instance" :limit="1" v-model="baseForm.thumbUrl" isShowTip></ai-uploader>
              </el-form-item>
              <el-form-item label="关键词" prop="keyWords">
                <el-tag
                  :key="tag"
                  v-for="tag in baseForm.keyWords"
                  closable
                  :disable-transitions="false"
                  effect="plain"
                  @close="handleClose(tag)">
                  {{tag}}
                </el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="inputVisible"
                  v-model="inputValue"
                  ref="saveTagInput"
                  size="small"
                  show-word-limit
                  :maxlength="15"
                  @keyup.enter.native="handleInputConfirm"
                  @blur="handleInputConfirm"
                >
                </el-input>
                <el-button v-else class="button-new-tag" icon="iconfont iconAdd" size="small" @click="showInput">添加
                </el-button>
              </el-form-item>
            </el-form>
          </template>
        </ai-card>
        <ai-card title="热点话题">
          <template #content>
            <div class="wrap" :class="{active:currentIndex==index}" v-for="(item,index) in topicForm" :key="index"
                 @click="onClick(index)">
<!--              <el-row type="flex" justify="space-between">-->
<!--                <header class="header">热点话题</header>-->
<!--              </el-row>-->
              <el-form :ref="('topicForm'+ index)" :model="topicForm[index]" :rules="topicRules" label-width="80px"
                       label-position="right">
                <el-form-item label="话题来源" prop="questionSource">
                  <el-input v-model="topicForm[index].questionSource" placeholder="请输入..." size="small" show-word-limit
                            :maxlength="50"></el-input>
                </el-form-item>
                <el-form-item label="话题描述" prop="question">
                  <el-input v-model="topicForm[index].question" type="textarea" :rows="5" placeholder="请输入回复内容"
                            size="small" show-word-limit :maxlength="500"></el-input>
                </el-form-item>
                <el-form-item label="回复来源" prop="answerSource">
                  <el-input v-model="topicForm[index].answerSource" placeholder="请输入..." size="small" show-word-limit
                            :maxlength="50"></el-input>
                </el-form-item>
                <el-form-item label="回复描述" prop="answer">
                  <el-input v-model="topicForm[index].answer" type="textarea" :rows="5" placeholder="请输入回复内容"
                            size="small" show-word-limit :maxlength="500"></el-input>
                </el-form-item>
                <el-form-item label="描述图片" prop="files">
                  <ai-uploader :instance="instance" :limit="3" isShowTip
                               v-model="topicForm[index]['files']"></ai-uploader>
                </el-form-item>
              </el-form>
            </div>
          </template>
        </ai-card>
      </template>
      <template slot="footer">
        <el-button @click="$emit('goBack')">取消</el-button>
        <el-button type="primary" @click="handleSubmit">提交</el-button>
      </template>
    </ai-detail>
    <div class="options">
      <el-button type="primary" size="small" icon="iconfont iconAdd" @click="add">添加话题</el-button>
      <el-button type="danger" size="small" icon="iconfont iconDelete" @click="handDel" :disabled="topicForm.length==1">
        删除话题
      </el-button>
    </div>
  </div>
</template>

<script>

  export default {
    name: "addHot",
    label: "添加话题",
    props: {
      instance: Function,
      dict: Object,
      permissions: Function,
      areaId: String,
      detail: Object
    },
    data() {
      return {
        baseForm: {
          areaId: this.areaId,
          title: "",
          thumbUrl: [],
          keyWords: [],
        },
        topicForm: [{
          questionSource: "",
          question: "",
          answerSource: "",
          answer: "",
          files: [],
        }],
        inputVisible: false,
        inputValue: '',
        ids: [],
        currentIndex: 0,
      }
    },
    methods: {
      onClick(index) {
        this.currentIndex = index
      },
      handleSubmit() {
        Promise.all([new Promise(resolve => {
          this.$refs['baseForm'].validate(valid => {
            if (valid) {
              resolve()
            }
          })
        }), new Promise(resolve => {
          let result = []
          this.topicForm.forEach((item, index) => {
            this.$refs[('topicForm' + index)][0].validate(valid => result.push(valid))
          })
          result.every(e=>e) && resolve()
        })]).then(() => {
          this.instance.post(`/app/apphotsubject/addOrUpdate`, {
            hotSubject: {
              ...this.baseForm,
              thumbUrl: this.baseForm.thumbUrl[0].url,
              id: this.isEdit ? this.detail.id : null,
              keyWords: this.baseForm.keyWords.join(",")
            },
            contents: this.topicForm,
            deleteIds: this.ids,
          }).then(res => {
            if (res.code == 0) {
              this.$message.success(this.isEdit ? "编辑成功" : "保存成功")
              this.$emit("goBack")
            }
          })
        })
      },
      add() {
        this.topicForm.splice(this.currentIndex + 1, 0, {
          questionSource: "",
          question: "",
          answerSource: "",
          answer: "",
          files: [],
        })
        this.currentIndex = this.topicForm.length - 1
      },
      handDel() {
        this.$confirm("是否删除").then(() => {
          this.topicForm[this.currentIndex] && this.ids.push(this.topicForm[this.currentIndex].id)
          this.topicForm.splice(this.currentIndex, 1)
          this.currentIndex = this.topicForm.length - 1
        })
      },
      handleClose(tag) {
        this.baseForm.keyWords.splice(this.baseForm.keyWords.indexOf(tag), 1);
      },

      showInput() {
        this.inputVisible = true;
        this.$nextTick(_ => this.$refs.saveTagInput.$refs.input.focus());
      },

      getDetail() {
        this.instance.post(`/app/apphotsubject/detail`, null, {
          params: {id: this.detail.id}
        }).then(res => {
          if (res && res.data) {
            this.baseForm.areaId = res.data.areaId
            this.baseForm.title = res.data.title
            this.baseForm.thumbUrl.push({url: res.data.thumbUrl})
            this.baseForm.keyWords = res.data.keyWords.split(",")
            this.topicForm = res.data.contents
          }
        })
      },

      handleInputConfirm() {
        let inputValue = this.inputValue
        if (inputValue) {
          this.baseForm.keyWords.push(inputValue);
        }
        this.inputVisible = false;
        this.inputValue = '';
      }
    },
    computed: {
      baseRules() {
        return {
          title: [{required: true, message: '请输入话题标题', trigger: 'blur'}],
          thumbUrl: [{required: true, message: '请上传封面图片', trigger: 'change'}],
          keyWords: [{required: true, message: '请输入关键词', trigger: 'blur'}],
        }
      },
      topicRules() {
        return {
          // questionSource: [{required: true, message: '请输入话题来源', trigger: 'blur'}],
          question: [{required: true, message: '请输入话题描述', trigger: 'blur'}],
          // answerSource: [{required: true, message: '请输入回复来源', trigger: 'blur'}],
          answer: [{required: true, message: '请输入回复描述', trigger: 'blur'}],
          // files: [{required: true, message: '请上传描述图片', trigger: 'change'}],
        }
      },
      isEdit() {
        return !!this.detail.id;
      }
    },
    created() {
      if (this.isEdit) {
        this.getDetail()
      }
    }
  }
</script>

<style lang="scss" scoped>
  .addHot {
    height: 100%;
    overflow: hidden;
    position: relative;

    .wrap {
      background-color: #F5F6F9;
      box-sizing: border-box;
      padding: 16px;

      &:not(:last-child) {
        margin-bottom: 20px;
      }

      .header {
        font-size: 16px;
        color: #222222;
        line-height: 24px;
        font-weight: 700;
      }
    }

    .active {
      background: #FFFFFF;
      box-shadow: 0px 4px 8px 0px rgba(0, 0, 0, 0.05);
    }

    .el-tag + .el-tag {
      margin-left: 10px;
    }

    ::v-deep .el-tag {
      color: #222222;
      border-color: #D0D4DC;

      & .el-icon-close {
        color: #222222;

        &:hover {
          background-color: transparent;
        }
      }
    }

    .button-new-tag {
      margin-left: 10px;
      height: 32px;
      line-height: 30px;
      padding-top: 0;
      padding-bottom: 0;
    }

    .input-new-tag {
      width: 90px;
      margin-left: 10px;
      vertical-align: bottom;
    }

    .options {
      position: fixed;
      right: 6%;
      top: 50%;
      display: flex;
      flex-direction: column;

      ::v-deep .el-button--danger {
        margin-left: 0;
        margin-top: 4px;
      }
    }
  }
</style>
