<template>
  <el-dialog
    title="推送内容设置"
    width="50%"
    :visible.sync="modal"
    :close-on-click-modal="false"
    @close="$emit('cancel')"
  >
    <divider-container title="基本信息" />

    <el-form ref="ruleForm" :model="form" :rules="rules" label-width="120px">
      <el-form-item label="上新类型" prop="type">
        <el-select v-model="form.type" placeholder="请选择类型">
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item v-if="form.type === 'ARTICLE'" label="文章" prop="article">
        <el-select v-model="form.article" placeholder="请选择文章" style="width: 300px;">
          <el-option
            v-for="item in articleOptions"
            :key="item.id"
            :label="item.title"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <!-- <el-form-item v-else label="参数" prop="params"><el-input v-model="form.params" style="max-width: 600px;" autocomplete="off" /></el-form-item> -->
      <el-form-item label="图片" prop="imgFile"><upload v-model="form.imgFile" params="prefix=/newContentPopUp" /></el-form-item>
      <el-form-item label="置顶状态"><el-checkbox v-model="form.isTop">置顶</el-checkbox></el-form-item>
      <el-form-item label="展示状态"><el-checkbox v-model="form.isShow">展示</el-checkbox></el-form-item>
      <el-form-item label="排序（倒序）" prop="sort"><el-input-number v-model="form.sort" controls-position="right" :min="0" :max="10000" /></el-form-item>
    </el-form>

    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="handleSubmit('ruleForm')">保存</el-button>
      <!-- <el-button v-if="modalType === 'edit'" type="danger" @click="handleDelete">删除</el-button> -->
      <el-button @click="modal = false">取消</el-button>
    </div>
  </el-dialog>
</template>

<script>
// import { setStatus } from '@/utils'
import EMITKEY from '@/const/emitNameKey'
import { UPLOAD_URL_DEMO } from '@/const/urlKey'
import { getItem, saveItem } from '@/model/indexRecommend'
import { getList as getArticleList } from '@/model/article'
import { cutUrl, setStatus } from '@/utils'

export default {
  name: 'IndexRecommendItem',

  props: {
    id: {
      type: String,
      default: ''
    },
    modalType: {
      type: String,
      default: ''
    }
  },

  data() {
    const validateImg = (rule, value, callback) => {
      if (!Array.isArray(value)) return callback(new Error('数据出错，请重新上传'))
      if (value.length < 1) return callback(new Error('请先上传图片'))

      return callback()
    }

    return {
      modal: true,

      form: {
        article: '',
        params: '',
        imgFile: [{ url: UPLOAD_URL_DEMO }],
        isTop: false,
        isShow: false,
        sort: null,
        type: null
      },
      rules: {
        article: [{ required: true, message: '请选择绑定文章', trigger: 'change' }],
        params: [{ required: true, message: '请输入相关信息', trigger: 'blur' }],
        imgFile: [{ required: true, validator: validateImg, trigger: 'change' }],
        sort: [{ required: true, message: '请输入优先度(1~9)', trigger: 'blur' }],
        type: [{ required: true, message: '请选择上新类型', trigger: 'change' }]
      },
      options: setStatus(['文章', '直播', '其他'], ['ARTICLE', 'LIVE_BROADCAST', 'OTHER']),

      val: [],

      articleOptions: []
    }
  },

  watch: {
    'form.imgFile': {
      handler(val) {
        this.$refs['ruleForm'].validateField('imgFile')
      },
      deep: true
    }
  },

  mounted() {
    this.loadArticleList()
  },

  methods: {

    async loadArticleList() {
      const { success, data, msg } = await getArticleList({
        'data': {},
        'start': 1,
        'limit': 9999
      })
      if (success) {
        this.articleOptions = data.items
        this.id && this.loadData()
      } else {
        this.$message.error(msg)
      }
    },

    async loadData() {
      const { success, data, msg } = await getItem({
        id: this.id
      })
      if (success) {
        Object.assign(this.form, data)
      } else {
        this.$message.error(msg)
      }
    },

    handleSubmit(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.saveData()
        }
      })
    },

    async saveData() {
      let params = this.form.params
      if (this.form.type === 'ARTICLE') {
        const obj = this.articleOptions.find(x => x.id === this.form.article)
        if (obj.id) {
          params = JSON.stringify({
            id: obj.id,
            type: obj.contentType
          })
        }
      }
      const { success, msg } = await saveItem({
        id: this.id,
        data: {
          params,
          imgUrl: cutUrl(this.form.imgFile[0].url),
          isTop: this.form.isTop,
          isShow: this.form.isShow,
          sort: this.form.sort,
          type: this.form.type
        }
      })
      if (success) {
        this.$message.success('操作成功~')
        this.bus.$emit(EMITKEY.INDEXRECOMMENDRELOAD)
        this.modal = false
      } else {
        this.$message.error(msg)
      }
    }
  }
}
</script>

<style scoped>
.mt-60 {
  margin-top: 60px;
}
.btn-right {
  display: flex;
  justify-content: flex-end;
  align-items: center;
}
.mcol-20 .el-row {
  font-size: 14px;
  line-height: 1.7;
  padding-top: 14px;
}
.search-box {
  border: 1px #DCDEE2 solid;
  padding: 5px;
}
.search-box .search-input {
  margin: 0 5px;
  max-width: 200px;
}
</style>
