<template>
  <div class="createPost-container">
    <el-form ref="postForm" :model="postForm" :rules="rules" class="form-container">

      <sticky :class-name="'sub-navbar'">
        <el-button v-loading="loading" style="margin-left: 10px;" type="success" @click="submitForm">保存
        </el-button>
      </sticky>

      <div class="createPost-main-container">
        <el-row>
          <el-col :span="24">
            <el-form-item style="margin-bottom: 40px;" prop="name">
              <MDinput v-model="postForm.name" :maxlength="100" name="name" required>
                标签名称
              </MDinput>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <div class="postInfo-container">
              <el-row>
                <el-col :span="12">
                  <el-form-item style="margin-bottom: 20px;" label-width="75px" label="标签ID:" prop="position"
                                v-if="isEdit">
                    <el-input :rows="1" v-model="postForm.id" type="number" class="article-textarea"
                              style="width: 300px" disabled/>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item style="margin-bottom: 20px;" label-width="75px" label="创建时间:" prop="position"
                                v-if="isEdit">
                    <el-input :rows="1" v-model="postForm.create_time" type="text" class="article-textarea"
                              style="width: 300px" disabled/>
                  </el-form-item>
                </el-col>
              </el-row>
            </div>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label-width="75px" label="上级标签:" class="postInfo-container-item">
              <el-select v-model="up_tags" :remote-method="getRemoteTagList" filterable remote multiple
                         value-key="id"
                         placeholder="搜索标签" style="width: 70%">
                <el-option v-for="(item,index) in TagListOptions" :key="item+index" :label="item"
                           :value="item"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">

            <el-form-item label-width="75px" label="下级标签:" class="postInfo-container-item">
              <el-select
                v-model="down_tags"
                :remote-method="getRemoteTagList"
                multiple
                filterable
                remote
                reserve-keyword
                placeholder="搜索标签"
                style="width: 70%"
                :loading="loading"
                value-key="id"
              >
                <el-option v-for="(item, index) in TagListOptions" :key="item+index" :label="item"
                           :value="item"/>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label-width="75px" label="标签类型:" class="postInfo-container-item">
              <el-select v-model="tagtypes" :remote-method="getRemoteTagTypeList" filterable remote multiple
                         value-key="id"
                         placeholder="搜索类型" style="width: 70%">
                <el-option v-for="(item,index) in TagTypeListOptions" :key="item+index" :label="item"
                           :value="item"/>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item style="margin-bottom: 40px;" label-width="75px" label="标签简介:" prop="desc">
          <el-input :rows="1" v-model="postForm.description" type="textarea" class="article-textarea" autosize
                    placeholder="请输入内容"/>
          <span v-show="contentShortLength" class="word-counter">{{ contentShortLength }}字</span>
        </el-form-item>

        <div style="margin-bottom: 20px">
              <el-form-item style="margin-bottom: 40px;" label-width="75px" label="帖子图片:" prop="icon_url">
                <span v-model="uploadType"></span>
              <Upload v-model="postForm.icon_url" :uploadType="uploadType"/>
                </el-form-item>
            </div>
      </div>
    </el-form>

  </div>
</template>

