<template>
  <div :class="{'m-container': type === 'DEFAULT'}">
    <h2 v-if="type === 'DEFAULT'">
      <el-page-header @back="onCancel" :content="detailName"></el-page-header>
    </h2>
    <div class="m-core">
      <div class="buttons">
        <auth :auths="['photo/add']">
          <el-button type="primary" @click="openUpload()">{{type === 'DEFAULT' ? '上传照片' : '上传证书'}}</el-button>
        </auth>
        <auth :auths="['photo/batchUpdate']">
          <el-button type="primary" :disabled="list.length == 0" v-if="!editing" @click="changeMode()">{{type === 'DEFAULT' ? '编辑照片' : '编辑证书'}}</el-button>
        </auth>
        <auth :auths="['photo/del']">
          <el-button type="danger" v-if="editing" @click="remove()">{{type === 'DEFAULT' ? '删除照片' : '删除证书'}}</el-button>
        </auth>
        <el-button type="primary" v-if="editing" @click="confirm()">确定</el-button>
        <el-button type="primary" v-if="editing" @click="cancel()">取消</el-button>
      </div>
      <el-alert
        v-if="editing"
        type="info"
        class="alert"
        :closable="false">
        <div slot="title">
          <el-button class="btn" type="text" :disabled="list.length === checked.length" @click="checkAll()">全选</el-button>
          <el-button class="btn" type="text" :disabled="!checked.length" @click="checked = []">取消选择</el-button>
          <span>共{{list.length}}条, 已选择{{checked.length}}条</span>
        </div>
      </el-alert>
      <el-checkbox-group v-model="checked">
        <draggable :list="list" :disabled="!editing" style="display: flex;">
          <div
            v-for="(item) in list"
            :key="item.url"
            class="img-container"
          >
            <auth :auths="['photo/del']">
              <div v-if="editing" class="ctrl-bar">
                <el-checkbox class="check" :label="item.id"></el-checkbox>
                <i class="el-icon-view" :class="{active: views.includes(item.id)}" @click="setView(item)"></i>
              </div>
              <div v-else class="ctrl-bar-view">
                <el-tooltip effect="dark" content="设为封面" placement="top" :open-delay=".5">
                  <i class="el-icon-picture-outline-round" @click="setCover(item)" v-if="type === 'DEFAULT'"></i>
                  <i v-else></i>
                </el-tooltip>
                <el-tooltip effect="dark" :content="views.includes(item.id) ? '设为不可见' : '设为可见'" placement="top" :open-delay=".5">
                  <i class="el-icon-view" :class="{active: views.includes(item.id)}" @click="setViewItem(item)"></i>
                </el-tooltip>
              </div>
            </auth>
            <el-image
              :src="item.url"
              class="img"
              :preview-src-list="list.map(item => item.url)">
            </el-image>
            <el-tooltip v-if="!editing" class="item" effect="dark" :content="item.name" placement="top" :open-delay=".5">
              <div class="name">{{item.name}}</div>
            </el-tooltip>
            <el-input class="nameinput" v-else v-model="item.name" size="mini" :placeholder="'请输入' + (type === 'DEFAULT' ? '照片' : '证书') + '名称'" clearable/>
          </div>
        </draggable>
      </el-checkbox-group>
      <empty v-if="list.length == 0"/>
    </div>
    <el-dialog
      :title="type === 'DEFAULT' ? '上传照片' : '上传证书'"
      :visible.sync="uploadVisible"
      v-if="uploadVisible"
    >
      <upload-popup
        @close="uploadVisible = false"
        @submited="submited"
        :name="$route.query.name"
        :query="queryIdOrType"
      />
    </el-dialog>
  </div>
