<template>
  <div class="main">
    <div class="opList">
      <div
        v-for="item in OpNameList"
        :style="{backgroundColor:item.工位号 == clickOpName ? '#2ed0ff' : '#fff'}"
        class="item"
        @click="searchOpPosition(item)">
        <div>{{ item.工位号 }}</div>
        <div>{{ opStatusList[item.状态代码] }}</div>
      </div>
    </div>
    <el-button v-if="!isDebug" @click="isDebug = true">调参模式</el-button>
    <el-button v-else @click="isDebug = false">调参模式</el-button>
    <div class="bottom">
      <div v-if="isDebug" class="table">
        <el-table
          v-loading="loading"
          :data="positionList"
          border
          element-loading-background="rgba(0, 0, 0, 0.2)"
          element-loading-spinner="el-icon-loading"
          element-loading-text="数据加载中"
          height="707"
          highlight-current-row
          size="mini"
          stripe
          style="width: 600px;margin-right: 50px"
          tooltip-effect="dark"
          @row-click="clickTableRow">
          <el-table-column align="center" label="序号" type="index" width="80"/>
          <el-table-column align="center" label="名称">
            <template slot-scope="scope">
              {{ scope.row.title }}
            </template>
          </el-table-column>
          <el-table-column align="center" label="变量值">
            <template slot-scope="scope">
              {{ scope.row.value }}
            </template>
          </el-table-column>
          <el-table-column align="center" label="是否显示">
            <template slot-scope="scope">
              <el-checkbox v-model="scope.row.isShow" :false-label="0" :true-label="1"/>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="canvas">
        <div v-if="isDebug" class="configTop">
          <div class="item">
            <span>X坐标：</span>
            <el-input-number v-model="clickItem.posX" :min="0"/>
          </div>
          <div class="item">
            <span>Y坐标：</span>
            <el-input-number v-model="clickItem.posY" :min="0"/>
          </div>
          <div class="item">
            <span>宽度：</span>
            <el-input-number v-model="clickItem.width" :max="1000" :min="1"/>
          </div>
          <div class="item">
            <span>高度：</span>
            <el-input-number v-model="clickItem.height" :max="1000" :min="1"/>
          </div>
        </div>
        <div v-if="isDebug" class="configTop">
          <div class="item">
            <span>画布缩放倍率：</span>
            <el-input-number v-model="scale.toFixed(1)" :max="1000" :min="0.1" :step="0.1" @change="updateImageScale()">
              字体大小
            </el-input-number>
          </div>
          <div class="item">
            <span>字体颜色：</span>
            <el-color-picker v-model="clickItem.color" show-alpha/>
          </div>
          <div class="item">
            <span>字体大小：</span>
            <el-input-number v-model="clickItem.fontSize" :max="1000" :min="1">字体大小</el-input-number>
          </div>
          <div class="item">
            <el-switch
              v-model="clickItem.fontWeight"
              active-color="#13ce66"
              active-text="加粗"
              active-value="bold"
              inactive-color="#0cd8ee"
              inactive-text="不加粗"
              inactive-value="500"/>
          </div>
          <div class="item">
            <el-button v-if="!isUpdate" @click="isUpdate = true">修改模式</el-button>
            <el-button v-else @click="isUpdate = false;">退出修改</el-button>
            <el-button @click="submit">保存点位</el-button>
          </div>
        </div>
        <div class="vdr-main">
          <div
            :style="imagePosition"
            class="vdr-Parent"
            @mousedown="startDrag"
            @mouseleave="endDrag"
            @mousemove="dragging"
            @mouseout="endDrag"
            @mouseup="endDrag"
            @mousewheel.stop="onMouseWheel">
            <vdr
              v-for="item in positionList"
              v-show="isUpdate && item.isShow"
              :key="item.title"
              :h="item.height"
              :parent="false"
              :w="item.width"
              :x="item.posX"
              :y="item.posY"
              @activated="onStart(item)"
              @deactivated="onEnd"
              @dragging="onDrag"
              @resizing="onResize">
              <p
                :style="{
                  color:item.color,
                  fontSize:item.fontSize + 'px',
                  fontWeight:item.fontWeight,
              }">{{ item.title + item.value + item.unit }}</p>
            </vdr>
            <div
              v-for="(item,index) in positionList"
              v-show="!isUpdate && item.isShow"
              :key="index"
              :style="{
                position: 'absolute',
                left:item.posX + 'px',
                top:item.posY + 'px',
                width:item.width + 'px',
                height:item.height + 'px'}"
            >
              <p
                :style="{
                  color:item.color,
                  fontSize:item.fontSize + 'px',
                  fontWeight:item.fontWeight}">
                {{ item.title + item.value + item.unit }}
              </p>
            </div>
            <img src="/static/VPSAProcess.jpg" style="user-select: none;" @dragstart="cancelDrag">
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>

