<template>
  <!-- 工位地图 -->
  <div class="seatMap" ref="seatMap">
    <Row align="middle" style="margin-bottom:10px" type="flex">
      <span style="display:inline-block;width:90px">工位地图名称：</span>
      <Col span="4">
        <Input
          :maxlength="20"
          :readonly="openState<1"
          @on-blur="disableDeleteBlock=false"
          @on-focus="disableDeleteBlock=true"
          placeholder="请输入"
          v-model="seatName"
        ></Input>
      </Col>

      <span style="display:inline-block;width:70px;margin-left:10px">所属中心：</span>
      <Col span="4">
        <Select
          :disabled="openState<1"
          @on-change="changeCenter"
          placeholder="所属中心"
          style="margin-left: 2px; width:180px"
          v-if="openState>0"
          v-model="centerSelect"
        >
          <Option
            :key="index"
            :value="item.wmSiteId"
            v-for="(item,index) in optionsForCenter"
          >{{item.wmName}}</Option>
        </Select>
        <Input
          :maxlength="20"
          :readonly="openState<1"
          :value="mapInfo.map.wmName"
          placeholder="请输入"
          v-if="openState<1"
        ></Input>
      </Col>

      <DatePicker
        :clearable="false"
        :editable="false"
        placement="bottom-start"
        style="width:200px;margin-left:10px;margin-right:10px"
        type="date"
        v-model="searchTime"
      ></DatePicker>
      <Button :loading="isSearching" @click="searchInfo()" type="primary">查询</Button>
    </Row>
    <Row align="middle" style="margin-bottom:10px" type="flex">
      <span style="display:inline-block;width:90px">专线颜色：</span>
      <div
        :key="index"
        label
        style="margin-right:10px;display:inline-block;vertical-align:middle"
        v-for="(item,index) in lineOptions"
      >
        <span>{{item.name}}：</span>
        <ColorPicker
          :disabled="openState<1"
          class="seat-info"
          recommend
          v-model="colorCurrentMap[item.id]"
        />
      </div>
    </Row>
    <Row align="middle" style="margin-bottom:10px" v-show="openState>0">
      <span style="display:inline-block;width:90px">工位地图：</span>

      <Button :disabled="isAddBlock " @click="addBlcok" style="margin-right:10px" type="primary">+</Button>
      <Button :disabled="selectBlockIndex<0 " @click="minusBlcok" type="primary">-</Button>

      <div :key="index" class="demo-upload-list" v-for="(item,index) in uploadList">
        <template v-if="item.status === 'finished'">
          <img :src="item.url" />
          <div class="demo-upload-list-cover">
            <Icon @click.native="handleRemove()" type="ios-trash-outline"></Icon>
          </div>
        </template>
        <template v-else>
          <Progress :percent="item.percentage" hide-info v-if="item.showProgress"></Progress>
        </template>
      </div>
      <Upload
        :action="getUploadUrl"
        :before-upload="handleBeforeUpload"
        :format="['jpg','jpeg','png','JPG','JPEG','PNG']"
        :max-size="2048"
        :on-error="cancelSpin"
        :on-exceeded-size="handleMaxSize"
        :on-format-error="handleFormatError"
        :on-success="handleSuccess"
        :show-upload-list="false"
        ref="upload"
        style="display: inline-block;width:36px;vertical-align: middle;margin-left: 10px;"
        type="drag"
      >
        <div style="width: 36px;height:32px;line-height: 32px;">
          <Icon size="20" type="ios-camera"></Icon>
        </div>
      </Upload>
    </Row>
    <div class="paintArea">
      <div
        :style="{cursor:handStyle,background:imgSrc}"
        @mousedown="confrimPos"
        @mousemove="blockMouseMove"
        @mouseup="canvasMouseUp"
        id="galaxy-menu"
      >
        <Poptip
          :key="index"
          :style="{left:item.pointLeft-seatSize/2+'px',top:item.pointRight-seatSize/2+'px',position:'absolute'}"
          :trigger="item.deleted==='1'?'none':'hover'"
          content="111"
          placement="top"
          popper-class="popWin"
          title="工位信息"
          v-for="(item,index) in blockArray"
        >
          <div slot="content">
            <Row :key="index" v-for="(subItem,index) in item.map.stationList">
              <span>{{ getWorkTime(subItem) }}</span>
            </Row>
          </div>
          <div
            :ref="'block'+index"
            :style="{
          pointerEvents:preventEvent,background:selectBlockIndex==index?'black':colorCurrentMap[item.pointActivityId],
          width:seatSize+'px',height:seatSize+'px',lineHeight:'30px'}"
            @mousedown="blockClick(item,index,$event)"
            class="moveBlock"
          >
            <div>{{item.pointName?item.pointName:'请设置'}}</div>
            <div
              v-if="item.map && item.map.stationList && item.map.stationList.length>0 && (!item.deleted || item.deleted==='0')"
            >{{ getName(item.map.stationList)}}</div>
            <div v-else-if="item.deleted==='0'">未设置</div>

            <Icon size="40" type="ios-lock" v-if="item.deleted && item.deleted ==='1'" />
          </div>
        </Poptip>
      </div>
    </div>
    <Spin fix size="large" v-if="isLoading"></Spin>

    <Modal
      :footer-hide="false"
      :mask-closable="false"
      @on-ok="handOk"
      ok-text="保存"
      title="工位信息编辑"
      v-model="isShowSeatInfoEdit"
    >
      <Row align="middle" type="flex">
        <Col class-name="align-left" span="4">工位编号:</Col>
        <Col class-name="align-left" span="10">
          <Input
            :disabled="false"
            :maxlength="20"
            @on-blur="checkNum"
            placeholder="工位编号"
            style="width:200px;margin-right:10px"
            v-model="stationNo"
          ></Input>
        </Col>
      </Row>
      <br />
      <Row align="middle" type="flex">
        <Col class-name="align-left" span="4">所属专线:</Col>
        <Col class-name="align-left" span="10">
          <Select placeholder="所属专线" style="margin-left: 2px; width:200px" v-model="lineIdForEdit">
            <Option
              :key="index"
              :value="item.id"
              style="width:200px;margin-right:10px"
              v-for="(item,index) in lineOptions"
            >{{item.name}}</Option>
          </Select>
        </Col>
      </Row>
    </Modal>
  </div>