</template>
<script>
import draggable from 'vuedraggable'
import uploadPopup from '@/views/resetTeaming/components/training-photos/upload'
import { photoQueryPage, photoDel, photoUpdate, photoAlbumUpdate } from '@/views/resetTeaming/components/training-photos/api'
export default {
  props: {
    type: {
      type: String,
      default: 'DEFAULT'
    },
  },
  components: {
    'upload-popup': uploadPopup,
    draggable,
  },
  computed: {
    detailName() {
      return this.$route.query.name || '相册详情'
    },
    queryIdOrType() {
      const id = this.$route.query.pid
      if (this.type === 'DEFAULT') {
        return {
          id,
          type: this.type,
        }
      }
      return {
        type: this.type,
        musicGroupId: this.$route.query.id,
      }
    },
  },
  data() {
    return {
      views: [],
      checked: [],
      uploadVisible: false,
      list: [],
      editing: false,
    }
  },
  mounted() {
    console.log(this.$route)
    this.FetchList()
  },
  methods: {
    onCancel() {
      this.$store.dispatch("delVisitedViews", this.$route);
      if (this.$route.query.returnUrl) {
        this.$router.push(this.$route.query.returnUrl);
      }
    },
    openUpload() {
      this.uploadVisible = true
    },
    setInitViwes() {
      this.views = this.list.filter(item => item.clientShow).map(item => item.id)
    },
    async setCover(item) {
      try {
        await this.$confirm('是否确认设置为封面?', '提示')
        await photoAlbumUpdate({
          ...this.queryIdOrType,
          coverUrl: item.url
        })
        this.$message.success('设置成功')
        this.FetchList()
      } catch (error) {}
    },
    async setViewItem(item) {
      try {
        await this.$confirm('是否确认修改可见状态?', '提示')
        await photoUpdate([{
          ...item,
          clientShow: +!item.clientShow
        }])
        this.$message.success('设置成功')
        this.FetchList()
      } catch (error) {}
    },
    changeMode() {
      this.checked = []
      this.setInitViwes()
      this.editing = true
    },
    cancel() {
      this.editing = false
      this.list = this.list.sort((a, b) => a.order - b.order)
    },
    submited() {
      this.FetchList()
    },
    setView(item){
      const indexOf = this.views.indexOf(item.id)
      if (indexOf > -1) {
        this.views.splice(indexOf, 1)
      } else {
        this.views.push(item.id)
      }
    },
    checkAll() {
      this.checked = this.list.map(item => item.id)
    },
    async FetchList() {
      try {
        const res = await photoQueryPage({...this.queryIdOrType, photoAlbumId: this.queryIdOrType.id})
        // console.log(res.data.rows)
        this.list = res.data.rows
        this.setInitViwes()
      } catch (error) {}
    },
    async confirm() {
      try {
        await this.$confirm('是否确认修改照片信息?', '提示')
        const data = this.list.map((item, index) => ([{
          ...item,
          order: index,
          clientShow: +this.views.includes(item.id)
        }]))
        await photoUpdate(data)
        this.editing = false
        this.$message.success('修改成功')
        this.FetchList()
      } catch (error) {
        console.log(error)
      }
    },
    async remove() {
      try {
        await this.$confirm('是否确认删除已选照片?', '提示')
        await photoDel({
          ids: this.checked.join(',')
        })
        this.$message.success('删除成功')
        this.editing = false
        this.FetchList()
      } catch (error) {}
    }
  }
}
</script>
<style lang="less" scoped>
.img-container{
  display: inline-flex;
  margin-right: 20px;
  margin-top: 20px;
  flex-direction: column;
  text-align: center;
  position: relative;
  cursor: move;
  >.name{
    width: 150px;
    height: 30px;
    line-height: 30px;
    text-align: center;
    margin-top: 10px;
    color: rgba(0, 0, 0, .65);
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: pre;
    font-size: 14px;
  }
  >.nameinput{
    width: 150px;
    margin-top: 10px;
  }
}
.ctrl-bar,
.ctrl-bar-view{
  background-color: rgba(0, 0, 0, .45);
  height: 30px;
  position: absolute;
  top: 0;
  width: 100%;
  z-index: 1;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 15px;
}
.ctrl-bar-view{
  opacity: 0;
  visibility: hidden;
  transition: all .3s;
}
.img-container:hover{
  .ctrl-bar-view{
    opacity: 1;
    visibility: visible;
  }
}
.el-icon-view,
.el-icon-picture-outline-round{
  font-size: 14px;
  color: #fff;
  cursor: pointer;
  &.active{
    color: #14928A;
  }
}
.switch{
  position: absolute;
  top: 10px;
  right: 10px;
  z-index: 1;
}
.img{
  width: 150px;
  height: 150px;
  border-radius: 3px;
}
.alert{
  margin-top: 20px;
}
.btn{
  padding: 0;
}
</style>
