<template>
  <div class="app-container">

    <!-- 查询区域 -->
    <el-form :model="listQuery" size="small" :inline="true" label-position="top">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="品牌商 ID">
            <el-input clearable placeholder="请输入品牌商 ID" v-model="listQuery.id"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="品牌商名称">
            <el-input clearable placeholder="请输入品牌商名称" v-model="listQuery.name"></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="搜索">
            <el-button style="width: 100%;" type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="重置">
            <el-button style="width: 100%;" icon="el-icon-refresh" type="primary" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <!-- 操作按钮 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" class="editButton" size="small" icon="el-icon-plus" @click="handleCreate">添加</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" icon="el-icon-download" size="small" @click="handleDownload" :loading="downloadLoading">导出</el-button>
      </el-col>
    </el-row>

    <!-- 查询结果 -->
    <div class="border-card">
      <el-table height="450" size="small" :data="list" v-loading="listLoading" element-loading-text="正在查询中。。。" border fit
        highlight-current-row>

        <el-table-column type="index" label="序号" header-align="center" align="center">
        </el-table-column>

        <el-table-column align="center" width="150px" label="品牌商 ID" prop="id">
        </el-table-column>

        <el-table-column align="center" min-width="100px" label="品牌商名称" prop="name">
        </el-table-column>

        <el-table-column align="center" min-width="300px" label="介绍" prop="simpleDesc">
        </el-table-column>

        <el-table-column align="center" min-width="50px" label="底价" prop="floorPrice">
        </el-table-column>

        <el-table-column align="center" min-width="100px" label="是否显示" prop="isShow">
          <template slot-scope="scope">
            <el-tag :type="scope.row.isShow ? 'success' : 'error'">{{ scope.row.isShow ? '可显示' : '不显示' }}</el-tag>
          </template>
        </el-table-column>

        <el-table-column align="center" min-width="100px" label="是否新上" prop="isNew" :formatter="judgeIsnew">
        </el-table-column>

        <el-table-column align="center" label="操作" width="240px" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button type="text" icon="el-icon-edit" class="editText" size="small" @click="handleUpdate(scope.row)">编辑</el-button>
            <el-button type="text" icon="el-icon-delete" class="deleteText" size="small" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
          :current-page="listQuery.page" :page-sizes="[10, 20, 30, 50]" :page-size="listQuery.limit"
          layout="total, sizes, prev, pager, next, jumper" :total="total">
        </el-pagination>
      </div>
    </div>

    <!-- 添加或修改对话框 -->
    <el-dialog :close-on-click-modal="false" :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" width="70%">
      <el-form :rules="rules" ref="dataForm" :model="dataForm" status-icon label-position="top"
        style='margin: 0 50px;'>

        <el-form-item label="品牌商名称" prop="name">
          <el-input v-model="dataForm.name" placeholder="请输入品牌商名称"></el-input>
        </el-form-item>

        <el-form-item label="介绍" prop="simpleDesc">
          <el-input type="textarea" :autosize="{ minRows: 2, maxRows: 4 }" placeholder="请输入介绍"
            v-model="dataForm.simpleDesc">
          </el-input>
        </el-form-item>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="品牌商图片" style="display: block !important;">
              <el-tooltip content="建议图片规格：375*145 图片宽度扩大两倍，高度等比例扩大" placement="top-start">
                <el-upload class="avatar-uploader" :action="fileImgUrl" :show-file-list="false"
                  :on-success="handleBrandSuccess" :before-upload="beforeBrandUpload">
                  <img v-if="dataForm.picUrl" :src="dataForm.picUrl" class="avatar">
                  <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                </el-upload>
              </el-tooltip>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="宣传图片" style="display: block !important;">
              <el-tooltip content="建议图片规格：375*145 图片宽度扩大两倍，高度等比例扩大" placement="top-start">
                <el-upload class="avatar-uploader" :action="fileImgUrl" :show-file-list="false"
                  :on-success="handlePublicitySuccess" :before-upload="beforePublicityUpload">
                  <img v-if="dataForm.listPicUrl" :src="dataForm.listPicUrl" class="avatar">
                  <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                </el-upload>
              </el-tooltip>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="APP 宣传图片" style="display: block !important;">
              <el-tooltip content="建议图片规格：375*145 图片宽度扩大两倍，高度等比例扩大" placement="top-start">
                <el-upload class="avatar-uploader" :action="fileImgUrl" :show-file-list="false"
                  :on-success="handleAppcitySuccess" :before-upload="beforeAppcityUpload">
                  <img v-if="dataForm.appListPicUrl" :src="dataForm.appListPicUrl" class="avatar">
                  <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                </el-upload>
              </el-tooltip>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="底价" prop="floorPrice">
              <el-input v-model="dataForm.floorPrice" placeholder="请输入底价"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="是否显示" prop="isShow">
              <el-select v-model="dataForm.isShow" placeholder="请选择" style="width: 100%;">
                <el-option label="显示" :value="true"></el-option>
                <el-option label="不显示" :value="false"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="是否新上" prop="isNew">
              <el-select v-model="dataForm.isNew" placeholder="请选择" style="width: 100%;">
                <el-option label="新上" :value="true"></el-option>
                <el-option label="不是新上" :value="false"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="新上宣传图片" prop="newPicUrl" v-if="dataForm.isNew === true">
          <el-input v-model="dataForm.newPicUrl" placeholder="请输入新上宣传图片地址" style="width: 80%;"></el-input>
          <el-upload action="#" list-type="picture" :show-file-list="false" :limit="1" :http-request="uploadNewPicUrl"
            style="display: inline-block;">
            <el-button size="small" type="primary">点击上传</el-button>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button v-if="dialogStatus == 'create'" type="primary" @click="createData">确定</el-button>
        <el-button v-else type="primary" @click="updateData">确定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<style>

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.avatar-uploader {
  display: inline-block;
}