</template>

<script>
import COMMEN_CONFIG from '@conf'
import FILE_API from '@api/sys/file'
import WmSitesAPI from '@api/common/wmSites'
import WfmStationAPI from '@api/common/wfmStation'
import { format } from 'date-fns'
import store from '@/store'

export default {
  name: 'seat-map',
  data () {
    return {
      isSearching: false,
      maxNum: 0,
      editIndex: -1,
      stationNo: '',
      lineIdForEdit: 0,
      isShowSeatInfoEdit: false,
      disableDeleteBlock: false,
      radioSelect: 0,
      seatName: '',
      optionsForCenter: [],
      centerSelect: '',
      selectedId: '',
      isLoading: false,
      timeCount: null,
      seatSize: 0,
      imgSrc: '',
      imageId: '',
      preventEvent: 'auto',
      handStyle: 'default',
      canvasWidth: 1170,
      canvasHeight: 680,
      cellWidth: 0,
      cellHeight: 0,
      blockArray: [],
      uploadList: [],
      clickPos: {
        left: 0,
        top: 0
      },
      colorCurrentMap: {},
      colorSelectedMap: {},
      isAddBlock: false,
      isMouseDown: false,
      selectBlock: null,
      selectBlockIndex: -1,
      total: 0,
      lineOptions: [],
      searchTime: ''
    }
  },
  props: {
    isShowModal: {
      type: Boolean,
      default: false
    },
    openState: {
      type: Number,
      default: 0
    },
    mapInfo: {
      type: Object,
      default: null
    }
  },
  watch: {},
  computed: {
    getUploadUrl () {
      const url = FILE_API.upload()
      return url
    },
    getModalState () {
      return this.openState
    }
  },
  mounted () {
    const $this = this
    this.searchTime = format(
      new Date(store.state.app.systemTime),
      this.$config.DATE_FORMAT
    )
    document.addEventListener('keydown', e => {
      if (this.disableDeleteBlock) {
        return
      }
      if (e.keyCode === 8) {
        $this.minusBlcok()
      }
      if (e.keyCode === 13) {
        $this.addBlcok()
      }

      if ($this.selectBlockIndex > -1) {
        let tmpLeft = $this.selectBlock.pointLeft
        let tmpTop = $this.selectBlock.pointRight
        if (e.keyCode === 38) {
          // up
          tmpTop -= 1
        } else if (e.keyCode === 40) {
          // down
          tmpTop += 1
        } else if (e.keyCode === 37) {
          // left
          tmpLeft -= 1
        } else if (e.keyCode === 39) {
          // right
          tmpLeft += 1
        }

        if ($this.canMoveToNextPos(tmpLeft, tmpTop, $this.selectBlock.id)) {
          $this.selectBlock.pointLeft = tmpLeft
          $this.selectBlock.pointRight = tmpTop
        }
        e.preventDefault()
      }
    })

    this.seatSize = COMMEN_CONFIG.WORK_MAP_PARAMS.SEAT_SIZE

    // 读取数据并加载
    this.initData()

    // this.timeCount = setInterval(() => {
    //   this.saveData()
    // }, 60000 * 5)

    this.blockArray = []
    this.optionsForCenter = []
    WmSitesAPI.listOwer()
      .then(({ data }) => {
        if (data.status === 'success') {
          if (data.data && data.data.length > 0) {
            this.optionsForCenter = data.data
            if (this.mapInfo && this.mapInfo.stationId) {
              this.searchTime = format(
                this.searchTime,
                this.$config.DATE_FORMAT
              )

              this.getSeatMapDetail(
                this.mapInfo.stationId,
                this.mapInfo.stationSiteId,
                this.searchTime
              )
            } else {
              this.centerSelect = data.data[0].wmSiteId
              this.getSeatMapDetail(
                null,
                data.data[0].wmSiteId,
                this.searchTime
              )
            }
          }
        }
      })
      .catch(err => {
        console.error('err:', err)
      })
  },
  created () {
    this.isLoading = true
  },
  destroyed () {
    this.blockArray = []
    // clearInterval(this.timeCount)
    // document.removeEventListener('keydown')
  },
  methods: {
    getName (list) {
      if (list) {
        if (list.length === 0) {
          return '未设置'
        }
        let name = list[0].userName

        if (!name) {
          name = '未设置'
        } else {
          if (name.length > 3) {
            name = name.substring(0, 3) + '...'
          }
        }
        if (list.lenght > 1 && name.lenght < 4) {
          name += '...'
        }
        return name
      } else {
        return '未设置'
      }
    },
    getWorkTime (subItem) {
      if (!subItem) {
        return ''
      }
      return (
        subItem.userName +
        ': ' +
        subItem.wmShiftName +
        '(' +
        subItem.wmStartDatetime +
        ' ~ ' +
        subItem.wmEndDatetime +
        ')'
      )
    },
    searchInfo () {
      this.isSearching = true
      this.searchTime = format(this.searchTime, this.$config.DATE_FORMAT)
      if (this.mapInfo && this.mapInfo.stationId) {
        this.getSeatMapDetail(
          this.mapInfo.stationId,
          this.mapInfo.stationSiteId,
          this.searchTime
        )
      }
    },
    checkNum () {
      if (this.stationNo > this.maxNum) {
        this.stationNo = this.maxNum
      }
      for (let i in this.blockArray) {
        if (this.stationNo === this.blockArray[i].pointName) {
          this.$Message.destroy()
          this.$Message.warning('已有相同编号:' + this.stationNo)
          break
        }
      }
    },
    handOk () {
      this.$set(this.blockArray[this.editIndex], 'pointName', this.stationNo)
      this.$set(
        this.blockArray[this.editIndex],
        'pointActivityId',
        this.lineIdForEdit
      )
    },
    showSeatModal (seatNo, stationId, index) {
      this.isShowSeatInfoEdit = true
      this.editIndex = index
      if (!seatNo) {
        this.stationNo = ''
      } else {
        this.stationNo = seatNo
      }
      if (!stationId) {
        stationId = 0
      } else if (stationId > 0) {
        this.lineIdForEdit = stationId
      }
    },
    initData () {
      this.lineOptions = []
      this.blockArray = []
      if (this.mapInfo) {
        this.seatName = this.mapInfo.stationName
        if (this.mapInfo.stationSiteId) {
          this.centerSelect = this.mapInfo.stationSiteId
        } else {
          this.centerSelect = null
        }
      }
    },
    getColorsForline (sitId) {
      WfmStationAPI.listColor({ sitId })
        .then(({ data }) => {
          if (data.status === 'success') {
            for (let key in data.data) {
              let tmp = data.data[key]
              this.colorSelectedMap[tmp.wmActivityId] = tmp.colorVal
            }
            this.getLines(data.data)
          }
        })
        .catch(() => {
          this.isLoading = false
        })
    },
    getSeatMapDetail (stationId, stationSiteId, searchTime) {
      if (!stationId) {
        this.getColorsForline(stationSiteId)
        this.isLoading = false
        return
      }
      WfmStationAPI.view({ stationId, searchTime })
        .then(({ data }) => {
          if (data.status === 'success') {
            this.isSearching = false
            this.isLoading = false
            if (data.data) {
              if (data.data.stationImageId) {
                this.imageId = data.data.stationImageId
              }
              if (data.data.poinList) {
                this.blockArray = data.data.poinList
                for (let i in this.blockArray) {
                  let tmp = parseInt(this.blockArray[i].pointName)
                  this.maxNum = this.maxNum < tmp ? tmp : this.maxNum
                }
              }
              for (let key in data.data.map.colorList) {
                let tmp = data.data.map.colorList[key]
                this.colorSelectedMap[tmp.wmActivityId] = tmp.colorVal
              }
            }
            this.getLines(data.data.map.colorList)
            if (this.imageId) {
              this.imgSrc =
                'url(http:' + FILE_API.show(this.imageId) + ') no-repeat' // ----读取对应图片id
            } else {
              this.imgSrc = ''
            }
          }
        })
        .catch(() => {
          this.isLoading = false
          this.isSearching = false
        })
    },
    changeCenter () {
      this.radioSelect = 0
      this.getColorsForline(this.centerSelect)
    },
    getLines (colorList) {
      this.lineOptions = []
      for (let key in colorList) {
        let id = colorList[key].wmActivityId
        if (!id) {
          id = colorList[key].wmActivityId
        }
        if (id) {
          let obj = {}
          obj.id = id
          obj.name =
            colorList[key].actWmName === undefined
              ? colorList[key].wmName
              : colorList[key].actWmName
          this.lineOptions.push(obj)
        }
        if (this.colorSelectedMap[id]) {
          this.$set(this.colorCurrentMap, id, this.colorSelectedMap[id])
        } else {
          this.$set(this.colorCurrentMap, id, 'red')
        }
      }
    },
    addBlcok (e) {
      if (this.isShowSeatInfoEdit) {
        return
      }
      this.isAddBlock = true
    },
    minusBlcok () {
      if (this.selectBlockIndex < 0) {
        return
      }
      if (this.isShowSeatInfoEdit) {
        return
      }
      this.maxNum--
      this.blockArray.splice(this.selectBlockIndex, 1)
      this.selectBlock = null
      this.selectBlockIndex = -1
    },
    confrimPos (e) {
      let x = e.layerX
      let y = e.layerY
      this.selectBlockIndex = -1
      this.selectBlock = null
      if (this.isAddBlock) {
        this.maxNum++
        let tmp = {
          pointName: this.maxNum,
          pointLeft: x,
          pointRight: y,
          pointActivityId: this.lineOptions[this.radioSelect].id
        }
        this.blockArray.push(tmp)
        this.isAddBlock = false
        this.total++
      }
    },
    blockClick (item, index, e) {
      if (this.openState < 1) {
        return
      }
      if (e.button === 0) {
        // 左键
        this.clickPos.pointLeft = e.clientX
        this.clickPos.pointRight = e.clientY
        this.isMouseDown = true
        this.selectBlock = item
        this.selectBlockIndex = index
        e.stopPropagation()
        this.handStyle = 'move'
        this.preventEvent = 'none'
        this.blockColor = 'green'
      }
    },
    blockMouseMove (e) {
      if (this.isMouseDown) {
        let tmpLeft =
          this.selectBlock.pointLeft + e.clientX - this.clickPos.pointLeft
        let tmpTop =
          this.selectBlock.pointRight + e.clientY - this.clickPos.pointRight

        if (this.canMoveToNextPos(tmpLeft, tmpTop, this.selectBlock.id)) {
          this.selectBlock.pointLeft = tmpLeft
          this.selectBlock.pointRight = tmpTop
        }

        this.clickPos.pointLeft = e.clientX
        this.clickPos.pointRight = e.clientY
      }
    },
    canMoveToNextPos (centerX, centerY, id) {
      const array = this.blockArray
      for (let key in array) {
        if (id === array[key].id) {
          continue
        }
        let xGap = Math.abs(array[key].pointLeft - centerX)
        let yGap = Math.abs(array[key].pointRight - centerY)
        if (xGap > this.seatSize || yGap > this.seatSize) {
          continue
        } else {
          return false
        }
      }
      return true
    },
    judeIsCross (i, j, centerX, centerY) {
      // 判断两个div是否有交集
      console.log(centerX, centerY)
      const array = this.blockArea[i][j].array
      for (let key in array) {
        let xGap = Math.abs(array[key].pointLeft - centerX)
        let yGap = Math.abs(array[key].pointRight - centerY)
        if (xGap > this.seatSize || yGap > this.seatSize) {
          return false
        } else {
          return true
        }
      }
      return false
    },
    // blockMouseup (e) {
    //   this.selectBlock = null
    //   e.stopPropagation()
    // },
    canvasMouseUp (e) {
      this.blockColor = 'red'
      this.preventEvent = 'auto'
      this.isMouseDown = false
      this.handStyle = 'default'
    },
    // saveData () {
    //   this.$Message.destroy()
    //   this.$Message.success('数据已保存')
    //   // this.blockArray-------------------------保存该数组
    // },

    // -------------------------上传相关--------------------------------
    cancelSpin () {
      this.isLoading = false
    },
    handleRemove () {
      this.$refs.upload.fileList.splice(0, 1)
    },
    handleSuccess (res, file) {
      this.isLoading = false
      this.imageId = res.data[0].uuid
      this.imgSrc = 'url(http:' + FILE_API.show(this.imageId) + ') no-repeat'
    },
    handleFormatError (file) {
      this.isLoading = false
      this.$Notice.warning({
        title: '文件格式错误',
        desc: file.name + ' 的文件格式只能为 jpg ,jpeg 或 png.'
      })
    },
    handleMaxSize (file) {
      this.isLoading = false
      this.$Notice.warning({
        title: '文件过大',
        desc: 'File  ' + file.name + ' 图片大小不能超过 2M.'
      })
    },
    async handleBeforeUpload (file) {
      if (!new RegExp('.(jpg|jpeg|png)$').test(file.name)) {
        this.$Message.warning('请上传jpg或png格式文件')
        this.isLoading = false
        return false
      }
      if (this.$refs.upload.fileList.length > 0) {
        this.$refs.upload.fileList.splice(0, 1)
      }

      this.isLoading = true
      const promise = await this.checkImageWH(
        file,
        COMMEN_CONFIG.WORK_MAP_PARAMS.IMAGE_WIDTH
      )
      this.isLoading = false
      return promise
    },
    checkImageWH (file, width) {
      // 需要修改配置文件（现在最大宽度设置为100px）
      let self = this
      return new Promise(function (resolve, reject) {
        let filereader = new FileReader()
        filereader.readAsDataURL(file)
        filereader.onload = e => {
          let src = e.target.result
          const image = new Image()
          image.src = src
          image.onload = function () {
            if (width && this.width > width) {
              self.$Modal.confirm({
                title: '图片超限',
                content:
                  '<p style="color:green">图片宽度超过了限制(' +
                  COMMEN_CONFIG.WORK_MAP_PARAMS.IMAGE_WIDTH +
                  'px),是否继续上传</p>',
                onOk: () => {
                  resolve(true)
                },
                onCancel: () => {
                  resolve(false)
                }
              })
            } else {
              resolve(true)
            }
          }
        }
      })
    }
  }
}
</script>

