<template>
  <!-- 基本信息 -->
  <div class="cooperator flex">
    <div class="left whiteBlock">
      <!-- <div class="title">全部卸料平台</div> -->
      <vue-scroll style="height: 94%">
        <el-menu
          :default-active="String(checkedId)"
          class="el-menu-vertical-demo whiteBlock"
        >
          <el-menu-item
            index="0"
            class="el-menu-item"
            :class="checkedId == 0 ? 'checked_item' : ''"
            @click="selectMenu(0)"
          >
          <!-- 全部卸料平台(位置配置) -->
            <span slot="title">{{$t('message.unload.menuTitle')}}</span>
          </el-menu-item>
          <el-menu-item
            :index="String(item.id)"
            v-if="unloadList.length > 0"
            class="el-menu-item"
            :class="checkTowerId == item.id ? 'checked_item' : ''"
            v-for="(item, index) in unloadList"
            @click="selectMenu(index + 1)"
            :key="index"
          >
            <span slot="title" class="flex3 ">
                <span class="title_index">{{ index + 1 }}</span>
                <span class="title_name">{{ item.devName }}</span>
            </span>
          </el-menu-item>
        </el-menu>
      </vue-scroll>
      <div class="flex2 btn_pack">
        <!-- 新增设备 -->
        <el-button v-if="isDevBackEnd" size="small" type="primary" @click="newTowerBtn"
          >{{$t('message.unload.addDev')}}</el-button
        >
        <!-- "删除设备" : "取消新增" -->
        <el-button v-if="isDevBackEnd"
          size="small"
          type="danger"
          @click="deleteOrCancel"
          :disabled="checkedId == 0"
          >{{ checkedId != -1 ? $t('message.unload.removeDev'):$t('message.unload.cancelAdd') }}</el-button
        >
        <!-- 保存设备位置信息 -->
        <el-button
          size="small"
          type="success"
          @click="saveTowerLocationBtn"
          :disabled="checkedId != 0"
          >{{$t('message.unload.saveDevPointInfo')}}</el-button
        >
      </div>
    </div>
    <div class="right">
      <div class="pageTitle title flex2 whiteBlock" style="margin-bottom: 0">
        {{ rightTitle }}
        <!-- 对接协议下载 -->
         <span v-show="isDevBackEnd" class="downloadBtn primaryText" @click="downloadFn">{{$t('message.unload.downLoadExcel')}}</span>
      </div>
      <div class="content whiteBlock" v-if="!showTowerInfo">
        <div class="bgPack">
          <img :src="bgUrl" style="width: auto; height: auto" ref="bgPackImg" />
          <!-- 卸料平台点位 -->
          <div
            v-for="(item, index) in unloadList"
            class="point"
            :key="index"
            :style="{ top: item.mapY + 'px', left: item.mapX + 'px' }"
            @mousedown="(e) => mousedown(e, index)"
          >
            {{ index + 1 }}
          </div>
        </div>
      </div>
      <div class="content whiteBlock" v-else>
        <vue-scroll>
        <el-form
          :model="facilityForm"
          :rules="$t('message.unload.rules')"
          ref="facilityForm"
          label-width="150px"
          class="demo-facilityForm"
        >
        <!-- 设备名称 -->
          <el-form-item :label="$t('message.unload.devName')" prop="devName">
            <el-input
              v-model="facilityForm.devName"
              :placeholder="$t('message.unload.placeholderText')"
            ></el-input>
          </el-form-item>
          <!-- 设备编号 -->
          <el-form-item :label="$t('message.unload.devNo')" prop="devSn">
            <!-- '新增卸料平台' -->
            <el-input
              v-model="facilityForm.devSn"
              :disabled="rightTitle!=$t('message.unload.addDev2')"
              :placeholder="$t('message.unload.placeholderText2')"
            ></el-input>
          </el-form-item>
          <!-- 最大载重 -->
            <el-form-item :label="$t('message.unload.maxLoad')" prop="maxLoad">
            <el-input
            type="number"
              v-model="facilityForm.maxLoad"
              :placeholder="$t('message.unload.placeholderText')"
            ></el-input>
          </el-form-item>
          <!-- 重要报警推送人 -->
          <el-form-item :label="$t('message.unload.alarmPeople')" prop="importantAlarmPushWorkerId">
            <el-select
              v-model="facilityForm.importantAlarmPushWorkerId"
              multiple
              collapse-tags
              style="width: 100%"
              :placeholder="$t('message.unload.placeholderText3')"
            >
              <el-option
                v-for="item in driverList"
                :key="item.workerId"
                :label="item.workerName"
                :value="item.workerId+''"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <!-- 紧急报警推送人 -->
          <el-form-item :label="$t('message.unload.alarmPeople2')" prop="urgentAlarmPushWorkerId">
            <el-select
              v-model="facilityForm.urgentAlarmPushWorkerId"
              multiple
              collapse-tags
              style="width: 100%"
              :placeholder="$t('message.unload.placeholderText3')"
            >
              <el-option
                v-for="item in driverList"
                :key="item.workerId"
                :label="item.workerName"
                :value="item.workerId+''"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <!-- 次要报警推送人 -->
          <el-form-item :label="$t('message.unload.alarmPeople3')" prop="secondaryAlarmPushWorkerId">
            <el-select
              v-model="facilityForm.secondaryAlarmPushWorkerId"
              multiple
              collapse-tags
              style="width: 100%"
              :placeholder="$t('message.unload.placeholderText3')"
            >
              <el-option
                v-for="item in driverList"
                :key="item.workerId"
                :label="item.workerName"
                :value="item.workerId+''"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <!-- 提示报警推送人 -->
          <el-form-item :label="$t('message.unload.alarmPeople4')" prop="promptAlarmPushWorkerId">
            <el-select
              v-model="facilityForm.promptAlarmPushWorkerId"
              multiple
              collapse-tags
              style="width: 100%"
              :placeholder="$t('message.unload.placeholderText3')"
            >
              <el-option
                v-for="item in driverList"
                :key="item.workerId"
                :label="item.workerName"
                :value="item.workerId+''"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="" >
            <!-- 保存 -->
            <el-button type="primary" size="medium" @click="submit"
              >{{$t('message.unload.save')}}</el-button
            >
          </el-form-item>
        </el-form>
        </vue-scroll>
      </div>
    </div>
  </div>
