<template>
  <div id="index">
    <el-row>
      <el-col :span="24" class="main">
        <el-col :span="24" class="one">
          <el-col :span="24" class="one_1">保安员行动轨迹查询</el-col>
          <el-col :span="24" class="one_2">
            <el-form ref="searchFrom" :model="searchFrom" label-width="130px" :rules="rules">
              <el-col :span="24" class="one_2txt">
                <el-col :span="6">
                  <el-form-item label="保安员身份证号" :required="true" prop="card">
                    <el-input v-model="searchFrom.card" clearable></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="轨迹开始时间" :required="true" prop="time@start">
                    <el-date-picker
                      v-model="searchFrom['time@start']"
                      placeholder="请选择"
                      value-format="yyyy-MM-dd HH:mm:ss"
                      format="yyyy-MM-dd HH:mm:ss"
                      type="datetime"
                      style="width: 100%"
                    >
                    </el-date-picker>
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="轨迹结束时间" :required="true" prop="time@end">
                    <el-date-picker
                      v-model="searchFrom['time@end']"
                      placeholder="请选择"
                      value-format="yyyy-MM-dd HH:mm:ss"
                      format="yyyy-MM-dd HH:mm:ss"
                      type="datetime"
                      style="width: 100%"
                    >
                    </el-date-picker>
                  </el-form-item>
                </el-col>
                <el-col :span="6" class="btn">
                  <el-button type="primary" size="mini" @click="submit()">查询</el-button>
                </el-col>
              </el-col>
            </el-form>
          </el-col>
        </el-col>
        <el-col :span="24" class="two">
          <div id="container"></div>
        </el-col>
      </el-col>
    </el-row>
  </div>
</template>

