<template>
  <div class="container">
    <div class="searchSty">
      <el-form :inline="true" style="display: flex; justify-content: space-between" :model="queryForm"
               class="demo-form-inline">
<!--        <el-form-item label="气站名称:">-->
<!--          <el-input v-model="queryForm.orgname" clearable placeholder="请输入气站名称"></el-input>-->
<!--        </el-form-item>-->
        <div>
          <el-form-item label="企业名称:">
            <el-select v-model="queryForm.qyId" @change="handleQyChange" placeholder="请选择">
              <el-option v-for="item in qyOption" :key="item.qyId" :label="item.qymc" :value="item.qyId">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="气站名称:">
            <el-select v-model="queryForm.qzId" placeholder="请选择">
              <el-option v-for="item in qzOption" :key="item.qzId" :label="item.qzmc" :value="item.qzId">
              </el-option>
            </el-select>
          </el-form-item>
        </div>
        <el-form-item>
          <el-button type="primary" icon="el-icon-refresh"
                     style="border: 1px solid #5875eb; background: #ffffff; color: #5875eb; border-radius: 5px;"
                     @click="handleReset" plain>重置
          </el-button>
          <el-button type="primary" style="background: #5875eb; border: 1px solid #5875eb; border-radius: 5px;"
                     icon="el-icon-search" @click="handleSearch"> 查询
          </el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="mapSty">
      <div id="mapContainer"
           class="map"
           tabindex="0">
      </div>
    </div>
    <div ref="infoData"
         v-if="infoWindowVisible"
         class="custom-info input-card content-window-card">
      <div class="info-top" style="display: flex; justify-content: space-between;align-items: center">
        <div>
          <span style="color: #ffffff;">气瓶信息</span>
        </div>
        <div @click="closeInfoWindow" style="display: flex;align-items: center">
          <i class="el-icon-close" style="color: #ffffff; font-size: 20px;cursor: pointer; " ></i>
        </div>
      </div>
      <div class="info-middle"
           style="background-color: white;">
        <el-row>
          <el-col :span="24" v-for="(item,index) in devInfoList1" :key="'dev'+index" >
            <el-col :span="12" v-for="(bitem,index) in item" :key="bitem.name">
              <div class="info-div" style="display: flex">
                <div style="text-align: right;width: 105px;">
                  {{bitem.name}}：
                </div>
                <div class="info-span" style="flex: 1">{{bitem.value}}</div>
              </div>
            </el-col>
          </el-col>
          <el-col :span="24" style="padding: 20px 10px">
            <div style="border-bottom: 1px dashed #dcdfe6;"></div>
          </el-col>
          <el-col :span="24" style="padding: 0px 10px 10px" v-if="orderHolderInfoList1.length>0">
            <div style="font-size: 15px; color: #333333;">
              下单人信息
            </div>
          </el-col>
          <el-col :span="24" v-for="(item,index) in orderHolderInfoList1" :key="'order'+index" v-if="orderHolderInfoList1.length>0">
            <el-col :span="12" v-for="(bitem,index) in item" :key="bitem.name">
              <div class="info-div" style="display: flex">
                <div style="text-align: right;width: 70px;">
                  {{bitem.name}}：
                </div>
                <div class="info-span" style="flex: 1">{{bitem.value}}</div>
              </div>
            </el-col>
          </el-col>
          <el-col :span="24" style="padding: 20px 10px" v-if="orderHolderInfoList1.length>0">
            <div style="border-bottom: 1px dashed #dcdfe6;"></div>
          </el-col>
          <el-col :span="24" style="padding: 0px 10px 10px">
            <div style="display: flex;justify-content: space-between;">
              <div style="font-size: 15px; color: #333333;">
                末次流转
              </div>
              <div style="display: flex;">
                <div style="display: flex;align-items: center;">
                  <div class="completeSty labelSty margin-right-sm"></div>
                  <div>已完成</div>
                </div>
                <div style="display: flex;align-items: center; margin-left: 10px;">
                  <div class="uncompleteSty labelSty"></div>
                  <div>未完成</div>
                </div>
              </div>
            </div>
          </el-col>
          <el-col :span="24">
            <div v-for="(nodeitem,index) of nodeList" :key="index">
              <div v-if="index%2==0">
                <div style="float: left; width: 100%">
                  <div style="float: left; width: 100%" v-if="index !==0 ">
                    <div style="float: left; width: calc(100% / 5);">
                      <img :src="rightImgUrl" style=" transform: translate(30%,-115%) rotate(90deg);width: 45px;height: 15px;" />
                    </div>
                  </div>
                  <div v-for="(bitem,bindex) of nodeitem" style="float: left;width:calc(100% / 5);margin-bottom: 30px;" :key="bindex">
                    <div style="display: flex; ">
                      <el-popover
                        popper-class="popoverSty"
                        :ref="`popover-${bitem.id}`"
                        placement="top-start"
                        width="280"
                        trigger="click"
                      >
                        <div class="popoverStyContent">
                          <div class="popover-content">
                            充装时间:{{bitem.fCzsj}}
                          </div>
                          <div class="popover-content">
                            充装前重:{{bitem.czqz}}
                          </div>
                          <div class="popover-content">
                            充装后重:{{bitem.czhz}}
                          </div>
                          <div class="popover-content">
                            充装单位:{{bitem.czdw}}
                          </div>
                        </div>
                        <div slot="reference" style="display: flex;flex-direction: column;width: 80px; align-items: center; cursor: pointer;" :ref='`bt`+bitem.id' @click="handleNodeItem(bitem)">
                          <img :src="dailyRecordImgUrl" style="width: 46px;height: 46px;" />
                          <div class="textSty">
                            {{bitem.fLzmc}}
                          </div>
                        </div>
                      </el-popover>
                      <img :src="rightImgUrl" v-if="bindex!==nodeitem.length-1" style="width: 45px;height: 15px; margin-top: 20px;" />
                    </div>
                  </div>
                </div>
              </div>
              <div v-else>
                <div style="float: right; width: 100%">
                  <div style="float: right; width: 100%">
                    <div style="float: right; width: calc(100% / 5);">
                      <img :src="rightImgUrl" style=" transform: translate(30%,-115%) rotate(90deg);width: 45px;height: 15px;" />
                    </div>
                  </div>
                  <div v-for="(bitem,bindex) of nodeitem" style="float: right;width: calc(100% / 5);margin-bottom: 30px;" :key="bindex">
                    <div style="display: flex; ">
                      <el-popover
                        popper-class="popoverSty"
                        :ref="`popover-${bitem.id}`"
                        placement="top-start"
                        width="280"
                        trigger="click"
                      >
                        <div class="popoverStyContent">
                          <div class="popover-content">
                            充装时间:{{bitem.fCzsj}}
                          </div>
                          <div class="popover-content">
                            充装前重:{{bitem.czqz}}
                          </div>
                          <div class="popover-content">
                            充装后重:{{bitem.czhz}}
                          </div>
                          <div class="popover-content">
                            充装单位:{{bitem.czdw}}
                          </div>
                        </div>
                        <div slot="reference" style="display: flex;flex-direction: column;width: 80px; align-items: center; cursor: pointer;" :ref='`bt`+bitem.id' @click="handleNodeItem(bitem)">
                          <img :src="dailyRecordImgUrl" style="width: 46px;height: 46px;" />
                          <div class="textSty">
                            {{bitem.fLzmc}}
                          </div>
                        </div>
                      </el-popover>
                      <img :src="rightImgUrl"  v-if="bindex!==0" style="transform: rotate(180deg);width: 45px;height: 15px; margin-top: 20px;" />
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </el-col>
        </el-row>
      </div>
      <div class="info-bottom"
           style="position: relative; top: 0px; margin: 0px auto;"><img src="https://webapi.amap.com/images/sharp.png"></div>
    </div>
  </div>
