<template>
  <div class="journalism">
    <!-- 头部细节部分 -->
      <div class="title">
        <el-row>
          <el-col :span="24">
            <div class="top">
              <el-input  placeholder="新闻标题" class="input-demo" v-model="title"></el-input>
              <el-button type="success" style="margin-left: 1%;" @click="queryLook">查询</el-button>
              <el-button type="success" style="margin-left: 1%;" @click="addUserList = true">添加</el-button>
            </div>
          </el-col>
        </el-row>
      </div>
    <!-- 头部细节部分结束 -->
    <!-- 表格部分 -->
      <template>
        <el-table
          v-loading="loading"
          ref="multipleTable"
          :data="usertable"
          border
          tooltip-effect="dark">
          <el-table-column
            label="新闻标题"
            prop="title"
            show-overflow-tooltip>
          </el-table-column>
           <el-table-column
            prop="newsAbstract"
            label="新闻摘要"
            show-overflow-tooltip>
          </el-table-column>
          <el-table-column
            label="创建时间"
            show-overflow-tooltip
            width="180">
            <template slot-scope="scope" show-overflow-tooltip>
              <span>{{scope.row.createTime | fmtDate}}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            width="120">
            <template slot-scope="scope" show-overflow-tooltip>
              <span style="cursor:pointer;" @click="openChange(scope.row)">修改</span>
              <span style="margin-left: 10px; cursor:pointer; color: red;" @click="Delete(scope.row.id)">删除</span>
            </template>
          </el-table-column>
        </el-table>
      </template>

    <!-- 分页 -->
      <div class="block">
        <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="current"
        :page-sizes="[6, 8, 10]"
        :page-size="pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
        </el-pagination>
      </div>

    <!-- 新增新闻 -->
      <el-dialog
        @close="handleEditDialogClose"
        :visible.sync="addUserList">
        <div class="tou">新闻--添加</div>
        <div class="line"></div>
        <el-form
          label-position="right"
          label-width="80px"
          :rules="rules"
          ref="ruleForm"
          :model="formList">

            <el-form-item label="新闻标题" prop="title">
              <el-input v-model="formList.title" auto-complete="off" placeholder="请输入新闻标题"></el-input>
            </el-form-item>

            <el-form-item label="新闻摘要" prop="newsAbstract">
              <el-input v-model="formList.newsAbstract" auto-complete="off" placeholder="请输入新闻摘要"></el-input>
            </el-form-item>

            <el-form-item label="新闻作者" prop="author">
              <el-input v-model="formList.author" auto-complete="off" placeholder="请输入新闻作者"></el-input>
            </el-form-item>

            <el-form-item label="文章来源" prop="source">
              <el-input v-model="formList.source" auto-complete="off" placeholder="请输入文章来源"></el-input>
            </el-form-item>

            <el-form-item label="新闻封面">
              <el-upload
                ref='upload'
                action="http://192.168.1.199:18083/app/photo"
                list-type="picture-card"
                :on-preview="handlePreview"
                :on-remove="handleRemove"
                :on-change="handleSuccess"
                :auto-upload="false">
                <i class="el-icon-plus"></i>
              </el-upload>
            </el-form-item>

            <el-form-item label="导航分类">
              <el-tree
                :data="menuList"
                show-checkbox
                default-expand-all
                check-strictly
                node-key="id"
                ref="tree"
                highlight-current
                :default-checked-keys="haveRight"
                :props="defaultProps"
                style="font-size: 0px;">
              </el-tree>
            </el-form-item>

            <el-form-item label="新闻内容" prop="content">
             <template>
               <!-- 图片上传组件辅助 -->
              <el-upload
                class="avatar-uploader"
                :action="serverUrl"
                name="photo"
                :format="['jpg','jpeg','png','gif']"
                :headers="header"
                :show-file-list="false"
                :on-success="uploadSuccess"
                :on-error="uploadError"
                :before-upload="beforeUpload">
              </el-upload>
              <!-- 富文本编辑器组件 -->
              <el-row v-loading="quillUpdateImg">
                <quill-editor
                  v-model="detailContent"
                  ref="myQuillEditor"
                  :options="editorOption"
                  @change="onEditorChange($event)"
                  @ready="onEditorReady($event)">
                </quill-editor>
               </el-row>
             </template>
            </el-form-item>

        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="addUserList = false" type="info">取 消</el-button>
          <el-button type="primary" @click="addData('ruleForm')">新 增</el-button>
        </div>
      </el-dialog>
    <!-- 修改新闻 -->
      <el-dialog
        @close="handleEditDialogClose"
        :visible.sync="changeUser">
        <div class="tou">新闻--修改</div>
        <div class="line"></div>
        <el-form
          label-position="right"
          label-width="80px"
          :model="formChangeList">
           <el-form-item label="新闻标题">
              <el-input v-model="formChangeList.title" auto-complete="off" placeholder="请输入新闻标题"></el-input>
            </el-form-item>

            <el-form-item label="新闻摘要">
              <el-input v-model="formChangeList.newsAbstract" auto-complete="off" placeholder="请输入新闻摘要"></el-input>
            </el-form-item>

            <el-form-item label="新闻作者">
              <el-input v-model="formChangeList.author" auto-complete="off" placeholder="请输入新闻作者"></el-input>
            </el-form-item>

            <el-form-item label="文章来源">
              <el-input v-model="formChangeList.source" auto-complete="off" placeholder="请输入文章来源"></el-input>
            </el-form-item>

             <el-form-item label="新闻封面">
            <el-upload
              ref='upload'
              action="http://192.168.1.199:18083/app/photo"
              list-type="picture-card"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :on-change="handleSuccess"
              :auto-upload="false">
              <i class="el-icon-plus"></i>
            </el-upload>
            <img style="width: 150px; height: 150px;" :src="dialogImageUrl" alt="">
          </el-form-item>

            <el-form-item label="导航分类">
              <el-tree
                :data="menuList"
                show-checkbox
                default-expand-all
                check-strictly
                node-key="id"
                ref="tree"
                highlight-current
                :default-checked-keys="haveRight"
                :props="defaultProps">
              </el-tree>
            </el-form-item>

          <el-form-item label="新闻内容">
            <template>
               <!-- 图片上传组件辅助 -->
              <el-upload
                class="avatar-uploader"
                :action="serverUrl"
                name="photo"
                :format="['jpg','jpeg','png','gif']"
                :headers="header"
                :show-file-list="false"
                :on-success="uploadSuccessOne"
                :on-error="uploadErrorOne"
                :before-upload="beforeUploadOne">
              </el-upload>
              <!-- 富文本编辑器组件 -->
              <el-row v-loading="quillUpdateImg">
                <quill-editor
                  v-model="detailContent"
                  ref="myQuillEditor"
                  :options="editorOption"
                  @change="onEditorChange($event)"
                  @ready="onEditorReady($event)">
                </quill-editor>
              </el-row>
            </template>
          </el-form-item>

        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="changeUser = false" type="info">取 消</el-button>
          <el-button type="primary" @click="changeData">修 改</el-button>
        </div>
      </el-dialog>
  </div>
