<template>
<div>
  <div class="op" style="margin-left: 10px">
    <el-button type="primary" size="mini"  @click="dialogNewsFormVisible = true">发布<i class="el-icon-upload el-icon--right"></i></el-button>
  </div>

  <el-dialog title="发布新闻" width="40%" :visible.sync="dialogNewsFormVisible">
    <el-form ref="pushForm" :model="pushForm" label-width="100px" size="mini" :rules = "formrules">
      <el-form-item label="新闻主题" prop = "newsName">
        <el-input v-model="pushForm.newsName"  size = "medium"></el-input>
      </el-form-item>
      <el-form-item label="访问地址" prop = "urlName">
        <el-select v-model="pushForm.urlName" placeholder="请选择"
                   style="width: 100%;">
          <el-option v-for="item in urlNameData" :key="item.val"
                     :label="item.text" :value="item.val">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="附件上传" prop = "file">
        <el-upload
          ref="upload"
          action=""
          :auto-upload="false"
          :limit="1"
          align="left"
          accept = "application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document"
          :on-change = "selectFile"
        >
          <el-button slot="trigger" size="small"  class = "el-icon-upload2" type="success">选取文件</el-button><span style="margin-left: 10px" class="el-upload__tip">只能上传word文件，且不超过5Mb</span>
        </el-upload>
      </el-form-item>
      <el-form-item size="large">
        <el-button type = "info"  @click = "upload('pushForm')">立即发布</el-button>
        <el-button  @click = "closeDialog('pushForm')">取消</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
  <el-table
    :data="tableData"
    stripe
    style="width: 100%">
    <el-table-column
      prop="id"
      v-if="false"
    >
    </el-table-column>
    <el-table-column
      prop="newsName"
      label="标题"
      align="center"
     >
    </el-table-column>
    <el-table-column
      prop="urlName"
      label="地址"
      align="center"
      :formatter="urlFormat"
    >
    </el-table-column>
    <el-table-column
      prop="createTime"
      label="创建时间"
      align="center"
    >
    </el-table-column>
    <el-table-column
      prop="createBy"
      label="操作人"
      align="center"
    >
    </el-table-column>
    <el-table-column
    prop="todayCount"
    label="今日访问量"
    align = "right"
    >
    </el-table-column>
    <el-table-column
      prop="allCount"
      label="总访问量"
      align = "right"
    >
    </el-table-column>
    <el-table-column  label="状态" align="center">
      <template slot-scope="scope">
       <el-switch
          v-model="scope.row.state"
          active-color="#13ce66" inactive-color="#ff4949"
          active-text = "启用" inactive-text="禁用"
          :inactive-value = "0" :active-value = "2"
          @change="changeSwitch(scope.row.state,scope.$index)">
        </el-switch>
      </template>
    </el-table-column>
    <el-table-column label="操作" align="center"
                     min-width="100">
      <template slot-scope="scope">
        <el-button
          size="mini"
          type="info"
          @click="preview(scope.$index, scope.row)">预览
        </el-button>
      </template>
    </el-table-column>
  </el-table>
  <el-pagination
    class="pone"
    :page-size='10'
    layout="total, prev, pager, next, jumper"
    :total="totals"
    :current-page.sync="Page"
    @current-change="current_change">
  </el-pagination>


    <el-dialog width="60%"  :visible.sync="preViewVisible">
      <div v-html = "content"></div>
    </el-dialog>
    </div>

</template>

<style>
  .op{
    display: flex;
    align-items: center;

  }
