<template>
  <div id="detail">
    <data-form :fields="fields" :data="data" @save="toSave" returns="/adminCenter/news">
      <template #options="{ item }">
        <template v-if="item.model === 'column_name'">
          <el-option v-for="(i, index) in typeList" :key="`columns-name-${index}`" :label="i" :value="i"></el-option>
        </template>
      </template>
      <template #custom="{ item }">
        <template v-if="item.model === 'image'">
          <e-upload url="/files/cysci/news_image/upload" v-model="data[item.model]"></e-upload>
        </template>
        <template v-if="item.model === 'fileUrl'">
          <e-upload url="/files/cysci/news_file/upload" v-model="data[item.model]" type="text"></e-upload>
        </template>
      </template>
    </data-form>
  </div>
</template>

<script>
const _ = require('lodash');
const { newsColumn } = require('@common/dict/index');
import { mapState, createNamespacedHelpers } from 'vuex';
const { mapActions: news } = createNamespacedHelpers('news');
export default {
  name: 'newsDetail',
  props: {},
  components: {},
  data: function () {
    return {
      typeList: newsColumn,
      data: {
        image: [],
        fileUrl: [],
      },
      fields: [
        { label: '栏目名称', model: 'column_name', type: 'select' },
        { label: '标题', model: 'title' },
        { label: '发布时间', model: 'release_time', type: 'datetime' },
        { label: '来源', model: 'origin' },
        { label: '内容', model: 'content', type: 'editor', url: '/files/cysci/news_editor/upload' },
        { label: '图片', model: 'image', custom: true },
        { label: '附件', model: 'fileUrl', custom: true },
      ],
    };
  },
  created() {
    if (this.id) this.search();
  },
  methods: {
    ...news(['fetch', 'create', 'update']),
    async search() {
      const res = await this.fetch(this.id);
      if (this.$checkRes(res)) {
        this.$set(this, `data`, res.data);
      }
    },
    async toSave({ data }) {
      let dup = _.cloneDeep(data);
      let res;
      if (_.get(dup, 'id')) {
        res = await this.update(dup);
      } else {
        res = await this.create(dup);
      }
      if (this.$checkRes(res, '保存成功', '保存失败')) {
        if (!this.$dev_mode) this.$router.push('/adminCenter/news');
      }
    },
  },
  computed: {
    ...mapState(['user', 'menuParams']),
    pageTitle() {
      return `${this.$route.meta.title}`;
    },
    id() {
      return this.$route.query.id;
    },
  },
  metaInfo() {
    return { title: this.$route.meta.title };
  },
};
</script>

<style lang="less" scoped></style>