</template>

<script type="text/javascript">
const toolbarOptions = [
  ['bold', 'italic', 'underline', 'strike'],        // toggled buttons
  ['blockquote', 'code-block'],

  [{'header': 1}, {'header': 2}],               // custom button values
  [{'list': 'ordered'}, {'list': 'bullet'}],
  [{'script': 'sub'}, {'script': 'super'}],      // superscript/subscript
  [{'indent': '-1'}, {'indent': '+1'}],          // outdent/indent
  [{'direction': 'rtl'}],                         // text direction

  [{'size': ['small', false, 'large', 'huge']}],  // custom dropdown
  [{'header': [1, 2, 3, 4, 5, 6, false]}],

  [{'color': []}, {'background': []}],          // dropdown with defaults from theme
  [{'font': []}],
  [{'align': []}],
  ['link', 'image', 'video'],
  ['clean']                                         // remove formatting button
]
export default {
      data() {
        return {
          title: "",
          usertable: [],
          formList: {
            "urlList": [],
            "title": "",
            "author": "",
            "source": "",
            "newsAbstract": "",
            "photo": "",
            "navigationBarIds": [],
            "content": "",
          },
          defaultProps: {
            children: 'childList',
            label: 'name'
          },
          menuList: [],
          haveRight:[],
          treeIds:[],
          dialogImageUrl:"",
          flag: 0,
          formChangeList: {
            "id": "",
            "urlList": [],
            "title": "",
            "author": "",
            "source": "",
            "newsAbstract": "",
            "photo": "",
            "navigationBarIds": [],
            "content": "",
          },
          picList: [],
          photoList: [],
          current: 1,
          pagesize: 10,
          // 总共有多少条数据
          total: 0,
          addUserList: false,
          changeUser: false,
          photo: '',
          quillUpdateImg: false,
          serverUrl: 'http://localhost:8088/api/app/upload',
          // serverUrl: 'http://192.168.1.199:18083/app/upload',
          // 这里写你要上传的图片服务器地址
          header: {Authorization: 'Bearer ' + sessionStorage.token},  //有的图片服务器要求请求头需要有token之类的参数，写在这里
          detailContent: '', // 富文本内容
          editorOption: {
            placeholder: '',
            theme: 'snow',  // or 'bubble'
            modules: {
              toolbar: {
                container: toolbarOptions,  // 工具栏
                handlers: {
                  'image': function (value) {
                    if (value) {
                    // 触发input框选择图片文件
                       document.querySelector('.avatar-uploader input').click()
                      } else {
                       this.quill.format('image', false);
                     }
                  }
                }
              }
            }
          }
      }
  },

  created() {
    this.loadData();
    this.loadTree();
  },
  methods: {
    // 列表展示
    async loadData() {
      const response = await this.$http.get(`app/page/newsArticle?&current=${this.current}&size=${this.pagesize}`);
      if (response.data.code === 1) {
        this.loading = false;
        this.usertable = response.data.responseData.records;
        // console.log(response.data.responseData);
        this.total = response.data.responseData.total;
      }
    },
    //展示树形导航
    async loadTree() {
      const response = await this.$http.get(`app/menu`);
      if (response.data.code === 1) {
        // console.log(response.data.responseData)
        this.menuList = response.data.responseData;
        this.loading = false;
      }
    },
    //查询
    async queryLook() {
      const response = await this.$http.get(`app/page/newsArticle?&current=${this.current}&size=${this.pagesize}&title=${this.title}`);
      if (response.data.code === 1) {
        this.loading = false;
        this.usertable = response.data.responseData.records;
        this.total = response.data.responseData.total;
      }
    },
    // 新增新闻
    addData(formName) {
      this.$refs[formName].validate(async (valid) => {
        if(valid) {
            const formData = new FormData();
            if(this.flag == 1) {
              formData.append('photo', this.formList.photo);
            }

            formData.append('title', this.formList.title);
            formData.append('newsAbstract', this.formList.newsAbstract);
            this.treeIds = this.$refs.tree.getCheckedNodes(false, true);
              for(var i = 0; i < this.treeIds.length; i++) {
                this.formList.navigationBarIds.push(this.treeIds[i].id);
            };
            formData.append('navigationBarIds', this.formList.navigationBarIds);
            formData.append('content', this.formList.content);
            formData.append('urlList', this.formList.urlList);
            const response = await this.$http.post(`app/newsArticle`, formData);
            if(response.data.code === 1) {
              this.loadData();
              this.addUserList = false;
              this.$message({
                type: 'success',
                message: '添加新闻成功'
              });
            }else {
              this.$message({
                type: 'error',
                message: '添加新闻失败'
              });
            }
        }else {
          this.$message.error('请查看是否有选项未填写或填错项');
          return false;
        }
      })
    },

    // 富文本图片上传前
    beforeUpload(file) {
      // 显示loading动画
      this.quillUpdateImg = true;

    },
    uploadSuccess(res, file) {
        // res为图片服务器返回的数据
        // 获取富文本组件实例
        let quill = this.$refs.myQuillEditor.quill;
        // console.log(quill)
        // 如果上传成功
        if (res.code == 1) {
            // 获取光标所在位置
            let length = quill.getSelection().index;
            // console.log(length)
            // 插入图片  res.info为服务器返回的图片地址
            quill.insertEmbed(length, 'image', res.responseData);
            // alert(res.responseData)
            this.formList.urlList.push(res.responseData);
            // console.log(this.formList.urlList);
            // 调整光标到最后
            quill.setSelection(length + 1);
        } else {
            this.$message.error('图片插入失败');
        }
        // loading动画消失
        this.quillUpdateImg = false;
    },
    // 富文本图片上传失败
    uploadError() {
      // loading动画消失
      this.quillUpdateImg = false;
      this.$message.error('图片插入失败');
    },

    //修改新闻内容时候上传的图片地址
    // 富文本图片上传前
    beforeUploadOne(file) {
      // 显示loading动画
      this.quillUpdateImg = true;

    },
    uploadSuccessOne(res, file) {
        // res为图片服务器返回的数据
        // 获取富文本组件实例
        let quill = this.$refs.myQuillEditor.quill;
        // console.log(quill)
        // 如果上传成功
        if (res.code == 1) {
            // 获取光标所在位置
            let length = quill.getSelection().index;
            // console.log(length)
            // 插入图片  res.info为服务器返回的图片地址
            quill.insertEmbed(length, 'image', res.responseData);
            // alert(res.responseData)
            this.formChangeList.urlList.push(res.responseData);
            // console.log(this.formList.urlList);
            // 调整光标到最后
            quill.setSelection(length + 1);
        } else {
            this.$message.error('图片插入失败');
        }
        // loading动画消失
        this.quillUpdateImg = false;
    },
    // 富文本图片上传失败
    uploadErrorOne() {
      // loading动画消失
      this.quillUpdateImg = false;
      this.$message.error('图片插入失败');
    },
    // 新增新闻内容
    onEditorReady(editor) { },// 准备编辑器
    onEditorBlur(){}, // 失去焦点事件
    onEditorFocus(){}, // 获得焦点事件
    onEditorChange(event){
      this.formList.content = event.html;

    }, // 内容改变事件

    // 打开修改并赋予信息
    async openChange(user) {
      this.changeUser = true;
      this.formChangeList.id = user.id;
      this.formChangeList.title = user.title;
      this.formChangeList.author = user.author;
      this.formChangeList.source = user.source;
      this.formChangeList.newsAbstract = user.newsAbstract;
      this.dialogImageUrl = user.photoUrl;
      this.detailContent = user.content;
      const response = await this.$http.get(`app/newsArticle/${user.id}`);
      if(response.data.code === 1) {
        this.$refs.tree.setCheckedKeys([]);
        this.haveRight = response.data.responseData.navigationBarIds;
        this.formChangeList.urlList = response.data.responseData.urlList;
        console.log(this.formChangeList.urlList);
      }

    },
    // 修改新闻
    async changeData() {
      const formData = new FormData();
      formData.append('id', this.formChangeList.id);
      if(this.flag == 1) {
        formData.append('photo', this.formChangeList.photo);
      }

      formData.append('title', this.formChangeList.title);
      formData.append('newsAbstract', this.formChangeList.newsAbstract);
      formData.append('urlList', this.formChangeList.urlList);
      console.log(this.formChangeList.urlList)
      this.treeIds = this.$refs.tree.getCheckedNodes(false, true);
        for(var i = 0; i < this.treeIds.length; i++) {
          this.formChangeList.navigationBarIds.push(this.treeIds[i].id);
      };
      formData.append('navigationBarIds', this.formChangeList.navigationBarIds);
      formData.append('content', this.detailContent);

      const response = await this.$http.put(`app/newsArticle`, formData);
      if(response.data.code === 1) {
        this.loadData();
        this.changeUser = false;
        this.$message({
          type: 'success',
          message: '修改新闻成功'
        });
      }else {
        this.$message({
          type: 'error',
          message: '修改新闻失败'
        });
      }
    },
     // 点击删除按钮
    Delete(id) {
      this.$confirm('是否删除该用户', '提示' ,{
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          const response = await this.$http.put(`app/newsArticle/${id}`);
          if(response.data.code === 1) {
            this.loadData();
            this.$message({
              type: 'success',
              message: '删除新闻成功'
            });
          }else {
            this.$message({
              type: 'error',
              message: '删除新闻失败'
            });
          }
        }).catch(() => {
           this.$message({ type: 'info', message: '已取消删除'});
      });
    },

     // 上传图片功能
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },

    handlePreview(file) {
      console.log(file);
    },
    handleSuccess (a) {
      if(a !== '') {
        this.flag = 1
        this.formList.photo = a.raw;
        this.formChangeList.photo = a.raw;
      }else {
        this.flag = 0
      }
    },

    // 清空表单数据
    handleEditDialogClose() {
      for (var key in this.formList) {
        this.formList[key] = '';
      };
      this.formList.urlList = [];
      this.formList.navigationBarIds = [];
      //清除图片缓存
      this.$refs.upload.clearFiles();

      this.formList.content = '';

      this.$refs.tree.setCheckedKeys([]);
      this.haveRight = [];
      this.detailContent = '';
      this.formChangeList.navigationBarIds = [];
    },
    // 分页方法
    handleSizeChange(val) {
      this.pagesize = val;
      if(this.title !== '') {
        this.queryLook();
      }else{
        this.loadData();
      };
      console.log(`每页 ${val} 条`);
    },
    handleCurrentChange(val) {
      this.current = val;
      if(this.title !== '') {
        this.queryLook();
      }else{
        this.loadData();
      };
      console.log(`当前页: ${val}`);
    },

  }
};
</script>

<style>
.journalism {
  border: 1px solid #d9d9d9;
  border-radius: 10px;
}
.journalism .title {
  font-size: 5px;
  margin-bottom: 20px;
}
.journalism .top {
  padding-top: 20px;
  padding-left: 20px;
}
.journalism .text {
  display: inline-block;
  color: #000;
  font-size: 16px ;
  margin-left: 1%;
}
.journalism .input-demo {
  display: inline-block;
  width: 20%;
  margin-left: 1%;
}
.journalism .block {
  font-size: 5px;
  text-align: center;
  margin-top: 25px;
  margin-bottom: 25px;
}
.journalism .el-dialog {
  width: 60%;
}
.journalism .el-dialog__header, .el-dialog__body {
  padding: 0 20px;
}
.journalism .tou {
  font-size: 20px;
  height: 30px;
  line-height: 30px;
  padding-top: 15px;
}
.journalism .line {
  margin-top: 15px;
  margin-bottom: 15px;
  width: 100%;
  height: 2px;
  background-color: #d9d9d9;
}
.journalism .xinxi {
  text-align: center;
  margin: 15px auto;
  font-size: 18px;
}
</style>