</template>
<script>
import {
  getUnloadListApi,
  addUnloadInfoApi,
  editTowerInfoApi,
  getDetailsApi,
  deleteTowerInfoApi,
  setUpdateTowerCoordinateApi,
} from "@/assets/js/api/unloadManage";
import {
  getProjectChilderSystemUserListApi
} from "@/assets/js/api/configManage";
export default {
  data() {
    return {
      projectSn: "",
      uploadUrl: "",
      fileUrl: "",
      //校验设备详情信息
      rules: {
        devName: [
          {
            required: true,
            message: this.$t('message.unload.rules.devName[0].message'), // 请输入设备名称
            trigger: "blur",
          },
        ],
      
     
      },
      //设备详情信息
      facilityForm: {
        devName: "",
        devSn: "",
        maxLoad: "",
        promptAlarmPushWorkerId:'',
        importantAlarmPushWorkerId:'',
        secondaryAlarmPushWorkerId:'',
        urgentAlarmPushWorkerId:'',
      },
      checkTowerId: "", //选中的卸料平台id 只作为列表选中状态切换
      checkedId: 0, //选中的设备 -1 新增状态 控制取消按钮  获取选中设备
      unloadList: [], //设备列表
      rightTitle: this.$t('message.unload.sceneImg'), // 现场施工图
      driverList: [], //司机列表
      showTowerInfo: false, //显示施工图或卸料平台信息
      bgUrl: "", //施工图
      isDevBackEnd:false
    };
  },
  created() {
    this.uploadUrl = this.$store.state.UPLOADURL;
    this.fileUrl = this.$store.state.FILEURL;
    this.projectSn = this.$store.state.projectSn;
    this.getUnloadListApi(1);
    this.getWorkerInfoList();
    this.bgUrl = this.$store.state.currentProDetail.constructionMapUrl;
    if(this.$route.path.indexOf('equipmentCenter')!=-1){
      this.isDevBackEnd=true
    }
  },
  methods: {
    downloadFn(){
      // 卸料平台对外对接协议
        // window.open('/doc/'+this.$t('message.unload.unloadingAgreement')+'.docx')
        window.open('http://182.90.224.147:100/document/index.html#卸料平台对接')
    },
    // 获取所有卸料平台
    getUnloadListApi(type) {
      let data = {
        projectSn: this.projectSn,
      };
      getUnloadListApi(data).then((res) => {
        if (res.code == 200) {
          this.unloadList = res.result;
          if (type == 1) {
            // this.checkedId = 0;
            // this.checkTowerId = "";
          } else {
            this.checkedId = this.unloadList.length;
            this.checkTowerId = this.unloadList[this.unloadList.length - 1].id;
            //详情
            this.selectMenu(this.checkedId);
          }
        }
      });
    },

    //切换卸料平台
    selectMenu(val) {
      this.checkedId = val;
      if (val == 0) {
        // "现场施工图"
        this.rightTitle = this.$t('message.unload.sceneImg');
        this.showTowerInfo = false; //显示施工图
        this.checkTowerId = "";
      } else {
        this.showTowerInfo = true;
        if (this.unloadList[val - 1].id) {
          this.rightTitle = this.unloadList[val - 1].devName;
          this.facilityForm = this.unloadList[val - 1];
          this.checkTowerId = this.unloadList[val - 1].id;
          this.getDetailsData(this.unloadList[val - 1].id);
        }

      }
    },

    // 查询设备详情
    getDetailsData(id) {
      let data = {
        id,
      };
      getDetailsApi(data).then((res) => {
        if (res.code == 200) {
          this.facilityForm = res.result;
   
          if(this.facilityForm.importantAlarmPushWorkerId){
            if(this.facilityForm.importantAlarmPushWorkerId.indexOf(',')!=-1){
              this.facilityForm.importantAlarmPushWorkerId=this.facilityForm.importantAlarmPushWorkerId.split(',')
            }else{
              this.facilityForm.importantAlarmPushWorkerId=[this.facilityForm.importantAlarmPushWorkerId]
            }
          }else{
            this.facilityForm.importantAlarmPushWorkerId=[]
          }
          if(this.facilityForm.promptAlarmPushWorkerId){
            if(this.facilityForm.promptAlarmPushWorkerId.indexOf(',')!=-1){
              this.facilityForm.promptAlarmPushWorkerId=this.facilityForm.promptAlarmPushWorkerId.split(',')
            }else{
              this.facilityForm.promptAlarmPushWorkerId=[this.facilityForm.promptAlarmPushWorkerId]
            }
          }else{
            this.facilityForm.promptAlarmPushWorkerId=[]
          }
          if(this.facilityForm.secondaryAlarmPushWorkerId){
            if(this.facilityForm.secondaryAlarmPushWorkerId.indexOf(',')!=-1){
              this.facilityForm.secondaryAlarmPushWorkerId=this.facilityForm.secondaryAlarmPushWorkerId.split(',')
            }else{
              this.facilityForm.secondaryAlarmPushWorkerId=[this.facilityForm.secondaryAlarmPushWorkerId]
            }
          }else{
            this.facilityForm.secondaryAlarmPushWorkerId=[]
          }
          if(this.facilityForm.urgentAlarmPushWorkerId){
            if(this.facilityForm.urgentAlarmPushWorkerId.indexOf(',')!=-1){
              this.facilityForm.urgentAlarmPushWorkerId=this.facilityForm.urgentAlarmPushWorkerId.split(',')
            }else{
              this.facilityForm.urgentAlarmPushWorkerId=[this.facilityForm.urgentAlarmPushWorkerId]
            }
          }else{
            this.facilityForm.urgentAlarmPushWorkerId=[]
          }
        }
      });
    },

    //新增卸料平台按钮
    newTowerBtn() {
      this.facilityForm = {
        devName: "",
        devSn: "",
        promptAlarmPushWorkerId:[],
        importantAlarmPushWorkerId:[],
        secondaryAlarmPushWorkerId:[],
        urgentAlarmPushWorkerId:[],
      };
      this.showTowerInfo = true;
      this.checkedId = -1;
      this.checkTowerId = "";
      // "新增卸料平台"
      this.rightTitle = this.$t('message.unload.addDev2');
    },

    //删除或取消按钮
    deleteOrCancel() {
      //新增状态 this.checkedId=-1 为取消按钮
      if (this.checkedId == -1) {
        // "现场施工图"
        this.rightTitle = this.$t('message.unload.sceneImg');
        this.checkedId = 0;
        this.showTowerInfo = false;
      } else {
        // 删除按钮 "此操作将永久删除该设备, 是否继续?", "提示"
        this.$confirm(this.$t('message.unload.hintText'),this.$t('message.unload.hint'), {
          confirmButtonText: this.$t('message.unload.confirm'),
          cancelButtonText: this.$t('message.unload.cancel'),
          type: "warning",
        })
          .then(() => {
            let data = {
              id: this.unloadList[this.checkedId - 1].id,
            };
            deleteTowerInfoApi(data).then((res) => {
              if (res.code == 200) {
                this.checkedId = 0;
      this.checkTowerId = "";
                this.getUnloadListApi(1);
                this.showTowerInfo = false;
                // "现场施工图"
                this.rightTitle = this.$t('message.unload.sceneImg');
                this.$message({
                  type: "success",
                  message: this.$t('message.unload.removeSuccess'),
                });
              } else {
                this.$message.error(res.message);
              }
            });
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: this.$t('message.unload.cancelRemove'),
            });
          });
      }
    },

    //移动卸料平台位置
    mousedown(e, index) {
      let bgPackImg = this.$refs.bgPackImg; //获取背景图
      let maxH = bgPackImg.scrollHeight - 30; //可移动的最大高度
      let maxW = bgPackImg.scrollWidth - 30; //可移动的最大宽度
      let objDiv = e.target;
      //算出鼠标相对元素的位置
      let disX = e.clientX - objDiv.offsetLeft;
      let disY = e.clientY - objDiv.offsetTop;

      //鼠标移动时
      document.onmousemove = (e) => {
        //用鼠标的位置减去鼠标相对元素的位置，得到元素的位置
        let left = e.clientX - disX;
        let top = e.clientY - disY;
        if (left < 0 || top < 0 || top > maxH || left > maxW) {
          return;
        } else {
          this.unloadList[index].mapX = left;
          this.unloadList[index].mapY = top;
        }
      };
      //鼠标松开时
      document.onmouseup = (e) => {
        document.onmousemove = null;
        document.onmouseup = null;
      };
    },

    //获取司机列表
    getWorkerInfoList() {
      let data = {
        projectSn: this.projectSn,
      };
      getProjectChilderSystemUserListApi(data).then((res) => {
        this.driverList = res.result;
      });
    },

  

    //保存新增
    submit() {
      this.$refs["facilityForm"].validate((valid) => {
        if (valid) {
          let data = JSON.parse(JSON.stringify(this.facilityForm));
          data.projectSn = this.projectSn;
          data.mapX = "0";
          data.mapY = "0";

          data.importantAlarmPushWorkerId=data.importantAlarmPushWorkerId.join(',')
          data.promptAlarmPushWorkerId=data.promptAlarmPushWorkerId.join(',')
          data.secondaryAlarmPushWorkerId=data.secondaryAlarmPushWorkerId.join(',')
          data.urgentAlarmPushWorkerId=data.urgentAlarmPushWorkerId.join(',')
          if (this.checkedId == -1) {
            //新增
            addUnloadInfoApi(data).then((res) => {
              if (res.code == 200) {
                this.getUnloadListApi(2);
                this.$message.success(this.$t('message.unload.addSuccess'));
              } else {
                this.$message.error(res.message);
              }
            });
          } else {
            editTowerInfoApi(data).then((res) => {
              if (res.code == 200) {
                this.getUnloadListApi(1);
                this.$message.success(this.$t('message.unload.editSuccess'));
              }
            });
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    //保存卸料平台位置
    saveTowerLocationBtn() {
      console.log(this.unloadList);
      let data = [];
      for (let i = 0; i < this.unloadList.length; i++) {
        let obj = {
          id: this.unloadList[i].id,
          mapX: this.unloadList[i].mapX,
          mapY: this.unloadList[i].mapY,
        };
        data.push(obj);
      }
      setUpdateTowerCoordinateApi(data).then((res) => {
        console.log(res);
        if (res.code == 200) {
          this.$message.success(this.$t('message.unload.saveSuccess'));
          this.getUnloadListApi(1);
        }
      });
    },
  },
};
</script>
<style lang="less" scoped>
.flex {
  display: flex;
}
.flex2 {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.flex3 {
  display: flex;
  align-items: center;
}
.cooperator {
  width: 100%;
  height: 100%;
  .left {
    height: 100%;
    width: 350px;
    margin-right: 15px;
    font-size: 15px;
    .title {
      height: 41px;
      line-height: 41px;
      box-sizing: border-box;
      padding: 0 22px;
      margin-bottom: 0;
      // color: #282e49;
      // border-bottom: 2px #ebf0fc solid;
      font-weight: 600;
    }
    .title_index {
      display: inline-block;
      width: 30px;
      text-align: center;
      background: #ec7e2e;
      height: 20px;
      line-height: 20px;
      font-size: 14px;
      margin-right: 10px;
      border-radius: 25px;
      color: #fff;
    }
    .title_name {
      width: 68%;
      display: inline-block;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
    .el-menu-item {
      border-bottom: 1px #ebf0fc solid;
      border-left: 3px solid white;
      height: 50px;
      line-height: 50px;
      padding: 0 20px !important;
      font-size: 16px;
    }
    .checked_item {
      border-left: 3px solid #5181f6;
      // padding: 0 27px !important;
      background-color: #e1e8fa !important;
    }
    .btn_pack {
      padding: 5px 15px 0;

      box-sizing: border-box;
      justify-content: center;
      button {
        height: 34px;
      }
    }
  }
  .right {
    height: 100%;
    width: calc(100% - 350px);
    .title {
      font-size: 15px;
      height: 41px;
      line-height: 41px;
      // background-color: #ffffff;
      box-sizing: border-box;
      padding: 0 22px;
      // color: #282e49;
      border-bottom: 2px #ebf0fc solid;
      font-weight: 600;
      .right_value {
        color: rgba(115, 121, 150, 100);
        font-size: 14px;
        font-weight: 100;
        .value {
          color: #5181f6;
        }
      }
    }
    .content {
      height: calc(100% - 41px);
      // background-color: #fff;
      box-sizing: border-box;
      padding: 30px 20px;
      .demo-facilityForm {
        width: 50%;
      }
    }
  }
}
/deep/ .__view {
  min-height: calc(100% - 41px) !important;
}
/deep/ .el-checkbox__label {
  display: none;
}
.el-menu-vertical-demo {
  width: 100%;
}

.cooperatorDetail {
  width: 100%;
  height: 100%;
  // background: #ffffff;
  box-sizing: border-box;
  .navigationTitle {
    //    border-bottom: 2px solid #ebf0fc;
    // margin-bottom: 15px;
  }
}

.nodata_wrap {
  width: 100%;
  text-align: center;
  height: 80%;
  padding-top: 20%;
  box-sizing: border-box;
  // color: #c3d4fd;
  div {
    margin-top: 10px;
  }
}

.bgPack {
  width: 100%;
  height: 100%;
  background-repeat: no-repeat;
  position: relative;
  overflow: auto;
  .point {
    position: absolute;
    display: inline-block;
    width: 30px;
    height: 30px;
    border-radius: 50%;
    background: rgb(236, 126, 46);
    text-align: center;
    line-height: 30px;
    color: #fff;
    cursor: pointer;
    user-select: none;
  }
  .point:hover {
    background: rgb(241, 191, 24);
  }
}
.downloadBtn{
  cursor: pointer;
}
</style>