<script>
  import Upload from '@/components/Upload/singleImage3'
  import MDinput from '@/components/MDinput'
  import Sticky from '@/components/Sticky' // 粘性header组件
  import {fetchTagDetail, CreateTag} from '@/api/tag'
  import {tagSearch, tagTypeSearch} from '@/api/remoteSearch'
  import {isInArray} from "@/utils";


  const defaultForm = {
    status: 'draft',
    name: '',
    description: '',
    up_tags: [],
    down_tags: [],
    tagtypes: [],
    icon_url: '',
  }

  export default {
    name: 'TagDetail',
    components: {MDinput, Sticky, Upload},
    props: {
      isEdit: {
        type: Boolean,
        default: false
      }
    },
    data() {
      const validateRequire = (rule, value, callback) => {
        value = value.trim()
        if (value === '') {
          this.$message({
            message: rule.field + '为必传项',
            type: 'error'
          })
          callback(new Error(rule.field + '为必传项'))
        } else {
          callback()
        }
      }
      return {
        postForm: Object.assign({}, defaultForm),
        loading: false,
        TagListOptions: [],
        TagTypeListOptions: [],
        up_tags: [],
        down_tags: [],
        tagtypes: [],
        uploadType: 25,
        rules: {
          name: [{validator: validateRequire, trigger: 'blur'}],
        },
        tempRoute: {},
      }
    },
    computed: {
      contentShortLength() {
        return this.postForm.description.length
      }
    },
    created() {
      if (this.isEdit) {
        const id = this.$route.params && this.$route.params.id
        this.fetchData(id)
      } else {
        this.postForm = Object.assign({}, defaultForm)
      }

      this.tempRoute = Object.assign({}, this.$route)
    },
    methods: {
      fetchData(id) {
        fetchTagDetail(id).then(response => {
          // select 回填数据处理，后期再进行优化
          let rep = response.data.data.data;
          for (let i = 0; i < rep.up_tags.length; i++) {
            this.up_tags.push(rep.up_tags[i]['id'] + ':' + rep.up_tags[i]['name'])
          }
          for (let i = 0; i < rep.down_tags.length; i++) {
            this.down_tags.push(rep.down_tags[i]['id'] + ':' + rep.down_tags[i]['name'])
          }
          for (let i = 0;i < rep.tagtypes.length; i++){
            this.tagtypes.push(rep.tagtypes[i]['id'] + ':' + rep.tagtypes[i]['name'])
          }
          this.postForm = rep
        }).catch(err => {
          console.log(err)
        })
      },
      submitForm() {
        this.$refs.postForm.validate(valid => {
          if (valid) {
            this.loading = true;

            let flag = false;
            for (let i = 0; i < this.up_tags.length; i++) {
              if (isInArray(this.down_tags, this.up_tags[i])) {
                this.$message.error('上下级标签不能存相同标签')
                this.postForm.up_tags = [];
                this.postForm.down_tags = [];
                flag = true;
                break
              }
            }
            if (flag) {
              return false;
            }
            this.postForm.up_tags = JSON.stringify(this.up_tags)
            this.postForm.down_tags = JSON.stringify(this.down_tags);
            this.postForm.tagtypes = JSON.stringify(this.tagtypes);
            CreateTag(this.postForm).then(response => {
              if (response.data.data.code == 500) {
                this.$notify({
                  title: '失败',
                  message: response.data.data.message,
                  type: 'error',
                  duration: 2000
                })
                this.loading = false
                return false
              }
              this.$notify({
                title: '成功',
                message: response.data.data.message,
                type: 'success',
                duration: 2000
              })
              setTimeout(() => {
                this.$router.push('/tag/list')
              }, 1000)

            }).catch(err => {
              this.$notify({
                title: '失败',
                message: '操作失败',
                type: 'danger',
                duration: 2000
              })
            });


            this.postForm.status = 'published'
            this.loading = false
          } else {
            console.log('error submit!!')
            return false
          }
        })
      },
      getRemoteTagList(query) {
        tagSearch(query).then(response => {
          if (!response.data.data.data) return
          this.TagListOptions = response.data.data.data
        })
      },
      getRemoteTagTypeList(query) {
        tagTypeSearch(query).then(response => {
          if (!response.data.data.data) return
          this.TagTypeListOptions = response.data.data.data
        })
      }
    }
  }
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
  @import "src/styles/mixin.scss";

  .createPost-container {
    position: relative;
    .createPost-main-container {
      padding: 40px 45px 20px 50px;
      .postInfo-container {
        position: relative;
        @include clearfix;
        margin-bottom: 10px;
        .postInfo-container-item {
          float: left;
        }
      }
      .editor-container {
        min-height: 500px;
        margin: 0 0 30px;
        .editor-upload-btn-container {
          text-align: right;
          margin-right: 10px;
          .editor-upload-btn {
            display: inline-block;
          }
        }
      }
    }
    .word-counter {
      width: 40px;
      position: absolute;
      right: -10px;
      top: 0px;
    }
  }
</style>
