<template>
  <div class="app-container">
    <div class="venue-header">
      <h4><i class="iconfont icon-duolouceng" />楼层列表</h4>
      <p><i class="iconfont icon-gongsi" />{{ user.fonds.fondsName }}</p>
    </div>
    <div class="venue-content">
      <div class="venue-left">
        <div class="head-container">
          <div class="head-search">
            <!-- 搜索 -->
            <el-input v-model="query.search" clearable size="small" placeholder="输入关键字搜索" prefix-icon="el-icon-search" style="width: 200px;" class="filter-item" @clear="crud.toQuery" @keyup.enter.native="crud.toQuery" />
            <!-- <rrOperation /> -->
          </div>
          <crudOperation :permission="permission">
            <template v-slot:middle>
              <el-button slot="reference" size="mini" :loading="crud.delAllLoading" :disabled="crud.selections.length === 0" @click="toDelete(crud.selections)">
                <i class="iconfont icon-shanchu" />
                删除
              </el-button>
            </template>
            <template v-slot:right>
              <el-button :loading="crud.downloadLoading" size="mini" :disabled="crud.selections.length <= 1" @click="showSort">
                <i class="iconfont icon-paixu" />
                排序
              </el-button>
            </template>
          </crudOperation>
        </div>
        <div>
          <el-table
            ref="table"
            v-loading="crud.loading"
            :data="crud.data"
            style="width: 100%;"
            height="540"
            @selection-change="crud.selectionChangeHandler"
            @row-click="clickRowHandler"
          >
            <el-table-column type="selection" align="center" width="55" />
            <el-table-column type="index" label="排序" />
            <el-table-column prop="floorName" label="楼层名称" />
            <el-table-column prop="collectionFloor" label="区域" />
            <el-table-column prop="floorMap" label="地图">
              <template slot-scope="scope">
                <span :class="['row-state', scope.row.floorMap ? 'end-state' : 'cancel-state' ]">{{ scope.row.floorMap ? '已上传': '未上传' }}</span>
              </template>
            </el-table-column>
          <!-- <el-table-column prop="floorDescription" label="说明">
            <template slot-scope="scope">
              <div>{{ scope.row.floorDescription ? scope.row.floorDescription : '-' }}</div>
            </template>
          </el-table-column> -->
          <!-- <el-table-column prop="createTime" label="创建时间" min-width="180">
            <template slot-scope="scope">
              <div>{{ scope.row.createTime | parseTime }}</div>
            </template>
          </el-table-column> -->
          </el-table>
          <!--分页组件-->
          <pagination v-if="crud.data.length!==0" />
        </div>
      </div>
      <div class="venue-right">
        <div class="container-right tab-content">
          <span class="right-top-line" />
          <span class="left-bottom-line" />
          <ul class="tab-nav">
            <li class="active-tab-nav">楼层预览<i /></li>
            <!-- 最右侧装饰img -->
            <span class="tab-right-img" />
          </ul>
          <div class="venue-preview">
            <!-- <img src="~@/assets/images/system/default-img.jpg" alt=""> -->
            <img :src="imageUrl" :onerror="defaultImg" alt="">
          </div>
        </div>
      </div>
    </div>

    <!-- form -->
    <el-dialog append-to-body :close-on-click-modal="false" :modal-append-to-body="false" :before-close="crud.cancelCU" :visible="crud.status.cu > 0" :title="crud.status.title">
      <span class="dialog-right-top" />
      <span class="dialog-left-bottom" />
      <div class="setting-dialog">
        <el-form ref="form" :rules="rules" :model="form" size="small" label-width="100px">
          <el-form-item label="楼层名称" prop="floorName">
            <el-input v-model="form.floorName" style="width: 580px;" />
          </el-form-item>
          <el-form-item label="描述信息" prop="floorDescription">
            <el-input v-model="form.floorDescription" placeholder="请输入" type="textarea" rows="3" style="width: 580px;" />
          </el-form-item>
          <UploadCover :label-name="labelName" :form="form" @childCover="handleCover" />
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="text" @click="crud.cancelCU">取消</el-button>
          <el-button :loading="crud.status.cu === 2" type="primary" @click="crud.submitCU">保存</el-button>
        </div>
      </div>
    </el-dialog>

    <!-- 排序 -->
    <el-dialog :close-on-click-modal="false" :append-to-body="true" title="排序" :visible.sync="sortVisible" @opened="opened">
      <span class="dialog-right-top" />
      <span class="dialog-left-bottom" />
      <div class="setting-dialog">
        <i class="drag-tip">提示：请通过拖动鼠标来调整当前顺序</i>
        <el-table :data="sortTableData" class="file-sort" style="width: 100%;max-height: 70vh;" row-key="id">
          <el-table-column type="index" label="序号" width="100" align="center" />
          <el-table-column prop="floorName" label="楼层名称" />
        </el-table>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click.native="handleSort">保存</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import crudFloor from '@/api/floor/index'
