<template>
  <t-card :bordered="false">
    <div class="form-step-container">
      <t-button @click="add">新增</t-button>
      <t-table
        rowKey="index"
        :data="list"
        :columns="columns"
        :stripe="true"
        :bordered="false"
        :hover="true"
        size="large"
        table-layout="auto"
        cellEmptyContent="-"
        :pagination="pagination"
      >
        <template #select="{ row }">
          <t-space size="24px">
            <t-button theme="warning" @click="edit(row)">编辑</t-button>
            <t-popconfirm content="确认删除吗" @confirm="del(row)">
              <t-button theme="danger">删除</t-button>
            </t-popconfirm>
          </t-space>
        </template>
      </t-table>
      <div style="margin-top: 30px">
        <t-pagination
          :total="pagination.total"
          :page-size="pagination.size"
          @current-change="onCurrentChange"
          :showPageSize="false"
        ></t-pagination>
      </div>
    </div>
    <t-dialog :header="isEdit?'编辑新闻':'新增新闻'" :visible="addMode" :onClose="onCloseMy" @confirm="onSubmit"
              width="45%" top="20px">
      <t-form>
        <t-form-item label="新闻标题" name="news_title">
          <t-input placeholder="请输入新闻标题" v-model="addForm.news_title"/>
        </t-form-item>
        <t-form-item label="简短标题" name="news_titleshort">
          <t-input placeholder="请输入简短标题" v-model="addForm.news_titleshort"/>
        </t-form-item>
        <t-form-item label="文章分类" name="activity_location">
          <t-select v-model="addForm.gory_id">
            <t-option v-for="(item,index) in gory_list" :key="index" :label="item.name" :value="item.id" />
          </t-select>
        </t-form-item>
        <t-form-item label="作者" name="news_auto">
          <t-input placeholder="请输入作者" v-model="addForm.news_auto"/>
        </t-form-item>
        <t-form-item label="来源" name="news_source">
          <t-input placeholder="请输入来源" v-model="addForm.news_source"/>
        </t-form-item>
        <t-form-item label="新闻详情" name="news_content">
          <div style="border: 1px solid #ccc;z-index: 99">
            <!-- 工具栏 -->
            <Toolbar
              style="border-bottom: 1px solid #ccc"
              mode="default"
              :editor="editor"
              :defaultConfig="toolbarConfig"
            />

            <Editor
              style="height: 200px"
              v-model="addForm.news_content"
              :defaultConfig="editorConfig"
              mode="default"
              @onCreated="(e) => onCreated(e)"
            />
          </div>
        </t-form-item>
        <t-form-item label="新闻主图">
          <t-upload
            :action="$store.state.user.apiUrl+'/api/common/upload'"
            v-model="addForm.news_image_show"
            theme="image"
            tips="请选择单张图片文件上传"
            accept="image/*"
            :format-response="formatResponse"
          ></t-upload>
        </t-form-item>
        <t-form-item
                     label="展示时间"
                     name="days">
          <t-date-picker :clearable="true" placeholder="展示时间"
                         :enableTimePicker="true" :allow-input="false"
                         v-model="addForm.showtime"></t-date-picker>
        </t-form-item>
      </t-form>
    </t-dialog>
  </t-card>

</template>
<script lang="ts">
import store from "@/store";
import {Editor, Toolbar} from '@wangeditor/editor-for-vue';