</style>

<script>
import { listBrand, createBrand, updateBrand, deleteBrand } from '@/api/brand'
import { createStorage } from '@/api/storage'
import waves from '@/directive/waves' // 水波纹指令
export default {
  name: 'Brand',
  directives: { waves },
  data() {
    return {
      list: undefined,
      total: undefined,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 10,
        id: undefined,
        name: undefined,
        sort: '+id'
      },
      dataForm: {
        id: undefined,
        name: '',
        simpleDesc: '',
        floorPrice: undefined,
        picUrl: undefined,
        listPicUrl: undefined,
        appListPicUrl: undefined,
        isShow: undefined,
        isNew: undefined,
        newPicUrl: undefined
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '创建'
      },
      rules: {
        name: [{ required: true, message: '品牌商名称不能为空', trigger: 'blur' }]
      },
      downloadLoading: false,
      fileImgUrl: this.upLoadUrl
    }
  },
  created() {
    this.getList()
  },
  methods: {
    /** 重置按钮操作 */
    resetQuery() {
      this.listQuery = {
        page: 1,
        limit: 10,
        id: undefined,
        name: undefined,
        sort: '+id'
      }
      this.handleQuery()
    },
    judgeIsnew(data) {
      return data.isNew == '1' ? '是' : '不是'
    },
    getList() {
      this.listLoading = true
      listBrand(this.listQuery).then(response => {
        this.list = response.data.data.items
        this.total = response.data.data.total
        this.listLoading = false
      }).catch(() => {
        this.list = []
        this.total = 0
        this.listLoading = false
      })
    },
    handleQuery() {
      this.listQuery.page = 1
      this.getList()
    },
    handleSizeChange(val) {
      this.listQuery.limit = val
      this.getList()
    },
    handleCurrentChange(val) {
      this.listQuery.page = val
      this.getList()
    },
    resetForm() {
      this.dataForm = {
        id: undefined,
        name: '',
        simpleDesc: '',
        floorPrice: undefined,
        picUrl: undefined,
        listPicUrl: undefined,
        appListPicUrl: undefined,
        isShow: undefined,
        isNew: undefined,
        newPicUrl: undefined
      }
    },
    handleCreate() {
      this.resetForm()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    uploadPicUrl(item) {
      const formData = new FormData()
      formData.append('file', item.file)
      createStorage(formData).then(res => {
        this.dataForm.picUrl = res.data.data.url
      }).catch(() => {
        this.$message.error('上传失败，请重新上传')
      })
    },
    uploadListPicUrl(item) {
      const formData = new FormData()
      formData.append('file', item.file)
      createStorage(formData).then(res => {
        this.dataForm.listPicUrl = res.data.data.url
      }).catch(() => {
        this.$message.error('上传失败，请重新上传')
      })
    },
    uploadAppListPicUrl(item) {
      const formData = new FormData()
      formData.append('file', item.file)
      createStorage(formData).then(res => {
        this.dataForm.appListPicUrl = res.data.data.url
      }).catch(() => {
        this.$message.error('上传失败，请重新上传')
      })
    },
    uploadNewPicUrl(item) {
      const formData = new FormData()
      formData.append('file', item.file)
      createStorage(formData).then(res => {
        this.dataForm.newPicUrl = res.data.data.url
      }).catch(() => {
        this.$message.error('上传失败，请重新上传')
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          createBrand(this.dataForm).then(response => {
            this.list.unshift(response.data.data)
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '创建成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleUpdate(row) {
      this.dataForm = Object.assign({}, row)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          updateBrand(this.dataForm).then(() => {
            for (const v of this.list) {
              if (v.id === this.dataForm.id) {
                const index = this.list.indexOf(v)
                this.list.splice(index, 1, this.dataForm)
                break
              }
            }
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '更新成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleDelete(row) {
      deleteBrand(row).then(response => {
        this.$notify({
          title: '成功',
          message: '删除成功',
          type: 'success',
          duration: 2000
        })
        const index = this.list.indexOf(row)
        this.list.splice(index, 1)
      })
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['品牌商 ID', '品牌商名称', '介绍', '低价', '是否显示', '品牌商图片', '宣传图片', 'APP 宣传图片', '是否新上', '新上宣传图片']
        const filterVal = ['id', 'name', 'simpleDesc', 'floorPrice', 'isShow', 'picUrl', 'listPicUrl', 'appListPicUrl', 'isNew', 'newPicUrl']
        excel.export_json_to_excel2(tHeader, this.list, filterVal, '品牌商信息')
        this.downloadLoading = false
      })
    },

    // 图片上传开始
    // 品牌商图片
    handleBrandSuccess(res, file) {
      this.dataForm.picUrl = res.data.url
    },
    beforeBrandUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isLt2M
    },
    // 宣传图片
    handlePublicitySuccess(res, file) {
      this.dataForm.listPicUrl = res.data.url
    },
    beforePublicityUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isLt2M
    },
    // APP 宣传图片
    handleAppcitySuccess(res, file) {
      this.dataForm.appListPicUrl = res.data.url
    },
    beforeAppcityUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isLt2M
    }
  }
}
</script>