</template>
<script>
import { getAppTagTypes,getMapPointDetailInfo } from '@/api/gasMap.js'
import { getCurrentEnterpriseAndStation } from '@/api/common.js'
import AMapLoader from '@amap/amap-jsapi-loader';
import iconImg from '@/assets/images/气瓶图标.png'
import iconImg1 from '@/assets/images/气瓶图标1.png'
import rightImg from '@/assets/qpxx/rightArrow.png'
import dailyRecordImg from '@/assets/qpxx/dailyRecord.png'


export default {
  name: "index",
  data() {
    return {
      rightImgUrl:rightImg,
      dailyRecordImgUrl:dailyRecordImg,
      queryForm: {
        qzId: "",  //气站id
        qyId: "" //企业id
      },
      qyOption: [],
      allOption:[],
      qzOption: [],
      reference:{},
      // 控制渲染条件 如果不用v-if会报错 具体可自行尝试
      showPop: false,
      // 保存当前激活的refrence id
      activeId:'',
      devInfoList1:[],
      devInfoList: [
        {
          name: '企业名称',
          value: '孝感市孝南区丰光储龙液化气有限公司储龙液化气有限公司储龙液化气',
          key:'fSsqymc'
        },
        {
          name: '气站名称',
          value: '孝感市孝南区丰光储配液化气',
          key:'fSsczmc'
        },
        {
          name: '气瓶编号',
          value: '017321587662',
          key:'fQpbh'
        },
        {
          name: '制造年月',
          value: '2015年10月5号',
          key:'fZzrq'
        },
        {
          name: '气瓶状态',
          value:'正常',
          key:'qpzt',
        },
        {
          name: '气瓶种类',
          value: '正常',
          key:'qpzl'
        },
        {
          name: '气瓶规格',
          value:'YSP35.5',
          key:'fQpgg',
        },
        {
          name: '出厂编号',
          value: '0240078',
          key:'ccbh'
        },
        {
          name: '自有编号',
          key:'zybh',
          value:'000000'
        },
        {
          name: '检验环编号',
          value: '08094',
          key:'jyhbh'
        },
        {
          name: '本次检验日期',
          key:'bcjyrq',
          value:'2021年7月1号'
        },
        {
          name: '下次检验日期',
          value:'2021年7月1号',
          key:'fXcjysj',
        },
        {
          name: '设计使用年限',
          value: '2027年11月1号',
          key:'sjsynx'
        },
        {
          name: '生产厂家',
          key:'sccj',
          value:'湖北华仕顿容器制造有限公司'
        },
        {
          name: '进站日期',
          value: '2021年7月4号',
          key:'jzrq'
        },
        {
          name: '建档日期',
          key:'jdrq',
          value:'2021年7月4号'
        },
        {
          name: '气瓶原始重量',
          value: '16',
          key:'qpyszl'
        },
        {
          name: '水试验压力',
          key:'ssyyl',
          value:'3.2'
        },
        {
          name: '气瓶容积(L)',
          value: '35.5',
          key:'qprj'
        },
        {
          name: '充装介质',
          key:'czjz',
          value:'液化石油气'
        },
        {
          name: '公称工作压力',
          value: '2.1',
          key:'gcgzyl'
        },
        {
          name: '设计壁厚(mm)',
          key:'sjbh',
          value:'2.5'
        }
      ],
      orderHolderInfoList1:[],
      orderHolderInfoList:[
        {
          name: '会员姓名',
          value: '张三',
          key:'hymc'
        },
        {
          name: '电话',
          value:'017321587662',
          key:'hydh',
        },
        {
          name: '配送地址',
          value: '孝感市汉川市城隍镇八古村拐弯处直行200米',
          key:'hydz'
        },
        {
          name: '订单号',
          value:'017321587662',
          key:'dddh',
        },
        {
          name: '下单时间',
          value: '2024年1月12日 14:00:00',
          key:'xdsj'
        },
        {
          name: '配送员',
          value:'张三',
          key:'psr',
        }
      ],
      markers:[],
      clickMapId:'',
      infoWindowVisible:false,
      map: null, //地图
      pointData: [],
      nodeList:[],
      centerPoint:[114.347441, 30.50438],
    }
  },
  mounted() {
  },
  created () {
    this.initData();
  },
  methods: {
    initData(){
      this.getEnterpriseAndStationList();
      this.getMarkPoint();
    },
    //获取企业和气站数据
    async getEnterpriseAndStationList(){
      await getCurrentEnterpriseAndStation().then((res)=>{
        console.log('打印当前气站和企业信息数据====',res);
        const { value } = res;
        if(value.length>0){
          this.allOption = value;
          this.qyOption = value?value.map((item)=>{
            return {
              qyId:item.qyId,
              qymc:item.qymc
            }
          }):[];
        }
      })
    },
    //选择企业的数据
    handleQyChange(val){
      this.qzOption =[];
      this.queryForm.qzId ='';
      this.qzOption = this.allOption.filter((item)=>item.qyId == val)[0].qzxxList;
    },
    //点击气瓶节点的功能
    handleNodeItem(val){
      console.log('打印val',val)
      // // 这个操作是为了避免与源码中的点击reference doToggle方法冲突
      // if (this.activeId === val.id && this.showPop) return
      // this.showPop = false;
      // this.activeId = val.id;
      // console.log('打印val',val);
      // // 因为reference是需要获取dom的引用 所以需要是$el
      // console.log('打印this.$refs',this.$refs);
      // this.reference = this.$refs['bt'+val.id][0].$el
      // this.$nextTick(() => {
      //   // 等待显示的popover销毁后再 重新渲染新的popover
      //   this.showPop = true;
      //   this.$nextTick(() => {
      //     // 此时才能获取refs引用
      //     this.$refs.pop.doShow()
      //   })
      // })
    },
    //查询按钮
    handleSearch() {
      this.pointData = [];
      this.infoWindowVisible = false;
      this.getMarkPoint();
    },
    //重置按钮
    handleReset() {
      this.qzOption = [];
      this.queryForm.qzId = '';
      this.queryForm.qyId = '';
      this.handleSearch();
    },
   async  getMarkPoint(){
      let params ={
        qzId:this.queryForm.qzId,
        qyId: this.queryForm.qyId,
      }
      await getAppTagTypes(params).then((res)=>{
        let { code, value} = res;
        if(code == 200){
          value.map((item,index)=>{
            if(item.typeone.length>0){
              item.typeone.map((itemone)=>{
                this.pointData.push({
                  ...itemone,
                  type:'one',
                });
              })
            }
            if(item.typetwo.length>0){
              item.typetwo.map((itemtwo)=>{
                this.pointData.push({
                  ...itemtwo,
                  type:'two'
                });
              })
            }
            if(item.typethree.length>0){
              item.typethree.map((itemthree)=>{
                this.pointData.push({
                  ...itemthree,
                  type:'three'
                });
              })
            }
          });
          this.pointData = this.pointData.map(item => {
            return {
              ...item,
              isActive :false,
            }
          });
          this.centerPoint = [this.pointData[0].fjd,this.pointData[0].fwd]
          this.initMap();
        }
      })
    },
    //获取地图数据
    initMap() {
      AMapLoader.reset();
      AMapLoader.load({
        "key": "d8ab422d147ee58cd3eb5a83506c6be4",// 申请好的Web端开发者Key，首次调用 load 时必填
        "version": "2.0",   // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
        "plugins": ['AMap.ToolBar', 'AMap.Driving'], // 需要使用的的插件列表，如比例尺'AMap.Scale'等
        "AMapUI": {
          "version": "1.1",
          "plugins": []
        },
        Loca: {
          version: '2.0' //数据可视化
        }
      }).then((AMap) => {
        this.map = new AMap.Map('mapContainer', {//设置地图容器id
          viewMode: '2D', //是否为3D地图模式
          zoom: 16, //初始化地图层级
          center: this.centerPoint,//初始化地图中心点
        });
        //信息窗口实例
        //循环所有的标记点
        console.log('打印pointData',this.pointData);
        let arr =[];
        for (let i = 0; i < this.pointData.length; i++) {
          const num = i + 1;
          const contentImg = '<div style="color: #fff; width: 50px;height: 50px;"><img src="./src/assets/images/后台.png" />'+num + "</div>"
          // 引入本地图片
          const localIcon = new AMap.Icon({
            size: new AMap.Size(30, 34), // 图标尺寸
            image: iconImg, // 图片的URL
            imageSize: new AMap.Size(30, 34), // 图标所用图片大小
          });
          var marker = new AMap.Marker({
            position: [this.pointData[i].fjd, this.pointData[i].fwd],
            map: this.map,
            icon:localIcon,
            offset: new AMap.Pixel(-15, -20),
          });
          arr.push( Object.assign(this.pointData[i], {
            mapId: marker._amap_id,
          }))
          // 将创建的点标记添加到已有的地图实例+
          marker['arr'] = arr;
          marker['isActive'] = this.pointData[i].isActive;
          // console.log('marker=====', marker);
          this.map.add([marker]);
          // marker.content = '我是第' + (i + 1) + '个Marker';
          marker.on("click", this.markerClick);
          this.markers.push(marker);
          marker.emit('click', {target: marker});
        }
        AMap.plugin('AMap.DistrictSearch', function () {
          //创建行政区查询对象
          var options = {
            subdistrict: 0, //获取边界不需要返回下级行政区
            extensions: 'all',//返回行政区边界坐标组等具体信息
            level: 'province'//查询行政级别为省
          };
          var district = new AMap.DistrictSearch(options);
          // console.log('打印地区搜索', district.search);

          district.search('湖北省', function (status, result) {
            // console.log('打印status', status);
            // 获取湖北省的边界信息
            var bounds = result.districtList[0].boundaries
            var polygons = [];
            if (bounds) {
              for (var i = 0, l = bounds.length; i < l; i++) {
                //生成行政区划polygon
                var polygon = new AMap.Polygon({
                  map: this.map,
                  strokeWeight: 1,
                  path: bounds[i],
                  fillOpacity: 0.7,
                  fillColor: '#CCF3FF',
                  strokeColor: '#CC66CC'
                })
                polygons.push(polygon)
              }
              // 地图自适应
              this.map.setFitView()
            }
          });
        })
      }).catch(e => {
        console.log(e);
      });
    },
    //点击点标记事件
    markerClick(e) {
      this.infoWindowVisible = true;
      let arrNew = e.target.arr.filter((x) => x.mapId == e.target._amap_id);
      this.devInfo = arrNew && arrNew[0];
      // infoWindow.setContent(e.target.content);
      console.log('打印res', arrNew);
      // 如果已选中，则不做处理

      // 引入本地图片
      const newIcon = new AMap.Icon({
        size: new AMap.Size(30, 34), // 图标尺寸
        image: iconImg1, // 图片的URL
        imageSize: new AMap.Size(30, 34), // 图标所用图片大小
      });
      const oldIcon = new AMap.Icon({
        size: new AMap.Size(30, 34), // 图标尺寸
        image: iconImg, // 图片的URL
        imageSize: new AMap.Size(30, 34), // 图标所用图片大小
      });
      if (!e.target.isActive) {
        e.target.isActive = true;
        this.clickMapId = '';
      } else {
        e.target.isActive = false;
        this.getPointDetailInfo(arrNew[0].fqptm,e);
        this.clickMapId = e.target._amap_id;
      }
      this.markers.forEach((marker) => {
        if (marker._amap_id !== this.clickMapId) {
          marker.isActive = true;
          marker.setIcon(oldIcon);
        }else{
          marker.isActive = false;
          console.log('打印marker',marker);
          marker.setIcon(newIcon);
        }
      });
      // 更新选中的标记点
      // 设置当前点击的标记点样式
      // e.target.setIcon(newIcon); // 或者其他方法来重置样式
    },
   async getPointDetailInfo(fqptm,e){
      let params ={
        qptm:fqptm
      }
      await getMapPointDetailInfo(params).then(async(res)=>{
        console.log('打印res',res);
        const { value} = res;
        const {qpdqlzs,qpOrderInfoVO} = value;
        var infoWindow = this.createInfoWindow();
        infoWindow.open(this.map, e.target.getPosition());
        this.devInfoList = await this.$assignValues(value, this.devInfoList);
        this.nodeList = await this.$createDoubleArray(qpdqlzs,5);
        console.log('打印this.nodeList', this.nodeList);
        if(!qpOrderInfoVO){
          this.orderHolderInfoList1 =[];
        }else{
          this.orderHolderInfoList =  await this.$assignValues(qpOrderInfoVO, this.orderHolderInfoList);
          this.orderHolderInfoList1 = await this.$createDoubleArray(this.orderHolderInfoList,2);
        }
        this.devInfoList1  = await this.$createDoubleArray(this.devInfoList,2);

      })
    },
    //4.构建自定义窗体
    createInfoWindow() {
      let infoWindowData = new AMap.InfoWindow({
        isCustom: true, //使用自定义窗体
        content: this.$refs.infoData,
        // content: this.getContent(),
        offset: new AMap.Pixel(-180, -45),
      })
      return infoWindowData
    },
    closeInfoWindow() {
      // 引入本地图片
      const oldIcon = new AMap.Icon({
        size: new AMap.Size(30, 34), // 图标尺寸
        image: iconImg, // 图片的URL
        imageSize: new AMap.Size(30, 34), // 图标所用图片大小
      });
      this.markers.forEach((marker) => {
        if (marker._amap_id == this.clickMapId) {
          marker.isActive = true;
          marker.setIcon(oldIcon);
        }
      });
      this.clickMapId = '';
      this.map.clearInfoWindow();
    },
  }
}

