<template>
  <div class="NewList">
    <div class="NewListMain">
      <div class="CRTop">
        <div>
          <span>新闻公告</span>
        </div>
        <div style="text-align:right">
          <el-button type="primary" v-if="NewListBtn.NewListBtn52" round plain @click="addNews">新增新闻公告</el-button>
        </div>
      </div>
      <el-row>
        <el-tabs
          class="BCtabs"
          v-model="activeName"
          type="border-card"
        >
          <p class="SearchTitle">
            总记录条数
            <span style="color:#379FFF">{{announcementListTotal}}</span>条
          </p>
          <div class="AnnouncementTable">
            <el-table
              ref="multipleTable"
              :data="announcementList"
              style="width: 100%"
              tooltip-effect="dark"
              :header-cell-style="{'background-color':'rgba(250,250,250,1)'}"
              border
              v-loading="announcementLoad"
            >
              <el-table-column prop="title" label="新闻标题" min-width="100px" :show-overflow-tooltip="true"></el-table-column>
              <el-table-column prop="likeNum" label="点赞量" min-width="100px" :show-overflow-tooltip="true"></el-table-column>
              <el-table-column prop="lookNum" label="浏览量" min-width="100px" :show-overflow-tooltip="true"></el-table-column>
              <el-table-column prop="releaseUser" label="发布人" min-width="100px" :show-overflow-tooltip="true"></el-table-column>
              <el-table-column prop="releaseDate" label="发布时间" min-width="100px" :show-overflow-tooltip="true"></el-table-column>
              <el-table-column label="置顶" min-width="100px" :show-overflow-tooltip="true">
                <template slot-scope="props">
                  <el-switch :disabled="true" v-model="props.row.isTop"></el-switch>
                </template>
              </el-table-column> 
              <el-table-column prop="topSerial" label="置顶序号" min-width="100px" :show-overflow-tooltip="true"></el-table-column>
             
              <el-table-column
                label="操作"
                min-width="120px"
                fixed="right"
              >
                <template slot-scope="props">
                  <el-button
                    type="primary"
                    plain
                    round
                    @click="showNews(props.row)"
                    v-if="NewListBtn.NewListBtn51"
                  >查看</el-button>
                  <el-button
                    type="warning"
                    plain
                    round
                    @click="editNews(props.row)"
                    v-if="NewListBtn.NewListBtn53"
                  >修改</el-button>
                  <el-button
                    size="small"
                    type="success"
                    plain
                    @click="deleteNews(props.row)"
                    v-if="NewListBtn.NewListBtn54"
                  >删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <div class="pagenation">
              <span>
                <el-pagination
                  background
                  layout="prev, pager, next, sizes, total, jumper"
                  :total="announcementListTotal"
                  @current-change="click"
                  @size-change="handleSizeChange"
                  :page-sizes="[5, 10, 15, 20]"
                  :page-size="pagesize"
                ></el-pagination>
              </span>
            </div>
          </div>
        </el-tabs>
      </el-row>
      
    </div>

    <!--删除项目-->
    <div class="DeleteNews">
      <el-dialog
        title="删除新闻"
        :visible.sync="dialogDeleteNews"
        width="30%"
        :before-close="handleClose"
      >
        <p>
          确定删除该新闻吗？
        </p>
        <div slot="footer" class="dialog-footer Txc">
          <el-button @click="dialogDeleteNews = false">取 消</el-button>
          <el-button type="primary" @click="submitDeNews">确 定</el-button>
        </div>
      </el-dialog>
    </div>

    <div class="Image">
      <el-dialog
        title="图片"
        :visible.sync="dialogImageUrl"
        width="40%"
        :before-close="handleClose"
      >
        <div class="block">
          <el-carousel height="350px">
            <el-carousel-item v-for="item in Image" :key="item.sort">
              <el-image :src="item.imgUrl" fit="fill"></el-image>
            </el-carousel-item>
          </el-carousel>
        </div>
        <div slot="footer" class="dialog-footer Txc">
          <el-button @click="dialogImageUrl = false">关 闭</el-button>
        </div>
      </el-dialog>
    </div>

