<template>
  <div class="app-container">
          <el-button type="primary" @click="handleAdd" icon="el-icon-plus">新增</el-button>
        <el-table
          :data="tableData"
          style="width: 100%;margin-top:10px;"
          border
          fit
          v-loading="listLoading"
          highlight-current-row
          max-height="600"
          row-key="id"
          default-expand-all
          :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
          
        >
          <el-table-column type="index" width="50"></el-table-column>
          <el-table-column label="图片名称">
            <template slot-scope="scope">{{ scope.row.name }}</template>
          </el-table-column>
          <el-table-column label="图片">
            <template slot-scope="scope">
                    <img :src="scope.row.path" width="160" height="90" />
                </template>
          </el-table-column>
          <el-table-column label="链接">
            <template slot-scope="scope">
              <span>{{ scope.row.url }}</span>
            </template>
          </el-table-column>
          <el-table-column label="排序数">
            <template slot-scope="scope">
              <span>{{ scope.row.sort }}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" label="操作">
            <template slot-scope="scope">
              <el-button
                type="primary"
                size="small"
                @click="handleEdit(scope)"
                icon="el-icon-edit"
                :disabled="!checkPermission(['banner_update'])"
              ></el-button>
              <el-button
                type="danger"
                size="small"
                @click="handleDelete(scope)"
                icon="el-icon-delete"
                :disabled="!checkPermission(['banner_delete'])"
              ></el-button>
            </template>
          </el-table-column>
        </el-table>

    <el-dialog :visible.sync="dialogVisible" :title="dialogType==='edit'?'编辑':'新增'" >
      <el-form :model="banner" label-width="80px" label-position="right" :rules="rule1" ref="Form">
        <el-form-item label="名称" prop="name">
          <el-input v-model="banner.name" placeholder="名称" />
        </el-form-item>
        <el-form-item label="链接" prop="url">
          <el-input v-model="banner.url" placeholder="链接" />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="banner.sort" :min="1" :max="4"></el-input-number>
        </el-form-item>
        <el-form-item label="图片" prop="path" >
                    <el-upload
            class="avatar-uploader"
            :headers="upHeaders"
            :action="upUrl"
            accept="image/jpeg, image/gif, image/png, image/bmp"
            :show-file-list="false"
            :on-success="handleImgSuccess"
            :before-upload="beforeImgUpload"
          >
          <img v-if="banner.path" :src="banner.path" style="width: 80%;height: auto;display: block;"/>
          <el-button size="small" type="primary" v-else>点击上传</el-button>
          </el-upload>
        </el-form-item>
      </el-form>
      <div style="text-align:right;">
        <el-button type="danger" @click="dialogVisible=false">取消</el-button>
        <el-button type="primary" @click="confirmBanner('Form')">确认</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getBannerAll, createBanner, deleteBanner, updateBanner } from "@/api/banner";
import { deepClone } from "@/utils";
import checkPermission from "@/utils/permission";
import { upUrl } from "@/api/file";
import { getToken } from "@/utils/auth";



const defaultBanner = {
        id: "",
        name: "",
        url:"",
        sort:0,
        path:""
      };
export default {
  data() {
    return {
      upHeaders: { Authorization: "JWT " + getToken() },
      upUrl: upUrl(),
      banner: {
        id: "",
        name: "",
        url:"",
        sort:0,
        path:""
      },
      search:'',
      tableData: [],
      bannerData:[],
      listLoading: true,
      dialogVisible: false,
      dialogType: "new",
      rule1: {
        name: [{ required: true, message: "请输入名称", trigger: "blur" }],
        path: [{ required: true, message: "请上传文件", trigger: "blur" }],
      },
      fileList:[],
    };
  },
  computed: {},
  created() {
    this.getList();
  },
  methods: {
    checkPermission,
    handleImgSuccess(res, file) {
        this.banner.path = res.data.path
    },
    beforeImgUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 0.6;
      if (!isLt2M) {
        this.$message.error("上传图片大小不能超过 600KB!");
      }
      return isLt2M;
    },
    getList() {
      this.listLoading = true
      getBannerAll().then(response => {
        if(response.data.length){
        this.tableData = response.data;
        }
        this.listLoading = false
      });
    },
    resetFilter() {
      this.getList();
    },
    // handleFilter() {
    //   let newData = this.bannerData.filter(data => !this.search || data.name.toLowerCase().includes(this.search.toLowerCase()))
    // },
    handleAdd() {
      this.banner = Object.assign({}, defaultBanner);
      this.dialogType = "new";
      this.dialogVisible = true;
      this.$nextTick(() => {
        this.$refs["Form"].clearValidate();
      });
    },
    handleEdit(scope) {
      this.banner = Object.assign({}, scope.row); // copy obj
      this.dialogType = "edit";
      this.dialogVisible = true;
      this.$nextTick(() => {
        this.$refs["Form"].clearValidate();
      });
    },
    handleDelete(scope) {
      this.$confirm("确认删除?", "警告", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "error"
      })
        .then(async () => {
          await deleteBanner(scope.row.id);
          this.getList()
          this.$message({
            type: "success",
            message: "成功删除!"
          });
        })
        .catch(err => {
          // console.error(err);
        });
    },
    async confirmBanner(form) {
      this.$refs[form].validate(valid => {
        if (valid) {
          const isEdit = this.dialogType === "edit";
          if (isEdit) {
            updateBanner(this.banner.id, this.banner).then(() => {
              this.getList();
              this.dialogVisible = false;
              this.$message.success('成功')
            });
          } else {
            createBanner(this.banner).then(res => {
              // this.banner = res.data
              // this.tableData.unshift(this.banner)
              this.getList();
              this.dialogVisible = false;
              this.$message.success('成功')
            });
          }
        } else {
          return false;
        }
      });
    }
  }
};
</script>
