<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="相片名称" prop="picName">
        <el-input v-model="queryParams.picName" placeholder="请输入相片名称" clearable
                  @keyup.enter.native="handleQuery"/>
        <!--    用于阻止按下回车键时刷新页面    -->
        <input type="text" class="form-control" style="display: none"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
                   v-hasPermi="['system:pic:add']">新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
                   v-hasPermi="['system:pic:edit']">修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
                   v-hasPermi="['system:pic:remove']">删除
        </el-button>
      </el-col>
      <!--      <el-col :span="1.5">-->
      <!--        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"-->
      <!--                   v-hasPermi="['system:pic:export']">导出-->
      <!--        </el-button>-->
      <!--      </el-col>-->
      <!--      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>-->
    </el-row>

    <el-table v-loading="loading" ref="table" :data="picList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="序号" align="center" prop="seqencing" width="80" v-if="columns[2].visible"/>
      <el-table-column label="园区照片" align="center" prop="picName" v-if="columns[0].visible">
        <template slot-scope="scope">
          <ListImage :image-url="pev+scope.row.picUrl"></ListImage>
        </template>
      </el-table-column>
      <el-table-column label="相片名称" align="center" prop="picName" show-overflow-tooltip v-if="columns[1].visible"/>
      <el-table-column label="是否轮播显示" align="center" prop="isShow">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.isShow" active-value="1" inactive-value="0"
                     @change="handleIsShow(scope.row)"></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="创建者" align="center" prop="createBy" v-if="columns[4].visible"/>
      <el-table-column label="创建时间" align="center" prop="createTime" v-if="columns[5].visible"/>
      <el-table-column label="备注" prop="remark" align="center" v-if="columns[3].visible" show-overflow-tooltip/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" v-if="columns[6].visible">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
                     v-hasPermi="['system:pic:edit']">修改
          </el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                     v-hasPermi="['system:pic:remove']">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
                @pagination="getList"/>

    <!-- 添加或修改园区照片对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="900px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="90px" style="width: 80%; margin: auto">
        <el-form-item prop="gardenEmblem"
                      style="display: flex; text-align: center; justify-content: center; transform: translateX(-30px)">
          <el-upload v-loading="uploadLoading" class="avatar-uploader" action="#" accept="image/*"
                     :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload"
                     :http-request="uploadImage">
            <img v-if="imageUrl" :src="imageUrl" class="avatar"/>
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
          <!--          <div>上传园徽</div>-->
        </el-form-item>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="名称:" prop="picName">
              <el-input v-model="form.picName" placeholder="请输入相片名称" style="width: 100%"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="排序:" prop="seqencing">
              <el-input-number v-model="form.seqencing" controls-position="right" style="width: 100%"
                               :min="1"></el-input-number>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <!--<el-col :span="12">-->
          <!--  <el-form-item label-width="130px">-->
          <!--    <span slot="label">-->
          <!--      <el-tooltip content="是否作为微信公共号首页轮播图" placement="top">-->
          <!--        <i class="el-icon-question"></i>-->
          <!--      </el-tooltip>-->
          <!--      是否轮播显示-->
          <!--    </span>-->
          <!--    <el-switch v-model="form.isShow" active-value="1" inactive-value="0"></el-switch>-->
          <!--  </el-form-item>-->
          <!--</el-col>-->
          <el-col :span="24">
            <el-form-item label="备注:" prop="remark">
              <el-input v-model="form.remark" type="textarea" :autosize="{ minRows: 3 }" :maxlength="TEXT_SIZE"
                        show-word-limit/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 导出 -->
    <ExportTable :open-export.sync="exportOptions.open" :title="exportOptions.title" @export="exportFile"></ExportTable>
  </div>
</template>

<script>
import {listPic, getPic, delPic, addPic, updatePic, updateState} from '@/api/smartSchool/schoolManage/introduce/pic'
import picAvatar from '@/views/smartSchool/schoolManage/introduce/schoolInfo/profile/picAvatar'
import {changeUserStatus} from '@/api/system/user'
import {uploadImage as commonUpload} from '@/api/common'
import {ExportType, TEXT_SIZE} from '@/enums/common'