<!--锁定项目-->
    <div class="deleteAnnouce">
      <el-dialog
        title="删除公告"
        :visible.sync="dialogdeleteAnnouce"
        width="30%"
        :before-close="handleClose"
      >
        <p>确定删除该公告吗？</p>
        <div slot="footer" class="dialog-footer Txc">
          <el-button type="primary" @click="submitdeleteAnnouce">确 定</el-button>
          <el-button @click="dialogdeleteAnnouce = false">取 消</el-button>
        </div>
      </el-dialog>
    </div>


    <!-- dialog -->
    <el-dialog
      :title="showANN?'查看新闻公告':(IsEditANN?'修改新闻公告':'新增新闻公告')"
      :visible.sync="notice"
      width="70%"
      class="Announcementdia"
    >
      <!-- <div>
        <span>
          <img src="https://ty-picture.oss-cn-hangzhou.aliyuncs.com/tx123.png " alt />
        </span>
        <span></span>
      </div> -->
      <el-form
          :model="AnnouncementFrom"
          class="AnnouncementFrom"
          :inline="true"
          label-position="left"
        >
        <el-row >
          <el-form-item label="新闻标题：" prop="title" class="ANNtitle">
            <el-input placeholder="请填写新闻标题" v-model="AnnouncementFrom.title" :disabled="showANN"></el-input>
          </el-form-item>
        </el-row>
        <el-row >
          <el-form-item label="新闻内容：" prop="content">
            <div v-if="showANN" v-html="AnnouncementFrom.content">
              {{AnnouncementFrom.content}}
            </div>
            <div style="padding:20px; height: 75%;" v-else>
              <el-upload style="display:none"
              class="avatar-uploader"
              ref="fileUpload"
              action="https://app.edtyun.com:8443/business/common/upload"
              :headers="{'Authorization':token}"
              :show-file-list="false"
              :on-success="uploadSuccess"
              :on-error="uploadError"
              :before-upload="beforeUpload"
              >
              </el-upload>
              <quill-editor v-model="AnnouncementFrom.content" ref="myQuillEditor" class="editor" :options="editorOption" @blur="onEditorBlur($event)" @focus="onEditorFocus($event)" @change="onEditorChange($event)">
              </quill-editor>
            </div>
          </el-form-item>
        </el-row>
        <el-row >
          <el-form-item label="是否置顶：" prop="title">
            <el-switch v-model="AnnouncementFrom.isTop" :disabled="showANN"></el-switch>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="置顶序号：" prop="title">
            <el-input placeholder="请填写置顶序号" v-model="AnnouncementFrom.topSerial" :disabled="showANN"></el-input>
          </el-form-item>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer Txc">
        <el-button type="info" size="small" plain @click="notice=false">取消</el-button>
        <el-button type="primary" size="small" plain @click="subPicForm()">确定</el-button>
      </div>
    </el-dialog>
    <!--  -->
  </div>
</template>

<script>
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
import { quillEditor } from 'vue-quill-editor'
import '../../../../assets/css/font.css'

// 工具栏配置
const toolbarOptions = [
  ["bold", "italic", "underline", "strike"], // 加粗 斜体 下划线 删除线 -----['bold', 'italic', 'underline', 'strike']
  // ['blockquote', 'code-block'], // 引用  代码块-----['blockquote', 'code-block']
  [{ header: 1 }, { header: 2 }], // 1、2 级标题-----[{ header: 1 }, { header: 2 }]
  [{ list: 'ordered' }, { list: 'bullet' }], // 有序、无序列表-----[{ list: 'ordered' }, { list: 'bullet' }]
  // [{ script: 'sub' }, { script: 'super' }], // 上标/下标-----[{ script: 'sub' }, { script: 'super' }]
  [{ indent: '-1' }, { indent: '+1' }], // 缩进-----[{ indent: '-1' }, { indent: '+1' }]
  [{'direction': 'rtl'}], // 文本方向-----[{'direction': 'rtl'}]
  [{ size: ['small', false, 'large', 'huge'] }], // 字体大小-----[{ size: ['small', false, 'large', 'huge'] }]
  [{ header: [1, 2, 3, 4, 5, 6, false] }], // 标题-----[{ header: [1, 2, 3, 4, 5, 6, false] }]
  [{ color: [] }, { background: [] }], // 字体颜色、字体背景颜色-----[{ color: [] }, { background: [] }]
  [{ font: [] }], // 字体种类-----[{ font: [] }]
  [{ align: [] }], // 对齐方式-----[{ align: [] }]
  ['clean'], // 清除文本格式-----['clean']
  ['image'] // 链接、图片、视频-----['link', 'image', 'video']
]


