<template>
    <el-card shadow="never" class="aui-card--fill">
        <div class="mod-home">
            <div class="page-title">{{ title }}</div>
            <div class="btns adf">
                <el-button type="primary" icon="el-icon-plus" @click="handleAdd">新增banner图</el-button>
            </div>
        </div>
        <el-table :data="dataList" border cell-class-name="vertical-top-cell" v-loading="loading" empty-text="暂无广告" max-height="578px" style="margin-top: 18px;">
            <el-table-column label="序号" width="50">
                <template #default="scope">
                    {{ scope.$index + 1 }}
                </template>
            </el-table-column>
            <el-table-column label="banner图位置" prop="space">
                <template #default="{ row }">{{ spaceCfg[row.space]||'' }}</template>
            </el-table-column>
            <el-table-column label="图片" prop="fileUrl">
                <template #default="{ row }">
                    <img :src="row.fileUrl" v-if="row.fileUrl" style="width: 130px;height: auto;" @click="showBigImg(row.fileUrl)">
                </template>
            </el-table-column>
            <el-table-column label="banner图标题" prop="title"></el-table-column>
            <el-table-column label="跳转链接" prop="redirect"></el-table-column>
            <!-- <el-table-column label="点击量" prop="xx"></el-table-column> -->
            <el-table-column label="创建时间" prop="createDate"></el-table-column>
            <el-table-column label="上架状态" prop="enable">
                <template #default="{ row }">
                    <el-switch v-model="row.enable" active-color="#33A7A7" inactive-color="#B9C0C8" @change="e=>statusChange(e,row)"></el-switch>
                </template>
            </el-table-column>
            <el-table-column label="操作" width="200">
                <template #default="scope">
                    <el-button link type="text" size="mini" @click="handleEdit(scope.row)">编辑</el-button>
                    <el-button link type="text" size="mini" @click="handleDelete(scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="queryParams.page"
            :page-sizes="[5, 10, 20, 50]"
            :page-size="10"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            v-show="total > 0">
        </el-pagination>
        <el-dialog width="40%" :visible.sync="show" :title="dialogTitle" @close="cancel">
            <el-form ref="advertRef" :model="advertForm" :rules="advertRules" label-width="100px" style="width: 90%;margin: 0 auto;">
                <el-form-item label="banner图位置" prop="space">
                    <el-select v-model="advertForm.space" placeholder="请选择banner图位置" style="width:100%">
                        <el-option label="首页" :value="1"></el-option>
                        <el-option label="发布问卷" :value="2"></el-option>
                    </el-select>
                </el-form-item>
                <!-- <el-form-item label="banner图类型" prop="type">
                    <el-select v-model="advertForm.type" placeholder="请选择banner图类型" style="width:100%">
                        <el-option label="banner区" :value="1"></el-option>
                        <el-option label="弹框" :value="2"></el-option>
                    </el-select>
                </el-form-item> -->
                <el-form-item label="banner图标题" prop="title">
                    <el-input v-model="advertForm.title" placeholder="请输入banner图标题"></el-input>
                </el-form-item>
                <el-form-item label="配图" prop="" class="red">
                    <el-upload
                        list-type="picture-card"
                        :action="uploadUrl"
                        :headers="uploadHeaders"
                        :on-success="uploadFileSuccess"
                        :on-remove="removeFile"
                        :before-upload="beforeAvatarUpload"
                        :limit="1"
                        :file-list="fileList">
                        <i class="el-icon-plus"></i>
                    </el-upload>
                    <div class="dialog-tip">图片最小分辨率：702*200</div>
                </el-form-item>
                <el-form-item label="跳转链接" prop="redirectType">
                    <el-radio-group v-model="advertForm.redirectType">
                        <el-radio :label="1">微信公众号</el-radio>
                        <el-radio :label="2">微信小程序</el-radio>
                    </el-radio-group>
                    <el-input v-model="advertForm.redirect" placeholder="配置跳转链接"></el-input>
                </el-form-item>
            </el-form>
            <div class="demo-drawer__footer" style="display: flex;justify-content: end;">
                <el-button :loading="buttonLoading" type="primary" @click="submitForm">保 存</el-button>
                <el-button @click="cancel" style="margin-right: 5%;">取 消</el-button>
            </div>
        </el-dialog>
        <el-dialog width="40%" :visible.sync="bigShow" title="banner图图片" @close="bigShow=false">
            <img :src="bigImg" style="width: 100%;height: auto;">
            <div class="demo-drawer__footer" style="display: flex;justify-content: end;margin-top: 50px;">
                <el-button @click="bigShow=false" style="margin-right: 5%;">关 闭</el-button>
            </div>
        </el-dialog>
    </el-card>
</template>

