<template>
  <div>
    <Modal
        id="assets-libs"
        class="img-lib"
        v-model="showLibs"
        title="素材库"
        width='1055px'
        @on-ok="ok"
        @on-cancel="cancel">
        <CheckboxGroup v-if="this.fileList.length" v-model="selected" @on-change="checkboxChange" class="assets-collection" >
          <item-card
          :class="['assets-collection-item', {'selected':is_selected(item)}]"
          v-for="item in fileList"
          :key="item.id"
          :fileData="item"
          @del_item="delImg">
          </item-card>
        </CheckboxGroup>
        <div v-else class="empty-libs">
          <Icon type="md-images" />
          <p>素材库内容目前还是空的。</p>
        </div>
        <div class="flexbox" slot="footer">
          <div class="pagination">
            <Page :page-size-opts="pageSizeOpts" :page-size="20" :total="total" show-sizer @on-page-size-change='changeSize' @on-change='changePage'/>
          </div>
          <div class="buttons">
            <Upload
            :action="uploadApi"
            :format="['jpg','jpeg','png']"
            :max-size="2048"
            :before-upload="handleUpload"
            :on-format-error="handleFormatError"
            :on-exceeded-size="handleMaxSize"
            :on-success="uploadSuccess"
            >
              <Button :loading="loadingStatus" size="large"><Icon type="ios-cloud-upload-outline" />&nbsp;&nbsp;上传图片&nbsp;</Button>
            </Upload>

            <Button type="primary" size="large" @click="ok">确定选择</Button>
          </div>
        </div>
    </Modal>
  </div>
</template>

<script>
import { GetImgList, DocsRecordDelete } from '@/api/data'
import ItemCard from './item-card.vue'
export default {
  components: {
    ItemCard
  },
  name: 'assets-libs',
  props: {
    // 可选，最大选择数量
    maxSelected: {
      type: Number,
      default: 1
    },
    uploadApi: {
      type: String,
      required: true
    }
  },
  data () {
    return {
      showLibs: false,
      total: 0,
      fileList: [],
      fileName: '', // 查询名字
      fileType: '', // 文件类型
      currentOrder: 'desc', // 升序降序
      page: 1, // 分页
      perpage: 20,
      orderType: '降序', // 下拉框默认,
      selected: [],
      pageSizeOpts: [20, 30, 40],
      loadingStatus: false,
      bindName: '' // 可传入绑定的字段，再emit事件时带出
    }
  },
  computed: {

  },
  methods: {
    is_selected (item) {
      let is_selected = this.selected.findIndex((value) => {
        return value === item.file_url
      })
      if (is_selected >= 0) {
        return true
      }
      return false
    },
    _initOption () { // 筛选条件初始化
      let file_name = this.fileName
      let file_type = this.fileType
      let order_type = this.currentOrder
      let page = this.page
      let perpage = this.perpage

      // post 参数为空的时候不加入
      let data = { order_type, page, perpage }
      if (file_name) {
        data.file_name = file_name
      }
      if (file_type) {
        data.file_name = file_type
      }

      return data
    },
    _reset () {
      let {
        fileName,
        fileType,
        currentOrder,
        page,
        perpage,
        orderType,
        bindName,
        selected
      } = this.$options.data()
      const originData = {
        fileName,
        fileType,
        currentOrder,
        page,
        perpage,
        orderType,
        bindName,
        selected
      }
      Object.assign(this.$data, originData)
      this.getImgs()
    },
    checkboxChange (value) {
      if (this.maxSelected === 1 && this.selected.length > 1) {
        this.selected.shift()
      } else if (this.selected.length > this.maxSelected) {
        this.selected.pop()
        this.$Message.info(`当前选项不得超过${this.maxSelected}个。`)
      }
    },
    show (bindName) {
      if (bindName) {
        this.bindName = bindName
      }
      this.showLibs = true
    },
    hide () {
      this._reset()
      this.showLibs = false
    },
    delImg (id) {
      DocsRecordDelete({ id }).then(res => {
        this.getImgs()
        this.$Message.success('图片已删除。')
      })
    },
    ok () {
      if (this.bindName) {
        let params = {
          bindName: this.bindName,
          value: this.selected
        }
        this.$emit('selected', params)
      } else {
        this.$emit('selected', this.selected)
      }
      this.hide()
    },
    cancel () {
      this._reset()
    },
    getImgs () {
      let data = this._initOption()
      const formdata = new FormData()
      // formdata.append('access_token', this.token)
      if (data.file_name) {
        formdata.append('file_name', data.file_name)
      }
      if (data.file_type) {
        formdata.append('sort', data.orderType)
      }
      formdata.append('by', data.order_type)
      formdata.append('page', this.page)
      formdata.append('perpage', this.perpage)
      GetImgList(formdata).then(res => {
        if (res.code === 0) {
          this.total = res.totalCount
          this.fileList = res.recordList
        } else {
          this.$Message.error(res.msg)
        }
      })
    },
    changeSize (size) {
      this.perpage = size
      this.getImgs()
    },
    changePage (page) {
      this.page = page
      this.getImgs()
    },
    handleUpload (file) {
      this.loadingStatus = true
    },
    handleFormatError (file) {
      this.$Message.warning({
        content: '请上传正确的图片格式文件。'
      })
      this.loadingStatus = false
    },
    handleMaxSize (file) {
      this.$Message.warning({
        content: '请将上传的图片控制在2M以内。'
      })
      this.loadingStatus = false
    },
    uploadSuccess (response, file, fileList) {
      this.loadingStatus = false
      this.getImgs()
    }
  },
  created () {
    this.getImgs()
  }

}
</script>

<style lang="less">
.selected {
  box-shadow: rgb(217, 233, 247) 1px 1px 6px 2px;
}
.assets-collection {
  display: flex;
  flex-wrap: wrap;
  justify-content: flex-start;
}
.ivu-modal{
  top: 20px;
  height: 80%;

}
.img-lib {
  .ivu-modal-body {
    overflow-y: scroll;
    height: 560px;
    padding-top: 0;
  }
  .ivu-modal-footer .flexbox {
    display: flex;
    justify-content: space-between;

    .buttons {
      display: flex;

      .ivu-btn-large {
        height: 36px;
        margin-left: 10px;
      }
    }
    .ivu-upload-list {
    display: none !important;
    }
  }
}
.empty-libs {
  width: 250px;
  margin: 0 auto;
  margin-top: 20px;
  font-size: 250px;
  color: #7485a9;
  p {
    font-size: 14px;
    font-weight: 600;
    text-align: center;
  }
}
</style>