export default {
  components: {
    quillEditor
  },
  name: "NewList",
  data() {
    return {
      fileUpload:{
        file:null
      },
      token:'',
      quillUpdateImg:true,
      announcementList: [],
      Isquestion:0,
      questionContent:"",
      
      //
      content:"",
      editorOption: {
        placeholder: '请输入文本...',
        theme: 'snow',
        modules: {
          toolbar: {
            container: toolbarOptions,
            handlers: {
                'image': function (value) {
                if (value) {
                  document.querySelector('.avatar-uploader input').click()
                } else {
                  this.quill.format('image', false);
                }
              }
            }
          }
        }
      },


      announcementLoad:false,
      announcementListTotal:10,
      dialogdeleteAnnouce:false,
      deleteAnnouceId:"",
      activeName: "first",
      pagesize: 10,
      currpage: 1,
      notice: false,
      dialogImageUrl: false,
      dialogDeleteNews:false,
      AnnouncementFrom:{
        title:'',
        content:'',
        imgUrls:'',
        topSerial:0,
      },
      AnnouncementFromrule:{
        title: [
          { required: true, message: "公告标题不能为空", trigger: "blur" },
        ],
        content:[{ required: true, message: "公告内容不能为空", trigger: "blur" },],
      },
      Image:[],
      dialogVisible: false,
      multiple: "",
      fileList:[],
      itemForm:{
        head_img: ''
      },
      fd: '',
      handleClose:null,
      showANN:false,
      IsEditANN:0,
      NewListBtn:{
        NewListBtn50:0,
        NewListBtn51:0,
        NewListBtn52:0,
        NewListBtn53:0,
        NewListBtn54:0,
      }
    };
  },
  created() {
    this.showAnnouncementList(1,10)
    this.token = JSON.parse(sessionStorage.getItem('token'))

    var NewListBtn = {}
    this.getButton(49).then(result => {
      if (result.data.statusCode==="1") {
        NewListBtn = result.data.data
        NewListBtn.map((item)=>{
          if(item.id==50){
            this.NewListBtn.NewListBtn50 = item.checked?1:0 
          }else if(item.id==51){
            this.NewListBtn.NewListBtn51 = item.checked?1:0 
          }else if(item.id==52){
            this.NewListBtn.NewListBtn52= item.checked?1:0 
          }else if(item.id==53){
            this.NewListBtn.NewListBtn53 = item.checked?1:0 
          }else if(item.id==54){
            this.NewListBtn.NewListBtn54 = item.checked?1:0 
          }
        })
      }
    });
  },
  methods: {
    uploadError() {
        // loading动画消失
        this.quillUpdateImg = false
        this.$message.error('图片插入失败')
    },
    uploadSuccess(res, file){
      // 首先获取富文本编辑器的实例
      let quill = this.$refs.myQuillEditor.quill
      // 上传成功所执行
      if (res.statusCode == 1 && res.data !== null) {
          // 获取光标所在位置
          let length = quill.getSelection().index;
          // 插入图片res为服务器返回的数据
          quill.insertEmbed(length, 'image', res.data)
          // 光标移动至文本末端
          quill.setSelection(length + 1)
          console.log(this.content)
      } else {
          this.$message.error('图片插入失败')
      }
      // loading动画消失
      this.quillUpdateImg = false
    },
    beforeUpload(file) {
      this.fileUpload.file=file;
        // 显示loading动画
        this.quillUpdateImg = true
    },
    ///
    onEditorBlur () {
      // 失去焦点事件
    },
    onEditorFocus () {
      // 获得焦点事件
    },
    onEditorChange () {
      // 内容改变事件
    },
    handleSizeChange(val) {
      this.showAnnouncementList(this.currpage,val)
      this.pagesize = val;
    },
    onEditorBlur(a){
      console.log(a)
    },
    handleAvatarSuccess1(res, file) {
      this.AnnouncementFrom.imgUrls= res.data;
    },
    handleRemove1(file, fileList) {
      console.log(file, fileList);
    },
    showAnnouncementList(pageNum, pageSize) {
      this.announcementLoad = true;
      var url =
        "quan/news/list";
      var param = {
        // mtCompanyId:JSON.parse(sessionStorage.getItem('mtCompanyId')),
        pageNum: pageNum,
        pageSize: pageSize
      };
      this.axios.post(url, param).then(result => {
        var data = result;
        if (data.statusCode) this.announcementLoad = false
        if (data.statusCode === "1" || data.statusCode === "9") {
          this.announcementList = data.data?data.data.rows:[];
          this.announcementListTotal = data.data?data.data.total:0;
        } else {
          this.$message.error(data.message);
        }
      });
    },
    deleteAnnoucement(row){
      this.deleteAnnouceId = row.id;
      this.dialogdeleteAnnouce = true;
    },
    submitdeleteAnnouce(){
      var url =
        "quan/news/delete";
      var param = {
        id : this.deleteAnnouceId
      };
      this.axios.post(url, param).then(result => {
        var data = result;
        if (data.statusCode === "1") {
          this.$message.success(data.message)
          this.showAnnouncementList(this.currpage,this.pagesize)
          this.dialogdeleteAnnouce = false
        } else {
          this.$message.error(data.message);
        }
      });
    },
    showNews(a){
      this.AnnouncementFrom = a
      this.showANN=true
      this.notice=true
    },
    editNews(a){
      this.AnnouncementFrom = a
      this.IsEditANN=1
      this.showANN=false
      this.notice=true
    },
    addNews(){
      this.IsEditANN=0
      this.showANN=false
      this.AnnouncementFrom = {
        releaseId:sessionStorage.getItem('user'),
        releaseUser:JSON.parse(JSON.parse(sessionStorage.getItem('userName'))),
      }
      this.notice=true
    },
    deleteNews(a){
      this.DeleteNewsId = a.id
      this.dialogDeleteNews = true;
    },
    submitDeNews(){
      var url = "quan/news/delete";
      var param = {
        id:this.DeleteNewsId
      }
      this.axios.post(url,param).then(result => {
        var data = result
        if(data.statusCode==="1"){
          this.$message.success(data.message);
          this.dialogDeleteNews = false;
          this.showAnnouncementList(this.currpage,this.pagesize)
        }else{
          this.$message.error(data.message);
        }
      });
    },
    showImage(imgUrl){
      this.Image[0] = {
        imgUrl:imgUrl,
        sort:0,
      }
      this.dialogImageUrl = true
    },
    trans(image){
      var imageList = [];
      imageList[0] = image
      return imageList
    },
    click(val) {
      this.currpage = val;
      this.showAnnouncementList(val,this.pagesize)
    },
    handleColse(done) {},

    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    uploadFile(file) {
      this.formDate.append("file", file.file);
      console.log(this.formDate)
    },
    beforeAvatarUpload(file){
      const isJPG =file.type == 'image/jpeg' || file.type == 'image/png' || file.type == 'image/gif'
// 　　　　const isLt2M = file.size / 1024 / 1024 < 2
　　　　if (!isJPG) {
　　　　　　this.$message.warning('上传头像图片只能是 JPG/PNG/GIF 格式!')
　　　　　　return isJPG
　　　　}
// 　　　　if (!isLt2M) {
// 　　　　　　this.$message.warning('上传头像图片大小不能超过 2MB!')
// 　　　　　　return isLt2M
// 　　　　}
　　　　this.multfileImg = file
　　　　return isJPG
    },
    handleAvatarSuccess(res, file) {
　　　　this.itemForm.head_img = URL.createObjectURL(file.raw)
　　},
    getNowTime() {
        var date = new Date();
        this.year = date.getFullYear();
        this.month =(date.getMonth() + 1 )< 10 ? "0" +(date.getMonth() + 1 ) : (date.getMonth() + 1 );
        this.date = date.getDate() < 10 ? "0" +date.getDate() : date.getDate();
        this.hour = date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
        this.minute = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
        this.second = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
        this.milliSeconds = date.getMilliseconds();
        var currentTime = this.year+'-'+this.month + '-' + this.date + ' ' + this.hour + ':' + this.minute + ':' + this.second;
        return currentTime;
      },
    subPicForm() {
          
            var url = "";
            if(this.IsEditANN==1){
              url="quan/news/modify"
            }else{
              url = "quan/news/add";
            }
            var param = {}
            param = this.AnnouncementFrom
            
            // param.mtCompanyId = JSON.parse(sessionStorage.getItem('mtCompanyId'))
            this.axios.post(url,param).then(result => {
              var data = result
              if(data.statusCode==="1"){
                this.$message.success(data.message);
                this.showAnnouncementList(this.currpage,this.pagesize)
                this.notice = false;
              }else{
                this.$message.error(data.message);
              }
            });
  }
    
//     subPicForm(){
//       　this.$refs.itemForm.validate(valid => {
// 　　　　　　if (valid) {
// 　　　　　　　　this.fd = new FormData()
// 　　　　　　　　this.fd.append('token', sessionStorage.getItem('loginToken')) //传其他参数
// 　　　　　　　　this.fd.append('id', this.itemForm.id)
// 　　　　　　　　this.fd.append('user_name', this.itemForm.user_name)
// 　　　　　　　　this.fd.append('user_nike_name', this.itemForm.user_nike_name)
// 　　　　　　　　this.fd.append('user_sex', this.itemForm.user_sex)
// 　　　　　　　　this.fd.append('user_phone', this.itemForm.user_phone)
// 　　　　　　　　this.fd.append('user_email', this.itemForm.user_email)
//                 console.log(fd);
// 　　　　　　　　if (this.multfileImg != null) {
// 　　　　　　　　　　this.fd.append('multfile', this.multfileImg)
// 　　　　　　　　}
// 　　　　　　　　api.updateUserInfo(this.fd).then(res => {
// 　　　　　　　　　　if (res) {
// 　　　　　　　　　　　　this.$message({ showClose: true, type: 'success', message: '设置成功' })
// 　　　　　　　　　　　　this.initPage()
// 　　　　　　　　　　}
// 　　　　　　　　})
// 　　　　　　} else {
// 　　　　　　　　　　this.$message({
// 　　　　　　　　　　showClose: true,
// 　　　　　　　　　　type: 'error',
// 　　　　　　　　　　message: '请检查表单信息的正确性'
// 　　　　　　　　　　})
// 　　　　　　　　return false
// 　　　　　　}
// 　　　　})
//     }

  }
};
</script>
<style lang="stylus">
  .NewList {
    height: 100%;
    .NewListMain{
      height: 100%;
      background: #fff;
      .AnnouncementTable{
        .el-button {
            padding: 8px;
            font-size: 12px;
            border-radius: 10px;
            margin-bottom: 5px;
        }
      }
    }
  }
  .avatar-uploader .el-upload {
        border: 1px dashed #d9d9d9;
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
        width: 200px;
        height: 178px;
      }

      .avatar-uploader .el-upload:hover {
        border-color: #409EFF;
      }

      .avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 100%;
        height: 178px;
        line-height: 178px;
        text-align: center;
      }

      .avatar {
        width: 100%;
        height: 100%;
        display: block;
      }

      .el-upload-list {
        width: 90%;
      }
      .AnnouncementFrom{
        .el-form-item__label{
          font-size:18px
        }
        .ANNtitle{
          width:100%
          .el-form-item__content{
            width:50%
          }
        }
        
      }
</style>