<script>
const _ = require('lodash');
var moment = require('moment');
import { mapState, createNamespacedHelpers } from 'vuex';
const { mapActions: position } = createNamespacedHelpers('position');
export default {
  metaInfo() {
    return { title: this.$route.meta.title };
  },
  name: 'resource',
  props: {},
  components: {},
  data: function () {
    return {
      // 数据查询
      searchFrom: {},
      rules: {
        card: [{ required: true, message: '请输入身份证号', trigger: 'blur' }],
        'time@start': [{ required: true, message: '请选择轨迹开始时间', trigger: 'blur' }],
        'time@end': [{ required: true, message: '请选择轨迹结束时间', trigger: 'blur' }],
      },
      //地图相关
      zoom: '17',
      center: [125.291162, 43.838597], //初始定位到中心
      mapStyle: '',
      points: [],
      // 标记点列表
      markList: [],
      // 地图实例
      map: undefined,
      loca: undefined,
      // 脉冲图层
      pulse: undefined,
      // 脉冲图颜色
      pulseLineColor: ['#7F3CFF', '#4CC19B', '#0B5D74', '#E06AC4', '#223F9B', '#F15C1A', '#7A0FA6', '#EFBB51'],
    };
  },
  mounted() {
    this.init();
  },
  methods: {
    ...position(['query']),
    submit() {
      this.$refs['searchFrom'].validate((valid) => {
        if (valid) {
          this.search();
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    async search() {
      let res = await this.query({ ...this.searchFrom });
      if (this.$checkRes(res)) {
        this.$set(this, `points`, res.data);
        this.changeData();
        this.initPulseLine();
      }
    },
    // 初始化地图
    init() {
      var map = new AMap.Map('container', {
        zoom: this.zoom,
        // showLabel: false,
        viewMode: '2D',
        center: this.center,
        mapStyle: this.mapStyle,
      });
      let loca = this.initLoca(map);
      map.on('complete', function () {
        console.log('地图初始化完成');
      });
      loca.animate.start();
      this.map = map;
      this.loca = loca;
      // 添加标记
      this.addMark(this.points);
    },
    // 数据可视化初始化
    initLoca(map) {
      var loca = new Loca.Container({
        map,
      });

      loca.ambLight = {
        intensity: 0.7,
        color: '#7b7bff',
      };
      loca.dirLight = {
        intensity: 0.8,
        color: '#fff',
        target: [0, 0, 0],
        position: [0, -1, 1],
      };
      loca.pointLight = {
        color: 'rgb(240,88,25)',
        position: [112.028276, 31.58538, 2000000],
        intensity: 3,
        // 距离表示从光源到光照强度为 0 的位置，0 就是光不会消失。
        distance: 5000000,
      };
      return loca;
    },
    // 脉冲图初始化,返回实例
    initPulseLine() {
      this.removePulse();
      // 组织数据
      let mapData = this.initMapLine(this.points);
      let mapGeo = this.initGeoData(mapData);
      // 生成脉冲图 图层
      let layer = new Loca.PulseLineLayer({
        zIndex: 10,
        opacity: 1,
        visible: true,
        zooms: [2, 22],
      });
      layer.setSource(mapGeo);
      layer.setStyle({
        altitude: 0,
        lineWidth: 3,
        // 脉冲头颜色
        headColor: (_, feature) => {
          return this.pulseLineColor[feature.properties.type - 1];
        },
        // 脉冲尾颜色
        trailColor: 'rgba(128, 128, 128, 0.5)',
        // 脉冲长度，0.25 表示一段脉冲占整条路的 1/4
        interval: 0.25,
        // 脉冲线的速度，几秒钟跑完整段路
        duration: 20000,
      });
      this.loca.add(layer);
      this.pulse = layer;
    },
    // 移除脉冲图层
    removePulse() {
      if (this.pulse) {
        this.loca.remove(this.pulse);
        this.pulse = undefined;
      }
    },
    // 组织脉冲路线数据
    initMapLine(points) {
      const pointsList = points.map((i) => [i.longitude, i.latitude]);
      const data = {
        type: 'Feature',
        geometry: {
          type: 'LineString',
          // 点越多,越细致
          coordinates: pointsList, //经纬坐标
        },
        properties: { type: 1 }, // 该点的属性,在设置中可以输出
      };
      return { type: 'FeatureCollection', features: [data] };
    },
    // 添加标记
    addMark(data) {
      if (!this.map) return;
      if (!_.isArray(data) || data.length <= 0) return;
      const points = [_.head(data), _.last(data)];
      const marks = [];
      for (const i of points) {
        const { longitude, latitude } = i;
        if (!longitude || !latitude) continue;
        let mark = new AMap.Marker({
          anchor: 'bottom-center',
          position: [longitude, latitude],
          title: `${i.name}-${this.getDate(i.meta)}`,
        });
        marks.push(mark);
        this.markList.push(mark);
      }
      this.map.add(marks);
    },
    // 坐标数据初始化,返回实例;
    initGeoData(data) {
      let geo = new Loca.GeoJSONSource({
        data,
      });
      return geo;
    },
    // 更换数据:先把数据查好,处理完,放到points中;再调用这个
    changeData() {
      if (!this.map) this.init();
      // 销毁标记
      for (const mark of this.markList) {
        this.map.remove(mark);
      }
      this.markList = [];
      this.addMark(this.points);
    },
    getDate(date) {
      let p1 = moment(date.createdAt).format('YYYY-MM-DD HH:mm:ss');
      if (p1) return p1;
    },
  },
  computed: {
    ...mapState(['user']),
  },
};
</script>

<style lang="less" scoped>
.main {
  .one {
    height: 100px;
    .one_1 {
      height: 40px;
      line-height: 40px;
      border-bottom: 1px solid #ccc;
      margin: 0 0 10px 0;
      font-size: 18px;
      font-weight: bold;
    }
    .one_2 {
      .one_2txt {
        border: 1px solid #ccc;
        /deep/.el-form-item {
          margin: 0;
        }
        /deep/.el-date-editor.el-input,
        .el-date-editor.el-input__inner {
          width: 100%;
        }
        /deep/.el-select {
          width: 100%;
        }
        .btn {
          text-align: right;
          padding: 5px 5px;
        }
      }
    }
  }
  .two {
    margin-top: 15px;
    #container {
      width: 100%;
      height: 650px;
    }
  }
}
</style>