export default {
  data() {
    return {
      isUpdate: false,
      isDebug: false,
      clickOpName: '',
      clickItem: { // 当前选中的对象
        title: '',
        value: '',
        unit: '',
        color: '',
        fontSize: 1,
        fontWeight: '',
        posX: 0,
        posY: 0,
        height: 1,
        width: 1,
        isShow: 0
      },
      scale: 1, // 画布缩放
      draggingState: false, // 画布拖动状态
      startX: 0, // 移动时起始位置X
      startY: 0, // 移动是起始位置Y
      currentX: 0, // 画布移动x
      currentY: 0, // 画布移动y
      imagePosition: { // 画布动态样式
        transform: 'translate(0px, 0px)',
        width: (this.isDebug ? 100 + '%' : 750 + 'px'),
        height: (this.isDebug ? 1800 : 1600) + 'px'
      },
      color: null, // 取色器色盘颜色
      positionList: [], // 点位列表
      OpNameList: [],
      opStatusList: ['关机', '待机', '运行', '报警', '暂停'],
      loading: false
    }
  },
  created() {
    this.getOpName()
  },
  methods: {
    clickTableRow(row, column, event) {
      console.log(row, column, event)
      this.clickItem = row
    },
    // 查询工位号
    getOpName() {
      this.OpNameList = []
      var param = []
      param.push(['Personnel_Number', this.$store.state.user.id])
      var Data = this.CreateData('11', '工位与名称_查询', param)
      this.ExecDatabase(Data).then(response => {
        this.OpNameList = response.data
        this.searchOpPosition(response.data[0])
      })
    },
    // 读取工位点位
    searchOpPosition(item) {
      this.clickOpName = item.工位号
      this.positionList = []
      var param = []
      param[0] = ['工位号', item.工位号]
      var Data = this.CreateData('11', 'WEB_监控数据布局_查询', param)
      this.ExecDatabase(Data).then(response => {
        if (response.data.length !== 0) {
          for (const item of response.data) {
            this.positionList.push({
              title: item.名称,
              value: item.值,
              unit: item.单位,
              color: item.颜色,
              fontSize: item.字体大小,
              fontWeight: item.字体粗细,
              posX: item.位置X,
              posY: item.位置Y,
              height: item.高度,
              width: item.宽度,
              isShow: item.是否显示
            })
          }
        }
      })
    },
    // 画布滚轮事件
    onMouseWheel(event) {
      event.preventDefault()
      const wheelDelta = event.deltaY
      if (wheelDelta > 0 && this.scale > 0.3) {
        this.scale -= 0.1
      } else if (wheelDelta < 0) {
        this.scale += 0.1
      }
      this.updateImageScale()
    },
    // 更新画布缩放
    updateImageScale() {
      // 四舍五入一位小数点
      try {
        // this.scale = this.scale.toFixed(1)
      } catch (e) {

      }
      this.imagePosition.transform = `translate(${this.currentX}px,${this.currentY}px) scale(${this.scale})`
    },
    submit() {
      console.log(JSON.stringify(this.positionList))
      var param = []
      param.push(['工位号', this.clickOpName])
      param.push(['JSON', JSON.stringify(this.positionList)])
      var Data = this.CreateData('11', 'WEB_监控数据布局_JSON批量_修改', param)
      this.ExecDatabase(Data).then(response => {
        if (response.data.length > 0) {
          if (response.data[0].result == 1) {
            this.$message.success(response.data[0].msg)
          } else {
            this.$message.error(response.data[0].msg)
          }
        } else {
          this.$message.error('保存失败!')
        }
      })
    },
    // 拖动位置
    onDrag(x, y) {
      event.stopPropagation()
      this.clickItem.posX = x
      this.clickItem.posY = y
      // console.log('拖动位置:', x, y)
    },
    // 调整大小
    onResize(x, y, width, height) {
      event.stopPropagation()
      this.clickItem.posX = x
      this.clickItem.posY = y
      this.clickItem.width = width
      this.clickItem.height = height
      // console.log('调整大小:', x, y, width, height)
    },
    onStart(item) {
      // 浅拷贝
      this.clickItem = item
      console.log('拖拽开始', item.title)
    },
    onEnd() {
      console.log('拖拽结束')
    },
    // 开始移动画布
    startDrag(event) {
      this.draggingState = true
      this.startX = event.clientX - this.currentX
      this.startY = event.clientY - this.currentY
    },
    // 移动画布位置
    dragging(event) {
      if (this.draggingState) {
        let newX = event.clientX - this.startX
        let newY = event.clientY - this.startY

        // 限制图片移动范围
        // const maxX = 500 - 3840
        // const maxY = 500 - 2160
        // newX = Math.min(0, Math.max(maxX, newX))
        // newY = Math.min(0, Math.max(maxY, newY))
        // 就限制不能出左上角
        newX = Math.min(0, newX)
        newY = Math.min(0, newY)

        this.currentX = newX
        this.currentY = newY
        this.updateImageScale()
      }
    },
    // 结束画布拖拽
    endDrag() {
      this.draggingState = false
    },
    // 禁止图片拖拽事件
    cancelDrag(event) {
      event.preventDefault()
    }
  }
}
</script>

<style lang="scss" scoped>
.bottom {
  display: flex;
}

/* 整个滚动条 */
.opList::-webkit-scrollbar {
  width: 8px;
  height: 12px;
}

/* 滚动条里面滑块 */
.opList::-webkit-scrollbar-thumb {
  border-radius: 10px;
  background: skyblue;
}

/*滚动条里面轨道*/
.opList::-webkit-scrollbar-track {
  border-radius: 10px;
  box-shadow: inset 0 0 1px rgba(0, 0, 0, 0.2);
  background: #eee;
}

.opList {
  display: flex;
  overflow-y: hidden;
  overflow-x: auto;
  width: 100%;
  margin: 10px 0;

  .item {
    flex: 1;
    min-width: 200px;
    height: 90px;
    border: 1px solid #234f7c;
    margin: 10px 5px;
    background-color: #fff;
  }
}

.configTop {
  display: flex;

  .item {
    margin: 0 5px;
  }
}

.vdr-main {
  height: 750px;
  width: 1600px;
  border: 1px solid red;
  overflow: hidden;

  .vdr-Parent {
    position: relative;
    cursor: move;
    user-select: none;
  }
}

</style>