<style lang="less" scoped>
#galaxy-menu {
  position: relative;
  width: 100%;
  height: 980px;
  background: gainsboro;
  border: 1px dashed grey;
  background-attachment: fixed;

  .moveBlock {
    border-radius: 15px;
    // position: absolute;
    text-align: center;
    color: white;
    font-size: 18px;
  }
}

.seatMap {
  .paintArea {
    width: 1170px;
    height: 680px;
    overflow-y: auto;
  }
  .mapImage {
    width: 100%;
    height: 100%;
  }
  .demo-upload-list {
    display: inline-block;
    width: 60px;
    height: 60px;
    text-align: center;
    line-height: 60px;
    border: 1px solid transparent;
    border-radius: 4px;
    overflow: hidden;
    background: #fff;
    position: relative;
    box-shadow: 0 1px 1px rgba(0, 0, 0, 0.2);
    margin-right: 4px;
  }
  .demo-upload-list img {
    width: 100%;
    height: 100%;
  }
  .demo-upload-list-cover {
    display: none;
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    background: rgba(0, 0, 0, 0.6);
  }
  .demo-upload-list:hover .demo-upload-list-cover {
    display: block;
  }
  .demo-upload-list-cover i {
    color: #fff;
    font-size: 20px;
    cursor: pointer;
    margin: 0 2px;
  }
  .poptipExplain {
    width: 200px;
    white-space: normal;
    word-break: break-all;
    line-height: 25px;
    font-size: 14px;
    // position: absolute;
  }
}
</style>
<style lang="less">
.ivu-color-picker-transfer {
  width: auto !important;
}
.ivu-poptip-title {
  .ivu-poptip-title-inner {
    color: #b50029;
    //color: #17508A;
  }
}
</style>
