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

    <el-dialog title="发布信息"  :visible.sync="dialogNewsFormVisible" >
      <el-form ref="pushForm" enctype="multipart/form-data"  :model="pushForm" label-width="100px" size="mini" :rules = "formrules"  >
        <el-form-item label="主题" prop = "newsName">
          <el-input v-model="pushForm.newsName"  placeholder="请输入主题" size = "medium" ></el-input>
        </el-form-item>
        <el-form-item label="描述" prop = "remark">
          <el-input type = "textarea" :rows="8"  placeholder="请输入内容 " v-model="pushForm.remark"></el-input>
        </el-form-item>
        <el-form-item label="附件上传" prop = "file">
          <el-upload
            ref="upload"
            action=""
            :auto-upload="false"
            :limit="1"
            align="left"
            :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">不能超过10Mb</span>
          </el-upload>
        </el-form-item>
        <el-form-item size="large">
          <el-button size = "mini" type = "primary" @click = "upload('pushForm')">立即发布</el-button>
          <el-button size = "mini" @click="closeDialog('pushForm')">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <el-table
      :data="tableData"
      stripe
      style="width: 100%">
      <el-table-column
        label="ID"
        prop="id"
        v-if = "false"
      ></el-table-column>
      <el-table-column
        prop="newsName"
        label="标题"
        align="center"
        width = "180"
      >
      </el-table-column>
      <el-table-column
        prop="createTime"
        label="创建时间"
        align="center"
        width = "180"
      >
      </el-table-column>
      <el-table-column
        prop="createBy"
        label="操作人"
        align="center"
      >
      </el-table-column>
      <el-table-column
        prop="remark"
        label="描述"
        align="center"
        width = "300"
      >
      </el-table-column>
      <el-table-column
        prop="fileName"
        label="文件名"
        align="center"
        width = "150"
      >
      </el-table-column>
      <el-table-column  label="状态" align="center" width="150">
        <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="80">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="info"
            @click="download(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>
  </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 > 10) {
          //callback(new Error('上传文件不能超过10Mb'))
          this.$message({
            message: '上传文件不能超过10Mb',
            type: 'error'
          });
          return;
        } else {
          callback()
        }
      };
      return {
        totals:0,
        Page:1,
        tableData: [],
        dialogNewsFormVisible:false,
        pushForm:{
          newsName:"",
          file:"",
          fileName:"",
          remark:"",
          urlName:"interact",
          fileType: 1,
          state:0,
          toType:2,
        },
        formrules:{
          newsName:[
            {required: true, message: '请输入主题', trigger: 'blur'}
            ],
          remark:[
            {required: true, message: '请输入描述'}
            ],
          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));
        }
      },
      download(index,row){
        axios.get(baseUrl + '/news/download/'+row.id, {
          headers: {
            "token": Cookies.get("token")
          },
          responseType: 'blob'
        })
          .then(res => {
            let a = document.createElement("a");
            let blob = new Blob([res.data],{type:""});
              a.href = URL.createObjectURL(blob);
              a.download = row.fileName;
              a.click();
          })
          .catch(err => {
            console.log(err);
          });

      },
      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) => {

              });
            })
          }
        })
      },
      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;
        })
      },
      current_change(s){
        var data={
          pageNum:s,
          pageSize:10
        }
        this.$api.getlist.getInteracts(data).then((res) => {
          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.getInteracts(data).then((res) => {
        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>
