<template>
  <div class="banner" v-loading="loading">
    <div class="head clear-both">
      <el-button @click="add" plain type="success" style="float: right" v-if="!$store.state.readonly">新增</el-button>
    </div>
    <el-tabs v-model="searchFrom.type" type="card" style="background: white;padding-top: 10px" @tab-click="getList">
      <el-tab-pane label="磨耳朵" name="2"></el-tab-pane>
      <el-tab-pane label="启蒙小课堂" name="3"></el-tab-pane>
      <el-tab-pane label="明星学员" name="4"></el-tab-pane>
      <el-tab-pane label="精彩直播课" name="5"></el-tab-pane>
    </el-tabs>
    <el-tabs v-model="searchFrom.status" type="card" style="background: white;padding-top: 10px" @tab-click="getList">
      <el-tab-pane label="全部" name="-1"></el-tab-pane>
      <el-tab-pane label="上架" name="1"></el-tab-pane>
      <el-tab-pane label="下架" name="2"></el-tab-pane>
    </el-tabs>
    <el-table
      :data="bannerList"
      style="width: 100%">
      <el-table-column
        prop="id"
        label="ID">
      </el-table-column>
      <el-table-column
        prop="title"
        label="标题">
      </el-table-column>
      <el-table-column
        prop="url"
        label="图片">
        <template slot-scope="scope">
          <a :href="scope.row.url" target="_blank">
            <img class="short-banner" :src="scope.row.url"/>
          </a>
        </template>
      </el-table-column>
      <el-table-column
        label="状态">
        <template slot-scope="scope">
          {{scope.row.status | status}}
        </template>
      </el-table-column>
      <el-table-column
        prop="link"
        label="链接">
      </el-table-column>
      <el-table-column
        label="操作"
        v-if="!$store.state.readonly"
        width="100">
        <template slot-scope="scope">
          <el-popover
            placement="top"
            width="280">
            <div style="text-align: center">
              <el-button size="mini" plain type="primary" @click="edit(scope.row)">
                编辑
              </el-button>
              <el-button size="mini" type="danger" plain @click="del(scope.row)" v-if="$store.state.deletePermission">
                删除
              </el-button>
              <el-button v-if="scope.row.status == 2" size="mini" type="primary" plain @click="changeStatus(scope.row)">
                上架
              </el-button>
              <el-button v-if="scope.row.status == 1" size="mini" type="primary" plain @click="changeStatus(scope.row)">
                下架
              </el-button>
              <el-button v-if="scope.$index > 0" size="mini" type="primary" plain @click="moveUp(scope.$index)">
                上移
              </el-button>
              <el-button v-if="scope.$index !== bannerList.length - 1" size="mini" type="primary" plain @click="moveDown(scope.$index)">
                下移
              </el-button>
            </div>
            <el-button slot="reference" size="mini" type="text" >操作</el-button>
          </el-popover>
        </template>
      </el-table-column>
    </el-table>
    <page :nowPage="nowPage" :total="total" :limit="limit" @pageChange="onPageChange" @sizeChange="onSizeChange"/>
    <el-dialog
      :title="dialog.title"
      center
      append-to-body
      :visible.sync="dialog.show"
      width="30%">
      <el-form ref="form" :rules="dialog.rules" :model="dialog.form" label-width="100px">
        <el-form-item label="名称" prop="title">
          <el-input v-model="dialog.form.title"></el-input>
        </el-form-item>
        <el-form-item label="二级名称" prop="sub_title">
          <el-input v-model="dialog.form.sub_title"></el-input>
        </el-form-item>
        <el-form-item label="链接" prop="link">
          <el-input v-model="dialog.form.link"></el-input>
        </el-form-item>
        <div class="upload-block">
          <el-upload
            action="/api/public/upload/zone"
            :http-request="uploadFile"
            :class="{disabled:!uploadShow}"
            :before-upload="beforeAvatarUpload"
            list-type="picture-card"
            :file-list="imageList"
            :on-success="handleAvatarSuccess"
            :on-remove="handleRemove">
            <i class="el-icon-plus"></i>
          </el-upload>
          <p class="size">750*400</p>
        </div>
        <el-upload
          v-if="searchFrom.type==2&&audio.length==0"
          class="upload-demo"
          :http-request="uploadFileAudio2"
          :before-upload="beforeAvatarAudio"
          :file-list="audio"
          :on-exceed="handleExceed"
          :on-remove="removeFileAudio2"
          drag
          action="https://jsonplaceholder.typicode.com/posts/"
          multiple>
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">
            将文件拖到此处，或<em>点击上传</em>
            <br>
            <span style="color: #888888;font-size: 12px">只能上传MP3文件</span>
          </div>
        </el-upload>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialog.show = false">取 消</el-button>
        <el-button type="primary" @click="sub">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  import {getBannerListApi,addBannerApi,editBannerApi,getBannerDetailApi,delBannerApi,moveApi,uploadFileApi,bannerChangeStatusApi} from "../../service/api";
  import page from '../framework/page'
  export default {
    name: "banner",
    components:{
      page
    },
    data(){
      return {
        loading: false,
        bannerList: [],
        searchFrom:{
          status:'1',
          type:'2'
        },
        total: 0,
        nowPage: 1,
        uploadShow: true,
        limit: 10,
        dialog:{
          title:'新增',
          show:false,
          rules: {
            title: [
              {required: true, message: '请填写名称', trigger: 'change'},
            ],
            link: [
              {required: true, message: '请填写链接', trigger: 'change'},
            ],
            sub_title: [
              {required: true, message: '请填写子名称', trigger: 'change'},
            ]
          },
          form:{
            title:'',
            url:'',
            link:'',
            id: '',
            sub_title:''
          }
        },
        imageList: [],
        audio:[]
      }
    },
    created(){
      this.getList()
    },
    filters:{
      status(value){
        if(value === 1){
          return '上架中'
        }else{
          return '已下架'
        }
      }
    },
    methods: {
      removeFileAudio2(file,fileList){
        this.audio = fileList
      },
      handleExceed(){
      },
      // 音频文件限制
      beforeAvatarAudio(file){
        const isJPG = (file.type === 'audio/mp3' );
        if (!isJPG) {
          this.$message.error('上传视频只能是MP3格式!');
        }
        return isJPG;
      },
      // 上传音频2
      uploadFileAudio2(a){
          uploadFileApi({file:a.file,type:'local',obj:a}).then(res=>{
            this.$message({
              type: 'success',
              message: '上传成功!'
            });
            a.onSuccess('上传成功');
            this.dialog.form.link = process.env.IMAGE_URL_HEAD + res.url
            this.audio.push({name:res.name,url:process.env.IMAGE_URL_HEAD + res.url,title:'',tips:'',image:''});
          })
      },
      onPageChange(val){
        this.nowPage = val;
        this.getList()
      },
      changeStatus(data){
        let msg;
        let status;
        if(data.status === 1){
          msg = '此操作将下架，是否继续？';
          status = 2
        }else{
          msg = '此操作将上架，是否继续？';
          status = 1
        }
        this.$confirm(msg, '提示', {
          confirmButtonText: '继续',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let json = {
            status:status
          };
          bannerChangeStatusApi(data.id,json).then(res=>{
            this.$message({
              type: 'success',
              message: '修改成功!'
            });
            this.getList()
          })
        })

      },
      onSizeChange(val){
        this.nowPage = 1;
        this.limit = val;
        this.getList()
      },
      getList(){
        this.loading = true;
        let json = {
          limit: this.limit,
          page: this.nowPage
        };
        if(this.searchFrom.status !== '-1'){
          json.status = this.searchFrom.status
        }
        getBannerListApi(this.searchFrom.type,json).then(res=>{
          if (res) {
            this.bannerList = res.list;
            this.total = res.total;
            this.loading = false;
          }
        })
      },
      edit(data){
        this.dialog.form.id = data.id;
        this.dialog.title = '编辑';
        getBannerDetailApi(data.id).then((res)=>{
          this.dialog.form.title = res.title
          this.dialog.form.sub_title = res.sub_title
          this.dialog.form.link = res.link
          this.imageList = [{name:res.url,url:res.url}]
          this.dialog.show = true;
          this.uploadShow = false;
          this.audio=[];
        })
      },
      add(){
        this.dialog.show = true;
        this.dialog.form.id = '';
        this.dialog.title = '新增';
        this.dialog.form.title = ''
        this.dialog.form.sub_title = ''
        this.dialog.form.link = '';
        this.imageList = [];
        this.uploadShow = true;
        this.audio=[];
      },
      del(data){
        this.$confirm('此操作将删除该?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          delBannerApi(data.id).then(res=>{
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
            this.getList()
          });
        });
      },
      handleAvatarSuccess(res) {
        this.imageList = [{name:res.data.url,url:process.env.IMAGE_URL_HEAD + res.data.url}]
        this.dialog.form.url = process.env.IMAGE_URL_HEAD + res.data.url
      },
      beforeAvatarUpload(){
        this.uploadShow = false
      },
      handleRemove(){
        this.uploadShow = true
      },
      sub(){
        this.$refs['form'].validate((valid) => {
          if(valid){
            let dia = this.dialog;
            if(dia.form.id){
              let json = {
                title:dia.form.title,
                link:dia.form.link,
                sub_title:dia.form.sub_title
              };
              if (this.imageList.length > 0) {
                  json.url = this.imageList[0].url
              }
              this.$confirm('确认修改', '提示', {
                confirmButtonText: '继续',
                cancelButtonText: '取消',
                type: 'warning'
              }).then(() => {
                editBannerApi(dia.form.id,json).then(()=>{
                  this.$message({
                    type: 'success',
                    message: '修改成功!'
                  });
                  dia.show = false;
                  this.getList()
                })
              })

            }else{
              let json = {
                title:dia.form.title,
                link:dia.form.link,
                sub_title:dia.form.sub_title
              };
              if (this.imageList.length > 0) {
                json.url = this.imageList[0].url
              }
              this.$confirm('确认添加', '提示', {
                confirmButtonText: '继续',
                cancelButtonText: '取消',
                type: 'warning'
              }).then(() => {
                addBannerApi(this.searchFrom.type,json).then(()=>{
                  this.$message({
                    type: 'success',
                    message: '添加成功!'
                  });
                  dia.show = false;
                  this.getList()
                })
              })

            }
          }
        })
      },
      moveUp(index){
        let list = this.bannerList;
        this.sort(list[index].id,list[index-1].id);
      },
      moveDown(index){
        let list = this.bannerList;
        this.sort(list[index + 1].id,list[index].id);
      },
      sort(upId, downId){
        this.loading = true;
        moveApi(upId,downId).then(()=>{
          this.loading = false;
          this.getList();
        })
      },
      uploadFile(a) {
        this.loading = true;
        this.$store.dispatch('setProgress',{type:'new',id:a.file.uid});
        this.fileUid = a.file.uid;
        uploadFileApi({file:a.file,type:'local'}).then(res=>{
          this.imageList = [{name:res.url,url:process.env.IMAGE_URL_HEAD + res.url}]
          this.loading = false;
          this.$message({
            type: 'success',
            message: '上传成功!'
          });
        }).catch(()=>{
          this.loading = false;
        })
      }
    }
  }
</script>
<style @scoped lang="less">
  .banner{
    .head{
      /*padding: 5px;*/
      margin-bottom: 10px;
    }
    width: 100%;
    padding: 20px 0;
    .page-div{
      text-align: center;
      padding-top: 20px
    }
  }
  .short-banner {
    width: 50px;
  }
  .clear-both{
  &:after{
     content: '';
     display: block;
     clear: both;
   }
  }
  .size {
    color: #666;
    font-size: 14px;
  }
</style>
<style>
  .disabled .el-upload--picture-card {
    display: none !important;
  }
</style>
