<template>
  <div>
    <el-dialog :title="!tmpSource.ID ? '新建来源' : '编辑来源'" :visible.sync="isShow" v-if="isShow" class="source-word-dialog">
      <el-form :model="tmpSource" :rules="sourceRules" ref="sourceForm" label-width="100px">
        <el-form-item prop="sourceWord" label="来源：" :verify="['NotNull','Length<200']">
          <el-input type="text" v-model="tmpSource.sourceWord" auto-complete="off"></el-input>
        </el-form-item>
        <div style="text-align:center;padding-bottom: 12px;" v-if="!tmpSource.ID">(多个来源之间用逗号隔开)</div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="isShow = false">取 消</el-button>
        <el-button type="primary" @click="confirmSourceClick">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import util from '@src/common/util.js'

export default {
  data() {
    return {
      // 来源数据加载状态
      dataSourceLoading: false,
      // 来源form表单验证
      sourceRules: {
        sourceWord: [{ required: true, message: '请输入来源', trigger: 'blur' }]
      }
    }
  },
  computed: {
    isShow: {
      get() {
        return this.addSourceDialog
      },
      set(val) {
        this.$emit('update:addSourceDialog', val)
      }
    }
  },
  methods: {
    keywordsChange(val) {
      this.tmpSource.sourceWord = val
      if (this.tmpSource.sourceWord) {
        this.$refs.sourceForm.validateField('sourceWord')
      }
    },
    // 验证来源事件
    async confirmSourceClick() {
      if (!this.tmpSource.sourceWord) {
        util.showResponseMessage({message: '来源不能为空'})
        return
      } else if (!this.tmpSource.sourceWord.trim()) {
        util.showResponseMessage({message: '来源不能只含有空格'})
        return
      }
      this.tmpSource.sourceWord = this.tmpSource.sourceWord.trim()
      try {
        util.validateForm(this.$refs['sourceForm'])
      } catch (e) {
        util.showErrorMessageBox(e)
        return
      }
      if (!this.tmpSource.ID) {
        let res = await axios.post('/ui/sourcewords', this.tmpSource)
        util.showResponseMessage(res.data)
        if (res.data.status === 1) {
          this.isShow = false
          this.$emit('callback')
        }
      } else {
        if (this.tmpSource.sourceWord.length > 200) {
          util.showErrorMessageBox('来源最大长度为200')
          return
        }
        let res = await axios.put(`/ui/sourcewords/${this.tmpSource.ID}`, this.tmpSource)
        util.showResponseMessage(res.data)
        if (res.data.status === 1) {
          this.isShow = false
          this.$emit('callback')
        }
      }
    }
  },
  props: {
    addSourceDialog: {
      type: Boolean,
      required: true
    },
    tmpSource: {
      type: Object,
      required: true
    }
  }
}
</script>

<style>
/* 在一般情况下dialog宽为450像素，在逻辑分辨率480像素以下dialog宽为96% */
.source-word-dialog .el-dialog {
  width: 450px;
}
@media (max-width: 480px) {
  .source-word-dialog .el-dialog{
    width: 96%;
  }
}
</style>
<style scoped>
</style>