export default {
  components: {Editor, Toolbar},
  data() {
    return {
      visible: false,
      infoMode: false,
      addForm: {
        news_title: '',
        news_titleshort: '',
        gory_id: null,
        news_auto: '',
        news_source: '',
        news_content: '',
        news_image: '',
        news_image_show:[],
        showtime:'',
      },
      addMode: false,
      isEdit: false,
      editID: 0,
      list: [],
      gory_list:[],
      columns: [
        {colKey: 'news_title', title: '新闻标题', align: 'center'},
        {colKey: 'name', title: '类别', align: 'center'},
        {colKey: 'news_auto', title: '作者', align: 'center'},
        {colKey: 'news_hits', title: '点击量', align: 'center'},
        {colKey: 'news_source', title: '来源', align: 'center'},
        {colKey: 'showtime', title: '创建时间', align: 'center'},
        {colKey: 'select', title: '操作', width: 200, align: 'center'},
      ],
      pagination: {
        page: 1,
        size: 10,
        total: 0,
      },
      editor: null,
      toolbarConfig: {
        showLinkImg: false,
        uploadImgShowBase64: true,
        excludeKeys: [
          'insertVideo', // 删除视频
          'insertImage',// 删除网络图片上传
          'insertLink',// 删除链接
          'insertTable',// 删除表格
          'codeBlock',// 删除代码块
        ]
      },
      editorConfig: {
        placeholder: '',
        readOnly: false, // 是否只允许阅读，不可编辑
        autoFocus: true,
        MENU_CONF: {
          uploadImage: {
            server: store.state.user.apiUrl + '/api/common/upload',
            fieldName: 'file',
            customInsert(res: any, insertFn: InsertFnType) {  // TS 语法
              // customInsert(res, insertFn) {                  // JS 语法
              // res 即服务端的返回结果
              console.log(res);
              // 从 res 中找到 url alt href ，然后插入图片
              insertFn(res.data.fullurl, '', '')
            },
          },
          uploadVideo: {
            server: store.state.user.apiUrl + '/api/common/upload',
            fieldName: 'file',
            customInsert(res: any, insertFn: InsertFnType) {  // TS 语法
              // customInsert(res, insertFn) {                  // JS 语法
              // res 即服务端的返回结果
              console.log(res);
              // 从 res 中找到 url alt href ，然后插入图片
              insertFn(res.data.fullurl, '', '')
            },
          }
        }
      },
    }
  },
  beforeDestroy() {
    const editor = this.editor
    if (editor == null) return
    editor.destroy() // 组件销毁时，及时销毁编辑器
  },
  mounted() {
    //this.member_id=this.$route.query.id;
    this.getList();
    this.getGory();
  },
  methods: {
    onCurrentChange(d) {
      this.pagination.page = d;
      this.getList();
    },
    formatResponse(res) {
      console.log(res);
      this.addForm.news_image = res.data.url;
      return {url: res.data.fullurl};
    },
    onCreated(editor) {
      this.editor = Object.seal(editor);
    },
    del(d) {
      console.log(d);
      this.$request
        .post('/news/del', {news_id: d.news_id})
        .then((res) => {
          if (res.code == 1) {
            this.$message.success(res.msg);
            this.getList();
          } else {
            this.$message.error(res.msg);
          }
          console.log(res);
        })
        .catch((e) => {
          console.log(e);
        });
    },
    add() {
      this.addMode = true;
      this.isEdit = false;
    },
    edit(d) {
      console.log(d);
      this.addForm.news_id = d.news_id;
      this.addForm.news_title = d.news_title;
      this.addForm.news_titleshort = d.news_titleshort;
      this.addForm.news_image_show = [{url: store.state.user.apiUrl + d.news_image}];
      this.addForm.news_image = d.news_image;
      this.addForm.gory_id = d.gory_id;
      this.addForm.news_auto = d.news_auto;
      this.addForm.news_source = d.news_source;
      this.addForm.news_content = d.news_content;
      this.addForm.showtime = d.showtime;
      this.addMode = true;
      this.isEdit = true;
    },
    getList() {
      this.$request
        .post("/news", {page: this.pagination.page, size: this.pagination.size})
        .then((res) => {
          console.log(res);
          if (res.code == 1) {
            this.list = res.data.ret;
            this.pagination.total = res.data.count;
          }

        })
        .catch((e) => {
          console.log(e);
        });
    },
    getGory(){
      this.$request
        .post("/news/gory")
        .then((res) => {
          console.log(res);
          if (res.code == 1) {
            this.gory_list=res.data;
          }
        })
        .catch((e) => {
          console.log(e);
        });
    },
    onSubmit() {
      console.log(this.addForm);
      if (this.addForm.news_title == '') {
        this.$message.error('新闻标题不能为空');
        return;
      }
      if (this.addForm.news_titleshort == '') {
        this.$message.error('简短标题不能为空');
        return;
      }
      if (this.addForm.gory_id == null) {
        this.$message.error('请选择新闻分类');
        return;
      }
      if (this.addForm.news_auto == '') {
        this.$message.error('作者不能为空');
        return;
      }
      if (this.addForm.news_source == '') {
        this.$message.error('来源不能为空');
        return;
      }
      if (this.addForm.news_content == '') {
        this.$message.error('详情不能为空');
        return;
      }
      if (this.addForm.news_image=='') {
        this.$message.error('新闻主图不能为空');
        return;
      }
      if (this.addForm.showtime=='') {
        this.$message.error('展示时间不能为空');
        return;
      }
      var url = '/news/add';
      if (this.isEdit) {
        url = '/news/update';
      }
      this.$request
        .post(url, this.addForm)
        .then((res) => {
          console.log(res);
          if (res.code == 1) {
            this.$message.success(res.msg);
            this.addMode = false;
            this.getList();
          } else {
            this.$message.error(res.msg);
          }
        })
        .catch((e) => {
          console.log(e);
        });
    },
    onCloseMy() {
      this.addMode = false;
      this.infoMode = false;
    }
  }
}
</script>
<style src="@wangeditor/editor/dist/css/style.css"></style>
