<template>
  <div class="foundationPit-config">
    <div class="left-menu">
      <div class="menu-title">隧道列表</div>
      <div class="add-btn">
        <el-button icon="el-icon-circle-plus-outline" @click="addProject">隧道配置</el-button>
      </div>
      <vue-scroll style="height: calc(100% - 120px)">
        <div class="menu-box" v-if="deepExcavationList.length > 0">
          <div
            class="menu-item"
            :class="{ 'active-item': activeDeep == index }"
            v-for="(item, index) in deepExcavationList"
            :key="index"
            @click="checkTunnel(item, index)"
          >
            <p>隧道名称：{{ item.tunnelName }}</p>
            <p>隧道长度：{{ item.tunnelLength }}</p>
            <p>施工进度：{{ item.constructionProgressBegin }}/{{ item.constructionProgressEnd }}</p>
            <p>Y值随机值范围：{{ item.yvalueRandomRangeStart }}-{{ item.yvalueRandomRangeEnd }}</p>

            <div class="actions-box">
              <el-button type="text">
                <i class="el-icon-edit" @click="editTunnel(item)"></i>
              </el-button>
              <el-button type="text">
                <i class="el-icon-delete" @click="deleteTunnel(item)"></i>
              </el-button>
            </div>
          </div>
        </div>
        <div class="no-data" v-else style="padding-top: 240px">
          <img src="@/assets/images/noData2.png" />
          <p>暂无数据</p>
        </div>
      </vue-scroll>
    </div>
    <div class="foundationPit-content">
      <div class="foundationPit-table">
        <div class="table-title">平面图配置</div>
      </div>
      <div class="tunnelBox">
        <div class="uplodEditMap" v-if="activeImgUrl != ''">
          <el-upload
            :action="$store.state.UPLOADURL"
            multiple
            name="files"
            :show-file-list="false"
            :limit="1"
            :on-success="handleSuccess"
            :on-remove="handleRemove"
          >
            <el-button size="small" type="primary">更换隧道图</el-button>
          </el-upload>
        </div>
        <!-- 平面图卡片 -->
        <div class="mapCard">
          <div class="searchCard">
            <el-input
              placeholder="请输入卡号或姓名查找"
              prefix-icon="el-icon-search"
              size="small"
              v-model="queryStr"
              clearable
              style="margin-bottom: 15px"
              @input="getLocation"
            >
            </el-input>
          </div>
          <el-table class="tables" style="min-height: 165px; margin: 0% 2%; width: 96%" :data="List">
            <el-table-column align="center" label="序号" type="index"></el-table-column>
            <el-table-column prop="enterpriseName" label="企业名称" align="center"></el-table-column>
            <el-table-column prop="teamName" label="班组名称" align="center"></el-table-column>
            <el-table-column prop="count" label="人数" align="center"></el-table-column>
          </el-table>
          <div class="countPeople">共计:{{ countPeople }}人</div>
        </div>
        <div class="tunnelMap" v-if="activeImgUrl != ''">
          <div class="partenUrl">
            <img ref="map" :src="$store.state.FILEURL + activeImgUrl" alt="" />
            <!-- 班组人员点位位置  -->
            <div
              class="pointTunnel"
              ref="pointTunnel"
              v-for="item in pointTunnelList"
              :style="{ top: item.topPx + 'px', left: item.leftPx + 'px' }"
            >
              <div style="width: 90px; text-align: center">
                <!-- 人员名字 -->
              <span style="position: absolute; top: 58%; left: 25%"> {{ item.name }}</span>
              <img style="width: 55px; height: 50px" src="@/assets/images/tunneIcon.png" />
              </div>
            </div>
          </div>
        </div>
        <div class="uplodMap" v-else-if="activeImgUrl == '' && deepExcavationList.length > 0">
          <el-upload
            :action="$store.state.UPLOADURL"
            list-type="picture-card"
            multiple
            name="files"
            :limit="1"
            :file-list="fileList"
            :on-success="handleSuccess"
            :on-remove="handleRemove"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
          <span>上传隧道平面图</span>
        </div>
        <div v-else class="no-data" style="position: absolute; top: 40%; left: 45%">
          <img src="@/assets/images/noData2.png" />
          <p style="margin: 10% 20%">暂无平面图</p>
        </div>
      </div>
    </div>
    <!-- 新增隧道弹框 -->
    <el-dialog :modal-append-to-body="false" @close="close" :title="title" :visible.sync="tunnelDialog" width="667px">
      <div class="dialog_content">
        <el-form size="medium" ref="addEditForm" :model="addEditForm" :rules="addEditRules" label-width="90px" class="dialogFormBox">
          <el-form-item label="隧道名称" prop="tunnelName">
            <el-input v-model="addEditForm.tunnelName" placeholder="请输入"></el-input>
          </el-form-item>
          <el-form-item label="隧道ID" prop="tunnelId">
            <el-input v-model="addEditForm.tunnelId" placeholder="请输入"></el-input>
          </el-form-item>
          <el-form-item label-width="115px" label="隧道长度（m）" prop="tunnelLength" style="margin-left: -15px">
            <el-input style="margin-left: -10px" v-model="addEditForm.tunnelLength" placeholder="请输入" type="number"></el-input>
          </el-form-item>
          <el-form-item label-width="115px" label="施工进度（m）" prop="constructionProgressBegin" style="margin-left: -15px">
            <el-input class="smallInput1" type="number" v-model="addEditForm.constructionProgressBegin"></el-input>/
            <el-input class="smallInput2" type="number" v-model="addEditForm.constructionProgressEnd"></el-input>
          </el-form-item>
          <el-form-item class="labeInput" label="Y值随机范围（px）" prop="yvalueRandomRangeStart" style="margin-left: -10px">
            <el-input
              style="margin-left: -10px"
              class="smallInput1"
              v-model="addEditForm.yvalueRandomRangeStart"
              @change="inputNumber"
              type="number"
            ></el-input>
            -
            <el-input class="smallInput2" v-model="addEditForm.yvalueRandomRangeEnd" @change="inputNumber2" type="number"></el-input>
          </el-form-item>
          <el-form-item label="备注" prop="remark">
            <el-input v-model="addEditForm.remark" placeholder="请输入" clearable=""></el-input>
          </el-form-item>

          <div class="dialog-footer">
            <el-button class="cancleBtn" @click="tunnelDialog = false" icon="el-icon-circle-close" size="medium">取消 </el-button>
            <el-button type="primary" icon="el-icon-circle-check" @click="submit" size="medium">确定 </el-button>
          </div>
        </el-form>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  addLocationTunnelApi, //隧道列表
  deleteLocationTunnelApi,
  editLocationTunnelApi,
  getLocationTunnelApi,
  getRealTimeLocationWorkerApi, //查询实时定位人数
  getcountRealTimeLocationWorkerApi //查询实时定位班组人员
} from '@/assets/js/api/tunnelPositioning'
export default {
  data() {
    return {
      pointTunnelList: [],
      activeDeep: 0,
      deepExcavationList: [],
      projectSn: '',
      queryStr: '',
      List: [],
      tunnelDialog: false,
      addEditForm: {
        tunnelName: '',
        tunnelId: '',
        tunnelLength: '',
        constructionProgressBegin: '',
        constructionProgressEnd: '',
        yvalueRandomRangeStart: null,
        yvalueRandomRangeEnd: null,
        remark: '',
        planarGraph: '',
        id: ''
      },
      addEditRules: {
        tunnelName: [
          {
            required: true,
            message: '必填',
            trigger: 'change'
          }
        ],
        tunnelId: [
          {
            required: true,
            message: '必填',
            trigger: 'change'
          }
        ],
        tunnelLength: [
          {
            required: true,
            message: '必填',
            trigger: 'change'
          }
        ],
        constructionProgressBegin: [
          {
            required: true,
            message: '必填',
            trigger: 'change'
          }
        ],
        yvalueRandomRangeStart: [
          {
            required: true,
            message: '必填',
            trigger: 'change'
          }
        ]
      },
      title: '',
      fileList: [],
      activeImgUrl: '',
      countPeople: 0,
      data1: 0,
      data2: 0
    }
  },

  created() {
    this.projectSn = this.$store.state.projectSn
    this.getList()
  },
  methods: {
    inputNumber(value) {
      console.log('输入框的值---', value, this.addEditForm.yvalueRandomRangeEnd)
      // if (value >= 310 && value <= 530) {
      //   this.addEditForm.yvalueRandomRangeStart = value;
      // } else {
      //   this.$message.error('请输入符合范围内的数值:310-530')
      //   this.addEditForm.yvalueRandomRangeStart = ''
      // }
      if (this.addEditForm.yvalueRandomRangeEnd == '' || value < this.addEditForm.yvalueRandomRangeEnd) {
        this.addEditForm.yvalueRandomRangeStart = value
      } else {
        this.$message.error('请输入正确的范围数值')
        this.addEditForm.yvalueRandomRangeStart = ''
      }
    },
    inputNumber2(value) {
      console.log('输入框的值---', value)
      // if (value >= this.addEditForm.yvalueRandomRangeStart && value <= 530) {
      //   this.addEditForm.yvalueRandomRangeEnd = value;
      // } else {
      //   this.$message.error('请输入符合范围内的数值:310-530')
      //   this.addEditForm.yvalueRandomRangeEnd = ''
      // }
      if (value > this.addEditForm.yvalueRandomRangeStart) {
        this.addEditForm.yvalueRandomRangeEnd = value
      } else {
        this.$message.error('请输入正确的范围数值')
        this.addEditForm.yvalueRandomRangeEnd = ''
      }
    },
    //人员查询
    getLocation() {
      this.getCountTimeLocationList()
      this.getRealTimeLocationList(this.data2)
    },
    //查询实时定位班组人员
    getCountTimeLocationList() {
      getcountRealTimeLocationWorkerApi({
        projectSn: this.projectSn,
        locationTunnelId: this.addEditForm.id,
        queryStr: this.queryStr
      }).then(res => {
        if (res.result) {
          this.List = res.result
          this.countPeople = 0
          this.List.forEach(item => {
            this.countPeople += item.count
          })
          console.log('查询实时定位班组人员:::111', res)
        }
      })
    },
    //查询实时定位人数
    getRealTimeLocationList(width) {
      getRealTimeLocationWorkerApi({
        projectSn: this.projectSn,
        locationTunnelId: this.addEditForm.id,
        queryStr: this.queryStr
      }).then(res => {
        if (res.result) {
          console.log('查询实时定位人数---', res)
          this.pointTunnelList = []
          res.result.forEach(item => {
            //渲染隧道人员点位信息
            //x轴：nx÷隧道长度*总像素=点的x轴
            //y轴：Y值随机值范围：100-200
            let xPx = (item.inlX / this.addEditForm.constructionProgressBegin) * width
            console.log('y轴的值', item.ny)
            // let randomNum4 = parseInt(Math.random() * (yvalueRandomRangeEnd - yvalueRandomRangeStart + 1) + yvalueRandomRangeStart);
            // let yPx = randomNum4;
            let min = this.addEditForm.yvalueRandomRangeStart
            let max = this.addEditForm.yvalueRandomRangeEnd
            // 获取 min 到 max 之间的随机整数
            let randomInt = Math.floor(Math.random() * (max - min + 1)) + min;
            console.log("随机数",randomInt);
            
            let pointTunneObj = {
              topPx: randomInt + 250,
              leftPx: xPx,
              name: item.personName
            }
            this.pointTunnelList.push(pointTunneObj)
          })
          console.log('人员定位数据', this.pointTunnelList)
        }
      })
    },
    // 选中隧道
    checkTunnel(item, index) {
      this.data1 = item.tunnelLength
      console.log('item---', item)
      this.activeImgUrl = ''
      this.addEditForm = item
      // this.addEditForm.constructionProgressBegin = item.constructionProgressBegin
      this.activeDeep = index
      let width = 0
      let height = 0
      if (item.planarGraph && item.planarGraph != '' && item.planarGraph != null) {
        let Img = JSON.parse(item.planarGraph)
        this.activeImgUrl = Img[0].url
        //获取图片大小
        let img = new Image()
        img.src = this.$store.state.FILEURL + this.activeImgUrl
        let that = this
        img.onload = function() {
          console.log('点击隧道列表--- img.width:' + img.width)
          width = img.width
          height = img.height
          that.data2 = width
          that.getRealTimeLocationList(width)
          that.getCountTimeLocationList()
        }
      } else {
        this.activeImgUrl = ''
      }
    },
    //查询隧道列表
    getList() {
      getLocationTunnelApi({
        projectSn: this.projectSn
      }).then(res => {
        if (res.result) {
          //获取隧道长度
          this.deepExcavationList = res.result
          console.log('查询隧道列表:::', res)
          const activeItem = this.deepExcavationList[this.activeDeep]
          if (activeItem) {
            this.checkTunnel(activeItem, this.activeDeep)
          }
        }
      })
    },
    //新增隧道
    addProject() {
      this.title = '新增隧道'
      this.tunnelDialog = true
      this.activeImgUrl = ''
      this.addEditForm = {
        tunnelName: '',
        tunnelId: '',
        tunnelLength: '',
        constructionProgressBegin: '',
        constructionProgressEnd: '',
        yvalueRandomRangeStart: '',
        yvalueRandomRangeEnd: '',
        remark: '',
        planarGraph: '',
        id: ''
      }
      this.$nextTick(() => {
        this.$refs.addEditForm.clearValidate()
      })
    },
    //编辑隧道
    editTunnel(obj) {
      this.tunnelDialog = true
      this.title = '编辑隧道'
      this.addEditForm = JSON.parse(JSON.stringify(obj))
    },
    deleteTunnel(obj) {
      this.$confirm('此操作将永久删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          deleteLocationTunnelApi({ id: obj.id }).then(result => {
            if (result.success) {
              this.$message.success(result.message)
              this.activeImgUrl = ''
              this.addEditForm.id = ''
              this.getList()
            }
          })
        })
        .catch(() => {})
    },
    //新增/编辑
    submit() {
      let params = JSON.parse(JSON.stringify(this.addEditForm))
      params.projectSn = this.projectSn
      this.$refs.addEditForm.validate(valid => {
        if (valid) {
          if (this.title == '新增隧道') {
            addLocationTunnelApi(params).then(result => {
              if (result.success) {
                this.$message.success(result.message)
                this.getList()
              }
            })
          } else if (this.title == '编辑隧道') {
            editLocationTunnelApi(params).then(result => {
              if (result.success) {
                this.$message.success(result.message)
                this.getList()
              }
            })
          }
          this.tunnelDialog = false
        } else {
          return false
        }
      })
    },
    processTheFile() {
      //处理el上传的文件格式(结构)
      this.addEditForm.planarGraph = []
      this.fileList.map(item => {
        if (!item.response) {
          this.addEditForm.planarGraph.push(item)
          // console.log('符合的结构', item)
        } else if (item.response) {
          // console.log('不符合的结构', item)
          this.addEditForm.planarGraph.push({
            name: item.response.data[0].filename,
            url: item.response.data[0].imageUrl
          })
        }
      })
      this.addEditForm.planarGraph = JSON.stringify(this.addEditForm.planarGraph)
    },
    handleSuccess(response, file, fileList) {
      this.fileList = fileList
      this.processTheFile()
      console.log('上传图片时的信息--', this.addEditForm)
      editLocationTunnelApi(this.addEditForm).then(result => {
        if (result.success) {
          this.activeImgUrl = file.response.data[0].imageUrl
          this.$message.success(result.message)
          this.getList()
          this.activeImgUrl = ''
        }
      })
    },
    handleRemove(response, fileList) {
      this.fileList = fileList
    },
    close() {
      this.$nextTick(() => {
        this.$refs.addEditForm.clearValidate()
      })
    }
  }
}
</script>