export default {
  name: 'index',
  components: {picAvatar},
  data() {
    return {
      pev: process.env.VUE_APP_BASE_API,
      // 输入框字数限制
      TEXT_SIZE,
      //是否上传的院徽
      isUploadPic: false,
      //照片是否删除
      options: [
        {
          value: 0,
          label: '否'
        },
        {
          value: 1,
          label: '是'
        }
      ],
      //获取子组件传来的信息
      pic: [],
      // 图片路径
      imageUrl: undefined,
      // 图片上传遮罩层
      uploadLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 园区照片表格数据
      picList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        picName: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        picName: [{required: true, message: '请输入相片名称', trigger: 'blur'}],
        seqencing: [{required: true, message: '请输入排序', trigger: 'blur'}],
        remark: [{max: TEXT_SIZE, message: '备注信息在0到200字之间', trigger: 'blur'}]
      },
      //设置table列隐藏与显示
      columns: [
        {key: 0, label: `园区照片`, visible: true},
        {key: 1, label: `相片名称`, visible: true},
        // {key: 2, label: `相片路径`, visible: true},
        {key: 2, label: `排序`, visible: true},
        {key: 3, label: `备注`, visible: true},
        {key: 4, label: `创建者`, visible: true},
        {key: 5, label: `创建时间`, visible: true},
        {key: 6, label: `操作`, visible: true}
      ],
      // 作为临时图片展示
      tempImage: '',
      // 导出选项
      exportOptions: {
        title: '选择导出类别',
        open: false
      }
    }
  },
  created() {
    this.getList()
  },
  watch: {
    pic: {
      handler(newValue, oldValue) {
        console.log('watch----oldValue', oldValue)
        console.log('watch----newValue', newValue)
        this.isUploadPic = newValue[3]
      }
    }
  },
  methods: {
    //是否删除 选中值发生变化时id处理函数
    selectChangeHandler(value) {
      this.form.isShow = value
    },
    /** 查询园区照片列表 */
    getList() {
      this.loading = true
      this.picList = []
      listPic(this.queryParams).then(response => {
        this.picList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    //获取图片信息
    getSchoolInfoPic(val) {
      this.pic = val
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        params: {},
        id: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        delFlag: null,
        picName: null,
        picUrl: null,
        seqencing: null,
        isShow: 0
      }
      this.imageUrl = ''
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.throttle(() => {
        this.queryParams.pageNum = 1
        this.getList()
      })
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '添加园区照片'
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const ids = row.id || this.ids
      getPic(ids).then(response => {
        this.form = response.data
        this.imageUrl = this.pev + this.form.picUrl
        this.open = true
        this.title = '修改园区照片'
      })
    },
    // 上传成功回调
    handleAvatarSuccess(res, file) {
      this.imageUrl = res.data.url
      console.log(file)
      this.commonUpload(file)
    },
    // 上传前格式和图片大小限制
    beforeAvatarUpload(file) {
      const type = file.type === 'image/jpeg' || 'image/jpg' || 'image/webp' || 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!type) {
        this.$message.error('图片格式不正确!(只能包含jpg，png，webp，JPEG)')
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!')
      }
      return type && isLt2M
    },

    // 上传图片
    uploadImage(file) {
      const fileData = file.file
      const formData = new FormData()
      formData.append('file', fileData)
      this.uploadLoading = true
      commonUpload(formData)
        .then(response => {
          this.uploadLoading = false
          this.$modal.msgSuccess('上传成功')
          this.imageUrl = this.pev + response.url
          // this.form.picUrl = process.env.VUE_APP_BASE_API + response.url
          this.form.picUrl = response.url
        })
        .catch(error => {
          this.uploadLoading = false
        })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          this.$modal.loading('正在上传数据，请稍等...')
          if (this.form.id != null) {
            updatePic({
              ...this.form
            })
              .then(response => {
                this.$modal.closeLoading()
                this.$modal.msgSuccess('修改成功')
                this.open = false
                this.getList()
              })
              .catch(error => {
                this.$modal.closeLoading()
              })
          } else {
            addPic({
              ...this.form,
              isShow: '0'
            })
              .then(response => {
                this.$modal.closeLoading()
                this.$modal.msgSuccess('新增成功')
                this.open = false
                this.getList()
              })
              .catch(error => {
                this.$modal.closeLoading()
              })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      if (ids) {
        this.$modal
          .confirm(`是否确认删除选中的${Object.hasOwnProperty.call(ids, 'length') ? ids.length : 1}条数据？`)
          .then(() => {
            this.$modal.loading('正在处理数据，请稍等...')
            return delPic(ids)
          })
          .then(() => {
            this.$modal.closeLoading()
            this.getList()
            this.$modal.msgSuccess('删除成功')
          })
          .catch(() => {
            this.$modal.closeLoading()
          })
      }
    },
    /** 导出按钮操作 */
    handleExport() {
      // 导出选中，导出全部，根据查询条件导出
      this.exportOptions.open = true
    },
    /** 导出 */
    exportFile(callback) {
      const ids = this.ids
      const options = [
        {type: ExportType.TOTAL, path: '/pic/export', params: {}},
        {type: ExportType.SELECT, path: '/pic/export/' + this.ids, params: {}},
        {type: ExportType.QUERY, path: '/pic/export', params: this.queryParams}
      ]
      callback(options, `校园风采${new Date().getTime()}.xlsx`)
    },

    /** 是否做为轮播图 */
    handleIsShow(row) {
      this.$modal
        .confirm(row.isShow === '1' ? '是否确认显示为轮播图？' : '是否取消显示为轮播图？')
        .then(() => {
          this.$modal.loading('正在修改状态，请稍等...')
          updateState(row.id, row.isShow)
            .then(response => {
              this.$modal.closeLoading()
              this.$modal.msgSuccess('修改成功')
            })
            .catch(error => {
              this.$modal.closeLoading()
              row.isShow = row.isShow === '0' ? '1' : '0'
            })
        })
        .catch(() => {
          row.isShow = row.isShow === '0' ? '1' : '0'
        })
    }
  }
}
</script>
<style scoped>
.avatar,
.avatar-uploader,
.el-icon-plus {
  width: 650px;
}
</style>