</script>
<style lang="scss">
.popoverSty.el-popover {
  background: #ec661e;
  //border-color: #000022;
  border: 1px solid #ec661e !important;
  border-radius: 10px;
  opacity: 0.92;
  color: #fff;
}
/* 下方是去除三角箭头的代码 */
.popoverSty.el-popper[x-placement^=top] .popper__arrow::after {
  border-top-color: #ec661e !important;
}
</style>
<style lang="scss" scoped>
#mapContainer {
  min-width: 865px;
  min-height: 630px;
}

.container {
  .textSty{
    white-space: nowrap; /* 设置为单行 */
    max-width: 200px; /* 设置最大宽度 */
    overflow: hidden; /* 隐藏超出部分的内容 */
    text-overflow: ellipsis; /* 显示省略号 */
  }
  .searchSty {
    background: #ffffff;
    padding: 0 20px;
    padding-top: 20px;
  }

  .mapSty {
    padding: 20px;
    margin-top: 20px;
    background: #ffffff;
  }
  .labelSty{
    width: 10px;
    height: 10px;
    border-radius: 2px;
    margin-right: 10px;
  }
  .completeSty{
    background-color: #ea5504;
  }
  .uncompleteSty{
    background-color: #ccd0e5;
  }
  .textSty{
    white-space: nowrap; /* 设置为单行 */
    max-width: 200px; /* 设置最大宽度 */
    overflow: hidden; /* 隐藏超出部分的内容 */
    text-overflow: ellipsis; /* 显示省略号 */
  }
}
.content-window-card {
  position: relative;
  box-shadow: none;
  bottom: 0;
  left: 0;
  /* width: auto; */
  width: 45rem;
  padding: 0;
}
.content-window-card p {
  height: 2rem;
}