<style lang="less" scoped>
.sensor {
  border: 1px solid #e7e8eb;
  margin-bottom: 10px;
  padding: 20px 30px 10px 25px;
  border-radius: 10px;
  .sensorDel {
    position: absolute;
    right: 68px;
  }
}
.foundationPit-config {
  // background: #fff;
  width: 100%;
  height: 100%;
  display: flex;
}
.menu-title {
  font-size: 15px;
  font-weight: 600;
  position: relative;
  padding: 15px 0;
  padding-left: 10px;
}
.menu-title::before {
  content: '';
  display: block;
  position: absolute;
  width: 2px;
  height: 13px;
  background: #5181f6;
  top: 50%;
  left: 0;
  transform: translateY(-50%);
}
.left-menu {
  width: 320px;
  margin-right: 3px;
  background: #fff;
  padding: 15px;
  padding-top: 0;
  .add-btn {
    margin-top: 10px;
    margin-bottom: 23px;
    /deep/.el-button {
      background: rgba(#5181f6, 0.1);
      border: 0;
      color: #262d48;
      width: 280px;
      height: 36px;
      line-height: 36px;
      padding: 0;
      display: block;
      margin: 0 auto;
      .el-icon-circle-plus-outline {
        color: #5181f6;
      }
    }
  }
  .no-data {
    text-align: center;
    padding-top: 50px;
    img {
      margin-bottom: 20px;
    }
  }
  .menu-box {
    .menu-item {
      width: 280px;
      margin: 0 auto;
      background: #fbfbfb;
      border: 1px solid #eaeaea;
      padding: 20px 25px 15px;
      box-sizing: border-box;
      margin-bottom: 20px;
      border-radius: 3px;
      cursor: pointer;
      .menu-h2 {
        color: #2a2e3f;
        font-weight: 600;
        margin-bottom: 9px;
        font-size: 16px;
        width: 100%;
        word-break: break-all;
      }
      p {
        font-size: 14px;
        color: rgba(#2a2e3f, 0.8);
        margin-bottom: 7px;
        span {
          padding: 3px 6px;
          border-radius: 10px;
        }
        .status-underway {
          color: #44d7b6;
          background: rgba(#44d7b6, 0.15);
        }
        .status-finish {
          color: #5484f6;
          background: rgba(#5484f6, 0.15);
        }
      }
      /deep/.el-button {
        padding: 0;
        margin-bottom: 14px;
      }
      .actions-box {
        /deep/.el-button {
          padding: 0;
          margin-bottom: 0px;
          .el-icon-delete {
            color: #f24c32;
          }
        }
      }
    }
    .active-item {
      background: #fff;
      border: 0;
      box-shadow: 0px 2px 10px 0px rgba(42, 46, 63, 0.18);
      border: 1px solid #409eff;
    }
  }
}
.foundationPit-content {
  background: #fff;
  flex: 1;
}

.foundationPit-table {
  padding: 0 26px;
  padding-top: 30px;
  .table-title {
    color: #262d48;
    font-weight: 600;
    margin-bottom: 26px;
  }
}
.tunnelBox {
  height: 90%;
  position: relative;
  border: 2px solid #ccc;
  .uplodEditMap {
    position: absolute;
    left: 1%;
    top: 1%;
    text-align: center;
    line-height: 40px;
    z-index: 10;
  }
  .uplodMap {
    position: absolute;
    left: 40%;
    top: 30%;
    text-align: center;
    line-height: 40px;
  }
  .mapCard {
    width: 25%;
    height: 33%;
    left: 74%;
    position: absolute;
    top: 1%;
    border: 2px solid #ccc;
    background: #fff;
    z-index: 999;
    .searchCard {
      height: 15%;
      margin: 1% 2%;
    }
    .countPeople {
      float: right;
      margin-right: 5%;
    }
  }
  .tunnelMap {
    height: 100%;
    width: 100%;
    .partenUrl {
      height: 100%;
      width: 100%;
      box-sizing: border-box;
      padding-top: 250px;
      overflow-x: scroll;
      position: relative;
      .pointTunnel {
        position: absolute;
      }
      img {
        max-width: 300%;
        max-height: 100%;
      }
    }
  }
}
.smallInput1 {
  width: 110px !important;
  margin-left: -10px;
  /deep/.el-input__inner {
    width: 100%;
    display: inline-block;
  }
}
.smallInput2 {
  width: 195px !important;
  /deep/.el-input__inner {
    width: 100%;
    display: inline-block;
  }
}
.labeInput {
  /deep/.el-form-item__label {
    width: 150px !important;
    margin-left: -40px;
  }
}
::v-deep .el-input__inner {
  line-height: 1px !important;
}
::v-deep .el-upload .el-upload-list__item {
  display: none;
}
</style>