</style>
<script>
  import Cookies from "js-cookie";
  import {baseUrl} from "../../utils/global"
  import axios from "axios"
  let base64 = require('js-base64').Base64

  export default {
    data() {
      let checkFile = (rule, value, callback) => {
        let size = value.size/1024/1024
        if(size > 5) {
          this.$message({
            message: '上传文件不能超过5Mb',
            type: 'error'
          });
          return;
        } else {
          callback()
        }
      };
      return {
          totals:0,
          Page:1,
        tableData: [],
        dialogNewsFormVisible:false,
        preViewVisible:false,
        content:"",
        urlNameData:[{val:'policy',text:'政策解读'},{val:'index',text:'主页'}],
        pushForm:{
          newsName:"",
          file:"",
          fileName:"",
          remark:"",
          urlName:"",
          fileType: 1,
          state:0,
          toType:1
        },
        formrules:{
          newsName:[
            {required: true, message: '请输入主题', trigger: 'blur'}
          ],
          urlName:[
            {required: true, message: '请选择地址',trigger: 'change blur'}
          ],
          file:[
            {required:true,message:'请选择文件'},
            { validator: checkFile}
          ]
        }
      }
    },
    methods:{
      closeDialog(form){
        this.dialogNewsFormVisible = false;
        this.$refs[form].resetFields();
        this.$refs.upload.clearFiles();
      },
      selectFile(file){
        let This = this;
        let reader = new FileReader();
        reader.readAsDataURL(file.raw);
        this.converBase64(file,function (base64) {
          This.pushForm.file = base64;
        });
        this.pushForm.fileName = file.name;
      },
      converBase64(file,callback) {
        let reader = new FileReader();
        reader.readAsDataURL(file.raw);
        reader.onload = function (e) {
          callback.call(this, this.result.substring(this.result.indexOf(",") + 1));
        }
      },
      urlFormat(row,column) {
        switch (row.urlName){
          case 'index':
            return '主页'
          case  'policy':
            return '政策解读'
          default :
            return '';
        }
      },
      preview(index,row){
        this.preViewVisible = true;
        this.$api.getlist.newsPreView(row.id).then((res)=>{
          if(res.code == 200) {
            this.content = res.data.htmlStr;
          }
        }).catch((res)=>{

        })
      },
      changeSwitch(value,index) {
        let str = value == 2 ? '启用':value == 0 ? '禁用': '';
        this.$confirm('确认'+ str +'？', '提示', {}).then(() => {
          this.$api.getlist.updateFileState(this.tableData[index].id,value).then((res) => {
            if(res.code == 200) {
              this.$message({message: '操作成功', type: 'success'})
              this.current_change(this.pageNum);
            }else {
              this.$message({message: '操作失败, ' + res.message, type: 'error'})
              this.tableData[index].state = this.tableData[index].state == 0 ? 2 : 0;
            }
          }).catch((res) => {

          });
        }).catch(() => {
          this.tableData[index].state = this.tableData[index].state == 0 ? 2 : 0;
        })
      },
      upload(form){
        this.$refs[form].validate((valid) => {
          if (valid) {
            this.$confirm('确认提交吗？', '提示', {}).then(() => {
              this.$api.getlist.saveFile(this.pushForm).then((res) => {
                if(res.code == 200) {
                  this.$message({message: '操作成功', type: 'success'})
                  this.closeDialog('pushForm');
                  this.current_change(0);
                }else {
                  this.$message({message: '操作失败, ' + res.message, type: 'error'})
                }
              }).catch((res) => {

              });
            })
          }
        })
      },
      current_change(s){
      var data={
          pageNum:s,
          pageSize:10
      }
      this.$api.getlist.newsList(data).then((res) => {
        if(res.code == 200) {
          this.totals = res.data.total
          this.page = res.data.total.pageNum
          this.tableData = res.data.list
        }
      }).catch((res) => {

      });
      },
      stateFormat(row, column) {
        if (row.state === 0) {
          return '停用'
        } else if (row.state === 1) {
          return '默认'
        } else if (row.state === 2) {
          return '启用'
        }
        }
      },
      created(){
          var data={
              pageNum:1,
              pageSize:10
          }
          this.$api.getlist.newsList(data).then((res) => {
            if(res.code == 200) {
              this.totals = res.data.total
              this.page = res.data.total.pageNum
              this.tableData = res.data.list
              this.tableData.forEach(element => {
                this.tableData.state = this.tableData.state !== 0;
            });
            }
          }).catch((res) => {

          });
      }

  }
</script>