import CRUD, { presenter, header, form, crud } from '@crud/crud'
import crudOperation from '@crud/CRUD.operation'
// import rrOperation from '@crud/RR.operation'
import pagination from '@crud/Pagination'
import UploadCover from '@/views/components/upload.vue'
import Sortable from 'sortablejs'
import { mapGetters } from 'vuex'
import defaultImg from '@/assets/images/system/default-img.jpg'

const defaultForm = { id: null, floorName: null, floorDescription: null, floorMap: null }
export default {
  name: 'Floor',
  components: { crudOperation, pagination, UploadCover },
  cruds() {
    return CRUD({ title: '楼层', url: 'api/libraryFloor/initLibraryFloorList', crudMethod: { ...crudFloor }, sort: [], optShow: {
      add: true,
      edit: true,
      del: false,
      download: false,
      group: false,
      reset: true
    }})
  },
  mixins: [presenter(), header(), form(defaultForm), crud()],
  data() {
    return {
      labelName: '楼层地图',
      permission: {
        add: ['admin', 'floor:add'],
        edit: ['admin', 'floor:edit'],
        del: ['admin', 'floor:del']
      },
      rules: {
        floorName: [
          { required: true, message: '所在楼层不可为空', trigger: 'blur' }
        ]
      },
      defaultImg: defaultImg,
      imageUrl: defaultImg,
      sortTableData: [], // 排序data
      sortVisible: false // 排序dialog
    }
  },
  computed: {
    ...mapGetters([
      'user',
      'baseApi'
    ])
  },
  methods: {
    [CRUD.HOOK.beforeRefresh]() {

    },
    [CRUD.HOOK.afterRefresh](crud) {
      console.log(crud.data)
      if (crud.data.length !== 0) {
        // this.clickRowHandler(crud.data[0])
        this.$nextTick(() => {
          this.$refs.table.toggleRowSelection(crud.data[0], true)
        })
      }
    },
    // 提交前的验证
    [CRUD.HOOK.afterValidateCU](crud) {
      console.log(crud.form)
      return true
    },
    handleCover(value) {
      console.log(value)
      this.form.floorMap = value
    },
    clickRowHandler(row) {
      this.$refs.table.clearSelection()
      this.$refs.table.toggleRowSelection(row)
      // http://192.168.99.67:12010/api/fileRelevant/getImg?imgId=f6d3ecea-0456-4429-ba77-1a4921d5c806
      if (row.floorMap) {
        this.imageUrl = this.baseApi + '/api/fileRelevant/getImg?imgId=' + row.floorMap
      } else {
        this.imageUrl = this.defaultImg
      }
    },
    toDelete(datas) {
      this.$confirm('此操作将删除当前所选楼层<span>你是否还要继续？</span>', '提示', {
        confirmButtonText: '继续',
        cancelButtonText: '取消',
        type: 'warning',
        dangerouslyUseHTMLString: true
      }).then(() => {
        this.crud.delAllLoading = true
        const ids = []
        datas.forEach(val => {
          ids.push(val.id)
        })
        console.log(ids)
        crudFloor.del(ids).then(res => {
          console.log(res)
          this.$message({ message: res, type: 'success', offset: 8 })
          this.crud.delAllLoading = false
          this.crud.refresh()
        }).catch(err => {
          this.crud.delAllLoading = false
          console.log(err)
        })
      }).catch(() => {
        this.crud.delAllLoading = false
      })
    },
    // 排序 -  行拖拽
    rowDrop(className, targetName) {
      // 此时找到的元素是要拖拽元素的父容器
      const tbody = document.querySelector('.' + className + ' .el-table__body-wrapper tbody')
      const that = this
      Sortable.create(tbody, {
        // 指定父元素下可被拖拽的子元素
        draggable: '.el-table__row',
        onEnd({ newIndex, oldIndex }) {
          if (newIndex === oldIndex) return
          that[targetName].splice(newIndex, 0, that[targetName].splice(oldIndex, 1)[0])
        }
      })
    },
    // 排序
    opened() {
      this.rowDrop('file-sort', 'sortTableData')
    },
    showSort() {
      this.sortVisible = true
      this.sortTableData = JSON.parse(JSON.stringify(this.crud.selections))
    },
    handleSort() {
      const data = this.sortTableData.map((value, index) => {
        return { id: value.id, isSequence: index + 1 }
      })
      this.sortTableData.forEach((item, index) => {
        item.isSequence = index + 1
      })
      crudFloor.sort(data).then(() => {
        this.sortVisible = false
        this.$message({ message: '保存成功', type: 'success', offset: 8 })
        this.crud.refresh()
      })
    }
  }
}
</script>

<style lang="scss" scoped>
</style>
