<template>
  <div class="app-container">
    <el-page-header :content="isEdit?'编辑图文素材':'添加图文素材'" @back="goBack" />
    <el-card class="form-container" shadow="never">
      <el-form ref="weChatArticleFrom" :model="article" :rules="rules" label-width="120px">
        <el-form-item label="标题:" prop="title">
          <el-input v-model="article.title" />
        </el-form-item>
        <el-form-item label="素材详细列表:" prop="detailJson">
          <!-- <el-input v-model="article.detailJson" type="hidden" /> -->
          <el-table row-key="title" :data="detailList" border highlight-current-row>
            <el-table-column label="标题" prop="title" align="center">
              <template slot-scope="{row}">
                <el-input v-model="row.title" />
              </template>
            </el-table-column>
            <el-table-column label="跳转链接" prop="url" align="center">
              <template slot-scope="{row}">
                <el-input v-model="row.url" />
              </template>
            </el-table-column>
            <el-table-column label="图片链接" prop="picUrl" align="center">
              <template slot-scope="{row}">
                <el-input v-model="row.picUrl" />
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center">
              <template slot-scope="{row}">
                <el-button size="mini" type="danger" @click="handleDelete(row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <div class="detail-btn">
            <el-button type="primary" @click="handleCreate">添加</el-button>
          </div>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit('weChatArticleFrom')">提交</el-button>
          <el-button v-if="!isEdit" type="info" @click="resetForm('weChatArticleFrom')">重置</el-button>
          <el-button @click="goBack">返回</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>
<script>
import { getArticle, updateArticle, createArticle } from '@/api/wechat/article'
const defaultArticle = {
  id: 0,
  title: '',
  detailJson: '',
  type: ''
}
const defaultDetail = {
  id: 0,
  title: '',
  url: '',
  picUrl: ''
}
export default {
  name: 'WeChatArticleForm',
  props: {
    // type 类型： 1采美，2呵呵商城
    type: {
      type: Number,
      default: 0
    }
  },
  data() {
    return {
      rules: {
        title: [{ required: true, message: '标题不能为空', trigger: 'blur' }]
      },
      article: Object.assign({}, defaultArticle),
      detailList: [],
      isEdit: false
    }
  },
  watch: {
    $route(route) {
      this.getFormData()
    }
  },
  created() {
    this.getFormData()
  },
  methods: {
    goBack() {
      // 调用全局挂载的方法,关闭当前标签页
      this.$store.dispatch('tagsView/delView', this.$route)
      // 返回上一步路由，返回上一个标签页
      this.$router.go(-1)
    },
    getFormData() {
      if (this.$route.query.id) {
        this.article.id = this.$route.query.id
        this.isEdit = true
        getArticle(this.article.id).then(response => {
          this.article.title = response.data.title
          this.detailList = response.data.detailList
        })
      } else {
        this.article.id = ''
        this.isEdit = false
        this.article = Object.assign({}, defaultArticle)
      }
      this.article.type = this.type
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
      this.article = Object.assign({}, defaultArticle)
      this.getFormData()
    },
    onSubmit(formName) {
      this.article.detailJson = JSON.stringify(this.detailList)
      this.$refs[formName].validate(valid => {
        console.log(this.article)
        if (valid) {
          this.$confirm('是否提交数据', '提示', {
            confirmButtonArticle: '确定',
            cancelButtonArticle: '取消',
            type: 'warning'
          }).then(() => {
            const self = this
            if (this.isEdit) {
              updateArticle(this.$route.query.id, this.article).then(response => {
                this.$message({
                  message: '修改成功',
                  type: 'success',
                  duration: 1000
                })
                self.goBack()
              })
            } else {
              createArticle(this.article).then(response => {
                this.$refs[formName].resetFields()
                this.resetForm(formName)
                this.$message({
                  message: '提交成功',
                  type: 'success',
                  duration: 1000
                })
                self.goBack()
              })
            }
          })
        } else {
          this.$message({
            message: '验证失败',
            type: 'error',
            duration: 1000
          })
          return false
        }
      })
    },
    handleDelete(row) {
      const temp = this.detailList
      const newList = []
      temp.forEach(item => {
        if (item.id !== row.id) {
          newList.push(item)
        }
      })
      this.detailList = newList
    },
    handleCreate() {
      this.detailList.push(Object.assign({}, defaultDetail))
    }
  }
}
</script>

<style scoped>
.form-container{
  width:1000px;
}
.detail-btn{
  text-align: center;
  padding:15px 0;
  border-bottom: 1px solid #e6ebf5;
}
</style>