.custom-info {
  border: solid 1px silver;
}

.info-top {
  position: relative;
  //background: none repeat scroll 0 0 #f9f9f9;
  background: #0076d5;
  border-bottom: 1px solid #ccc;
  //border-radius: 5px 5px 0 0;
}

.info-top div {
  display: inline-block;
  color: #333333;
  font-size: 14px;
  font-weight: bold;
  line-height: 31px;
  padding: 0 10px;
}
.info-top img {
  position: absolute;
  top: 10px;
  right: 10px;
  transition-duration: 0.25s;
}

.info-top img:hover {
  box-shadow: 0px 0px 5px #000;
}

.info-middle {
  font-size: 14px;
  padding: 5px 6px;
  line-height: 25px;
  color: #999DB0;
}

.info-bottom {
  height: 0px;
  width: 100%;
  clear: both;
  text-align: center;
}
.info-bottom img {
  position: relative;
  z-index: 104;
}

/* span {
  margin-left: 5px;
  font-size: 11px;
} */

.info-middle img {
  float: left;
  margin-right: 6px;
}

.info-span {
  /* margin-left: 35px; */
  //font-size: 11px;
  color: #333333;
}

.info-div {
  width: 100%;
  display: inline-block;
  margin-left: 10px;
}

.info-img {
  width: 40px;
  height: 40px;
}

.info-a-title {
  color: #000000;
  font-size: 16px;
}

</style>
