<template>
  <div class="app-container">
    <div class="venue-header">
      <h4><i class="iconfont icon-shujia" />书架列表</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-select v-model="selectFloorVal" size="small" placeholder="楼层" class="filter-item" style="width: 80px" value-key="id" @change="changeBeforeFloor">
              <el-option v-for="(item,index) in floorOptions" :key="index" :label="item.floorName" :value="item" />
            </el-select>
            <el-select v-model="selectRegionVal" size="small" placeholder="区域" class="filter-item" style="width: 140px" value-key="id" @change="changeBeforeRegion">
              <el-option v-for="(item,index) in regionOptions" :key="index" :label="item.regionName" :value="item" />
            </el-select>
            <!-- <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>
          </crudOperation>
        </div>
        <div>
          <div class="double-click-btn"><i class="iconfont icon-zhuyi-lan" /><span>双击列表数据查看对应架位</span></div>
          <el-table
            ref="table"
            v-loading="crud.loading"
            :data="crud.data"
            style="width: 100%;"
            height="507"
            @selection-change="selectionChangeHandler"
            @row-dblclick="onRowDblclick"
            @row-click="clickRowHandler"
          >
            <el-table-column type="selection" align="center" width="55" />
            <!-- <el-table-column type="index" label="排序" /> -->
            <el-table-column prop="shelfName" label="书架名称" />
            <el-table-column prop="shelfShelf" label="书架规格">
              <template slot-scope="scope">
                <span>{{ scope.row.shelfFloor + ' X ' + scope.row.shelfShelf }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="rowType" label="单/双面">
              <template slot-scope="scope">
                <span>{{ scope.row.rowType === 1 ? '单面' :'双面' }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="floorName" label="所属楼层" />
            <el-table-column prop="regionName" label="所属区域" min-width="100" />
            <el-table-column prop="signPoint" label="标注">
              <template slot-scope="scope">
                <span :class="['row-state', scope.row.signPoint ? 'end-state' : 'cancel-state' ]">{{ scope.row.signPoint ? '已标注': '未标注' }}</span>
              </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" />
            <el-button size="mini" class="venue-mark" :disabled="crud.selections.length !== 1" @click="handleMark">
              <i class="el-icon-edit" />
              书架标注
            </el-button>
          </ul>
          <div class="venue-preview">
            <!-- <img :src="imageUrl" :onerror="defaultImg" alt=""> -->
            <div v-show="currentMarkData && currentMarkData.signPoint">
              <canvas id="canvasPreview" :width="width" :height="height" />
            </div>
            <img v-if="currentMarkData && !currentMarkData.signPoint" :src="imageUrl" :onerror="defaultImg" alt="">
            <img v-if="!currentMarkData" :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" inline size="small" label-width="90px">
          <el-form-item label="所属楼层" prop="floorName">
            <el-input v-model="form.floorName" disabled />
          </el-form-item>
          <el-form-item label="所属区域" prop="regionName">
            <el-input v-model="form.regionName" disabled />
          </el-form-item>
          <el-row>
            <el-form-item label="单/双排" prop="rowType">
              <el-radio-group v-model="form.rowType" v-removeAriaHidden size="mini">
                <el-radio :label="1">单排</el-radio>
                <el-radio :label="2">双排</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item v-if="form.rowType===1" label="A/B面" prop="toward">
              <el-select v-model="form.toward" placeholder="请选择" style="width: 225px;">
                <el-option
                  v-for="(item,index) in abOptions"
                  :key="index"
                  :label="item.name"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-row>
          <el-row>
            <el-form-item label="书架排号" prop="shelfRow">
              <el-input v-model="form.shelfRow" @blur="formatShelfRow" />
            </el-form-item>
            <el-form-item label="书架名称" prop="shelfName">
              <el-input v-model="computedShelfName" disabled />
            </el-form-item>
          </el-row>
          <el-form-item label="书架规格" prop="rackSpecs">
            <el-input-number v-model.number="form.shelfFloor" :min="1" :max="999" controls-position="right" style="width:80px;" />
            <span style="font-size: 12px;">层</span>
            <span style="padding:0 2px;">✕</span>
            <el-input-number v-model.number="form.shelfShelf" :min="1" :max="999" controls-position="right" style="width: 80px;" />
            <span style="font-size: 12px;">架</span>
          </el-form-item>
          <el-form-item label="架起始标" prop="startShelf">
            <el-input-number v-model.number="form.startShelf" :min="1" :max="999" controls-position="right" />
          </el-form-item>
          <el-row>
            <el-form-item label="架号顺序" prop="shelfType">
              <el-select v-model="form.shelfType" placeholder="请选择" style="width: 586px;">
                <el-option
                  v-for="(item,index) in rackOrderOptions"
                  :key="index"
                  :label="item.name"
                  :value="item.key"
                />
              </el-select>
            </el-form-item>
          </el-row>
          <el-row>
            <el-form-item label="层号顺序" prop="floorType">
              <el-select v-model="form.floorType" placeholder="请选择" style="width: 586px;">
                <el-option
                  v-for="(item,index) in layerSeqOptions"
                  :key="index"
                  :label="item.name"
                  :value="item.key"
                />
              </el-select>
            </el-form-item>
          </el-row>
          <el-form-item label="倒架规则" prop="shelfRule">
            <el-radio-group v-model="form.shelfRule" v-removeAriaHidden size="mini">
              <el-radio :label="1">有序</el-radio>
              <el-radio :label="2">无序</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="错架判断" prop="shelfErrorJudge">
            <el-radio-group v-model="form.shelfErrorJudge" v-removeAriaHidden size="mini">
              <el-radio :label="2">格子</el-radio>
              <el-radio :label="1">书架</el-radio>
            </el-radio-group>
          </el-form-item>
        </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 class="mark-dialog" :close-on-click-modal="false" :append-to-body="true" :title="titleMark" :visible.sync="markVisible" :before-close="handleCloseDialog">
      <span class="dialog-right-top" />
      <span class="dialog-left-bottom" />
      <div class="setting-dialog">
        <MarkCover ref="markRefs" :is-book-shelf="true" :current-mark-data="currentMarkData" :image-url="imageUrl" @handleCloseDialog="handleCloseDialog" />
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { FetchLibraryFloorListAll } from '@/api/floor/index'
import { FetchInitLibraryRegionList } from '@/api/area/index'
import crudShelf from '@/api/shelf/index'
import CRUD, { presenter, header, form, crud } from '@crud/crud'
import crudOperation from '@crud/CRUD.operation'
import pagination from '@crud/Pagination'
import { mapGetters } from 'vuex'
import defaultImg from '@/assets/images/system/default-img.jpg'
import MarkCover from '@/views/components/mark.vue'
import { fabric } from 'fabric'

const defaultForm = { id: null, floorName: null, floorId: null, regionName: null, rowType: 1, toward: 1, shelfRow: '', shelfName: '', shelfShelf: null, shelfFloor: null, startShelf: null, shelfType: 1, floorType: 1, shelfRule: 1, shelfErrorJudge: 2, signPoint: '' }
export default {
  name: 'Bookshelf',
  components: { crudOperation, pagination, MarkCover },
  cruds() {
    return CRUD({ title: '书架', idField: 'shelfId', url: 'api/bookShelf/initBookShelfList', crudMethod: { ...crudShelf }, sort: [], optShow: {
      add: true,
      edit: true,
      del: false,
      download: false,
      group: false,
      reset: false
    },
    queryOnPresenterCreated: false
    })
  },
  mixins: [presenter(), header(), form(defaultForm), crud()],
  data() {
    return {
      permission: {
        add: ['admin', 'floor:add'],
        edit: ['admin', 'floor:edit'],
        del: ['admin', 'floor:del']
      },
      floorOptions: [],
      regionOptions: [],
      selectFloorVal: null,
      selectRegionVal: null,
      abOptions: [
        { value: 1, name: 'A面' },
        { value: 2, name: 'B面' }
      ],
      rackOrderOptions: [
        { key: 1, name: '始终最左边为第1架（S型排架）' },
        { key: 2, name: 'A面最左为第1架（B面最左为最后1架）' },
        { key: 3, name: 'B面最左为第1架（A面最左为最后1架）' }
      ],
      layerSeqOptions: [
        { key: 1, name: '最顶层为第一层（从上至下）' },
        { key: 2, name: '最底层为第一层（从下至上）' }
      ],
      rules: {
        floorName: [
          { required: true, message: '所属楼层不可为空', trigger: 'blur' }
        ],
        regionName: [
          { required: true, message: '所属区域不可为空', trigger: 'blur' }
        ],
        rowType: [
          { required: true, message: '请选择单双排', trigger: 'change' }
        ],
        shelfRow: [
          { required: true, message: '书架排号不可为空', trigger: 'blur' }
        ],
        shelfName: [
          { validator: this.validateShelfName, trigger: 'blur' }
        ],
        rackSpecs: [
          { validator: this.validateRackSpecs, trigger: 'blur' }
        ],
        startShelf: [
          { required: true, message: '架起始标不可为空', trigger: 'blur' }
        ],
        shelfType: [
          { required: true, message: '请选择架号顺序', trigger: 'change' }
        ],
        floorType: [
          { required: true, message: '请选择层号顺序', trigger: 'change' }
        ],
        shelfRule: [
          { required: true, message: '请选择倒架规则', trigger: 'change' }
        ],
        shelfErrorJudge: [
          { required: true, message: '请选择错架判断', trigger: 'change' }
        ]
      },
      defaultImg: defaultImg,
      imageUrl: defaultImg,
      markVisible: false, // 区域标注
      titleMark: '书架标注',
      currentMarkData: null,

      canvasPreview: {},
      width: 900,
      height: 600,
      drawWidth: 2 // 笔触宽度
    }
  },
  computed: {
    ...mapGetters([
      'user',
      'baseApi'
    ]),
    computedShelfName() {
      const { shelfRow, rowType, toward } = this.form
      if (!shelfRow) {
        return ''
      }
      const baseName = `${shelfRow}排`
      if (rowType === 1 && toward !== null) {
        return `${baseName}${this.abOptions.find(option => option.value === toward).name}`
      } else if (rowType === 2) {
        return baseName
      }
      return ''
    }
  },
  watch: {
    computedShelfName(newVal) {
      this.form.shelfName = newVal
    },
    width() {
      this.canvasPreview.setWidth(this.width)
    },
    height() {
      this.canvasPreview.setHeight(this.height)
    }
  },
  beforeDestroy() {
    window.removeEventListener('beforeunload', this.clearLocalStorage)
  },
  created() {
    this.getLibraryFloorListAll()
  },
  mounted() {

  },
  methods: {
    clearLocalStorage() {
      const key = 'formArea'
      if (localStorage.getItem(key)) {
        localStorage.removeItem(key)
      }
    },
    formatShelfRow() {
      let value = this.form.shelfRow
      value = value.toString()
      if (value.length < 3) {
        value = value.padStart(3, '0')
      } else if (value.length > 3) {
        value = value.slice(0, 3)
      }
      this.form.shelfRow = value
    },
    validateShelfName(rule, value, callback) {
      if (this.form.shelfRow) {
        if (!value) {
          callback(new Error('书架名称不能为空'))
        } else {
          callback()
        }
      } else {
        callback()
      }
    },
    validateRackSpecs(rule, value, callback) {
    // 检查 shelfShelf 和 shelfFloor 是否为空
      if (!this.form.shelfShelf) {
        callback(new Error('请输入书架规格中书架架数'))
      } else if (!this.form.shelfFloor) {
        callback(new Error('请输入书架规格中书架层数'))
      } else {
        callback()
      }
    },
    [CRUD.HOOK.beforeRefresh]() {
      console.log(this.$route.query)
      if (this.$route.query.formArea) {
        const formArea = JSON.parse(localStorage.getItem('formArea'))
        if (formArea) {
          this.selectFloorVal = {
            id: formArea.floorId,
            floorMap: formArea.floorMap,
            floorName: formArea.floorName
          }
          this.selectRegionVal = formArea
          this.crud.query.floorId = this.selectFloorVal.id
          this.crud.query.regionId = this.selectRegionVal.id

          FetchInitLibraryRegionList({ 'floorId': this.selectFloorVal.id }).then(res => {
            this.regionOptions = res.content
          }).catch(() => {
          })
        }
      }
    },
    [CRUD.HOOK.afterRefresh](crud) {
      console.log(crud.data)
      if (this.selectRegionVal && this.selectRegionVal.regionMap) {
        this.imageUrl = this.baseApi + '/api/fileRelevant/getImg?imgType=1&imgId=' + this.selectRegionVal.regionMap
      } else {
        this.imageUrl = defaultImg
      }
    },
    // 新增与编辑前做的操作
    [CRUD.HOOK.afterToCU](crud, form) {
      console.log(form)
      console.log('crud.query.floorId', crud.query.floorId)
      console.log('selectFloorVal', this.selectFloorVal)
      console.log('crud.query.regionId', crud.query.regionId)
      console.log('selectRegionVal', this.selectRegionVal)
      form.floorId = this.selectFloorVal.id
      form.floorName = this.selectFloorVal.floorName
      form.regionId = this.selectRegionVal.id
      form.regionName = this.selectRegionVal.regionName
    },
    // 编辑前
    [CRUD.HOOK.beforeToEdit](crud, form) {
      const params = {
        'shelfId': this.crud.selections[0].shelfId
      }
      crudShelf.FetchBookShelfDetails(params).then(res => {
        form.id = res.id
        // 单/双排 1 单 2 双
        form.rowType = res.rowType
        // A/B面   1 A 2 B
        form.toward = res.toward
        // 书架排号
        form.shelfRow = res.shelfRow
        // 书架名称
        form.shelfName = res.shelfName
        // 书架规格  架
        form.shelfShelf = res.shelfShelf
        // 书架规格  层
        form.shelfFloor = res.shelfFloor
        // 架起始标
        form.startShelf = res.startShelf
        // 架号顺序
        form.shelfType = res.shelfType
        // 层号顺序
        form.floorType = res.floorType
        // 倒架规则  1 无序 2 有序
        form.shelfRule = res.shelfRule
        // 错架判断 1 书架 2 格子
        form.shelfErrorJudge = res.shelfErrorJudge
      }).catch(() => {
      })
    },
    // 提交前的验证
    [CRUD.HOOK.afterValidateCU](crud) {
      console.log(crud.form)
      delete crud.form.floorName
      delete crud.form.regionName
      return true
    },
    // 获取楼层数据
    getLibraryFloorListAll() {
      FetchLibraryFloorListAll().then(res => {
        this.floorOptions = res
        if (this.floorOptions.length > 0) {
          this.selectFloorVal = this.floorOptions[0]
          this.crud.query.floorId = this.selectFloorVal.id
          if (this.crud.query.floorId) {
            this.getInitLibraryRegionList(this.crud.query.floorId)
          }
        }
      }).catch(() => {
      })
    },
    getInitLibraryRegionList(val) {
      const params = {
        'floorId': val
      }
      FetchInitLibraryRegionList(params).then(res => {
        this.regionOptions = res.content
        if (this.regionOptions.length > 0) {
          this.selectRegionVal = this.regionOptions[0]
          this.crud.query.regionId = this.selectRegionVal.id
        } else {
          this.selectRegionVal = null
          this.crud.query.regionId = null
        }
        this.crud.toQuery()
      }).catch(() => {
      })
    },
    changeBeforeFloor(val) {
      if (this.$route.query.formArea) {
        localStorage.removeItem('formArea')
      }
      if (val) {
        this.selectFloorVal = val
        this.crud.query.floorId = val.id
        this.getInitLibraryRegionList(val.id)
      }
    },
    changeBeforeRegion(val) {
      if (this.$route.query.formArea) {
        localStorage.removeItem('formArea')
      }

      if (val) {
        this.selectRegionVal = val
        this.crud.query.regionId = val.id
        this.crud.toQuery()
      }
    },
    selectionChangeHandler(val) {
      this.crud.selections = val
      // 处理选择项为1且有签名点的情况
      if (this.crud.selections.length === 1 && this.crud.selections[0].signPoint) {
        this.currentMarkData = val[0]
        if (this.canvasPreview.lowerCanvasEl) {
          this.canvasPreview.clear()
          this.canvasPreview.dispose()
        }

        try {
          const drawinfo = JSON.parse(this.crud.selections[0].signPoint)
          this.initCanvasPreview(drawinfo)
        } catch (error) {
          console.error(error)
          this.resetImageUrl()
        }
      } else {
        // 处理选择项大于1或选择项为0的情况
        this.currentMarkData = null
        this.setImageUrlBasedOnRegionMap()
      }
    },
    setImageUrlBasedOnRegionMap() {
      if (this.selectRegionVal && this.selectRegionVal.regionMap) {
        this.imageUrl = `${this.baseApi}/api/fileRelevant/getImg?imgType=1&imgId=${this.selectRegionVal.regionMap}`
      } else {
        this.resetImageUrl()
      }
    },
    resetImageUrl() {
      this.imageUrl = this.defaultImg
    },
    async handleMark() {
      if (this.crud.selections.length === 1) {
        const selection = this.crud.selections[0]
        if (selection && this.selectRegionVal.regionMap) {
          this.markVisible = true
          this.currentMarkData = selection
          this.titleMark = this.currentMarkData.shelfName + ' - 书架标注'
          this.$nextTick(() => {
            this.$refs.markRefs.drawinfo = this.currentMarkData && this.currentMarkData.signPoint ? JSON.parse(this.currentMarkData.signPoint) : null
            this.$refs.markRefs.initCanvas()
          })
        } else {
          this.$message({ message: '请先上传当前区域图', type: 'error', offset: 8 })
        }
      } else {
        console.error('666')
      }
    },
    clickRowHandler(row) {
      this.$refs.table.clearSelection()
      this.$refs.table.toggleRowSelection(row)
    },
    onRowDblclick(row) {
      crudShelf.FetchBookShelfDetails({ 'shelfId': row.shelfId }).then(res => {
        this.$router.push({ path: '/bookshelf/bookshelfPosition', query: { 'floorName': row.floorName, 'regionName': row.regionName }})
        localStorage.setItem('bookShelfDetails', JSON.stringify(res))
      }).catch(() => {
      })
    },
    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.shelfId)
        })
        console.log(ids)
        crudShelf.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
      })
    },
    handleCloseDialog() {
      this.markVisible = false
      this.crud.refresh()
    },
    initCanvasPreview(drawinfo) {
      this.canvasPreview = new fabric.Canvas('canvasPreview', {
        skipTargetFind: false,
        selectable: false,
        selection: false
      })

      this.canvasPreview.selectionColor = 'rgba(0,0,0,0.05)'
      this.loadDrawPreview(drawinfo)
      this.canvasPreview.on('mouse:wheel', this.mouse)
    },
    // 鼠标滚轮放大缩小
    mouse(e) {
      if (undefined === e) return
      let zoom = (e.e.deltaY > 0 ? -0.1 : 0.1) + this.canvasPreview.getZoom()
      zoom = Math.max(0.8, zoom)
      // 最小为原来的1/10
      zoom = Math.min(3, zoom)
      // 最大是原来的3倍
      const zoomPoint = new fabric.Point(e.e.pageX, e.e.pageY)
      this.canvasPreview.zoomToPoint(zoomPoint, zoom)
    },
    // 回显详情信息
    loadDrawPreview(drawinfo) {
      const self = this
      const pointGroup = drawinfo.pointInfo
      const imgInfo = drawinfo.imgInfo
      imgInfo.src = self.imageUrl
      // 加载底图
      fabric.util.enlivenObjects([imgInfo], objects => {
        objects.forEach(o => {
          o.selectable = false
          o.hasControls = false
          o.centeredScaling = false
          self.canvasPreview.add(o)
        })
        // 处理多边形绘制回显操作
        pointGroup.forEach(async(item, index) => {
          if (item.pointInfo !== '') {
            const polygon = new fabric.Polygon(item.pointInfo, {
              name: item.name,
              stroke: 'rgba(196,43, 1, 1)',
              strokeWidth: self.drawWidth,
              fill: 'rgba(196,43, 1, 1)',
              opacity: 0.5,
              selectable: false,
              hasBorders: false,
              hasControls: false,
              originX: 'left', // 设置原点为左上角
              originY: 'top' // 设置原点为左上角
            })
            // polygon.index = index
            self.canvasPreview.add(polygon)

            polygon.on('mousedown', function(e) {
              console.log('Rect ' + (index + 1) + ' clicked', e)
              console.log('e.target.name', e.target.name)
            })

            polygon.on('mouseover', function(e) {
              console.log('e', e)
              console.log('e.target', e.target)
              console.log('e.target.name', e.target.name)
              this.set({ opacity: 0.8, hoverCursor: 'pointer' })
              self.canvasPreview.renderAll()
            })

            // 监听鼠标移出事件
            polygon.on('mouseout', function() {
              this.set({ opacity: 0.5 })
              self.canvasPreview.renderAll()
            })
          }
        })
      })
      self.canvasPreview.renderAll()
    }
  }
}
</script>

<style lang="scss" scoped>
.tab-content{
  min-height: calc(100vh - 232px) !important;
}
</style>