<script>
import Cookies from 'js-cookie'
export default {
  data () {
    return {
      title: this.$route.meta.title,
      uploadUrl: `${window.SITE_CONFIG['apiURL']}/sys/oss/uploadFile`,
      uploadHeaders: { token: Cookies.get('token') },
      fileList: [],
      queryParams: {
        page: 1,
        limit: 10
      },
      spaceCfg: {
        '1': '首页',
        '2': '发布问卷'
      },
      typeCfg: {
        '1': 'banner区',
        '2': '弹框'
      },
      dataList: [],
      total: 0,
      loading: false,
      buttonLoading: false,
      show: false,
      bigShow: false,
      bigImg: '',
      dialogTitle: '新增banner图',
      advertForm: {
        id: '',
        space: '',
        type: '',
        title: '',
        redirectType: 1,
        redirect: '',
        fileUrl: '',
        enable: 1
      },
      advertRules: {
        space: [
          { required: true, message: '请选择banner图位置', trigger: 'change' }
        ],
        title: [
          { required: true, message: '请输入banner图标题', trigger: 'blur' }
        ]
      }
    }
  },
  mounted () {
    this.getList()
  },
  methods: {
    getList () {
      this.loading = true
      this.$http.get('/core/advertisement/manage/page', { params: this.queryParams }).then(res => {
        if (res.data.code !== 0) return this.$message.error(res.data.msg)
        this.dataList = res.data.data.list
        this.dataList.forEach(item => {
          // eslint-disable-next-line no-unneeded-ternary
          item.enable = item.enable === 1 ? true : false
        })
        this.total = res.data.data.total
        this.loading = false
      })
    },
    handleSizeChange (e) {
      this.queryParams.limit = e
      this.getList()
    },
    handleCurrentChange (e) {
      this.queryParams.page = e
      this.getList()
    },
    handleAdd () {
      this.dialogTitle = '新增banner图'
      this.show = true
    },
    handleEdit (row) {
      this.dialogTitle = '编辑banner图'
      this.$http.get(`/core/advertisement/manage/${row.id}`).then(res => {
        if (res.data.code !== 0) return this.$message.error(res.data.msg)
        this.advertForm = { ...this.advertForm, ...res.data.data }
        this.fileList = [{ name: '', url: this.advertForm.fileUrl }]
        this.show = true
      })
    },
    submitForm () {
      this.$refs['advertRef'].validate((valid) => {
        if (valid) {
          if (this.fileList.length === 0) return this.$message.error('请上传图片')
          this.advertForm.fileUrl = this.fileList[0].url
          this.$http[this.advertForm.id ? 'put' : 'post']('/core/advertisement/manage', this.advertForm).then(res => {
            if (res.data.code !== 0) return this.$message.error(res.data.msg)
            this.$message.success('保存成功')
            this.fileList = []
            this.advertForm.fileUrl = ''
            this.cancel()
            this.getList()
          })
        } else {
          return false
        }
      })
    },
    cancel () {
      this.advertForm = {
        id: '',
        space: '',
        type: '',
        title: '',
        redirectType: 1,
        redirect: '',
        fileUrl: '',
        enable: 1
      }
      this.$refs['advertRef'].resetFields()
      this.show = false
    },
    handleDelete (row) {
      this.$confirm(`确认删除该banner图吗？`, '提示', {
        type: 'warning'
      }).then(() => {
        this.$http.delete('/core/advertisement/manage', { 'data': [row.id] }).then(res => {
          if (res.data.code !== 0) return this.$message.error(res.data.msg)
          this.$message.success('删除成功')
          this.getList()
        })
      })
    },
    statusChange (e, row) {
      let data = JSON.parse(JSON.stringify(row))
      data.enable = data.enable ? 1 : 0
      this.$http.put('/core/advertisement/manage', data).then(res => {
        if (res.data.code !== 0) return this.$message.error(res.data.msg)
        this.getList()
      })
    },
    uploadFileSuccess (e) {
      if (e.data) {
        this.fileList.unshift({ name: '', url: e.data })
      }
    },
    removeFile (e) {
      this.fileList = []
      this.advertForm.fileUrl = ''
    },
    beforeAvatarUpload (file) {
      // if (!['image/jpeg', 'image/png', 'image/jpg'].includes(file.type)) {
      //     return proxy.$message.error('上传图片只能是 JPG/PNG/JPEG 格式!');
      // }
      // if (file.size / 1024 / 1024 > 5) {
      //     return proxy.$message.error('上传图片大小不能超过 5MB!');
      // }
      return true
    },
    showBigImg (imgurl) {
      this.bigImg = imgurl
      this.bigShow = true
    }
  }
}
</script>

<style scoped lang="scss">
.page-title{
    font-family: PingFang-SC, PingFang-SC;
    font-weight: bold;
    font-size: 16px;
    color: #252525;
    line-height: 22px;
}
.btns{
    justify-content: flex-end;
    margin-top: -10px;

}
</style>
