<template>
  <div class="page-track">
    <el-container>
      <el-header style="height: auto">
        <block-header title="搜索">
          <el-upload class="upload-demo" :show-file-list="false" action="" :before-upload="beforeUpload"
                     :http-request="handleUpload">
            <el-button size="small" icon="el-icon-plus" type="primary">导入数据</el-button>
          </el-upload>
        </block-header>
        <div class="page-search">
          <el-form label-suffix=":" size="small" :inline="true" label-width="80px" ref="refForm" :model="form"
                   class="demo-form-inline">
            <el-form-item prop="loanNo" label="经度">
              <el-input
                  clearable
                  v-model.trim="form.lng"
                  @keyup.enter.native="onSubmit"
                  placeholder="请输入"></el-input>
            </el-form-item>
            <template>
              <el-form-item prop="protocolType" label="纬度">
                <el-input
                    clearable
                    v-model.trim="form.lat"
                    @keyup.enter.native="onSubmit"
                    placeholder="请输入"></el-input>
              </el-form-item>
            </template>
            <el-form-item>
              <el-button type="primary" @click="onSubmit">查询</el-button>
              <el-button @click="onReset('refForm')">清空</el-button>
            </el-form-item>
          </el-form>
        </div>

      </el-header>
      <el-container>
        <el-main>
          <!-- 列表 -->
          <block-header title="地图展示"/>
          <div class="map-box">
            <div id="map" style="height: 685px"/>
          </div>

        </el-main>
        <el-aside width="650px">
          <div class="aside-box">
            <block-header title="坐标详情"/>
            <el-input type="textarea" rows="32" v-model="coordinate"></el-input>
          </div>

        </el-aside>
      </el-container>
    </el-container>


  </div>
</template>

<script>
let BMap = {};
let map = {};
import Axios from 'axios'

export default {
  name: "MapTrack",
  data() {
    return {
      form: {
        poi: 0,
        lng: '116.404', // 纬度
        lat: '39.915', // 经度
      },
      map: null,
      coordinate: '',
      point: [],
      desc:[]
    }
  },
  created() {
    // 初始化地图
    this.$nextTick(() => {
      this.init([{lat: '39.915', lng: '116.404'}]);
    });
  },

  methods: {
    /** 初始化协议列表 **/
    async init() {
      try {
        // 创建Map实例
        BMap = window.BMapGL
        this.map = new BMap.Map('map')
        // 初始化地图,设置中心点坐标和地图级别
        this.map.centerAndZoom(new window.BMapGL.Point(116.404, 39.915), 14)
        // 设置地图显示的城市 此项是必须设置的
        // this.map.setCurrentCity('成都')
        // 启用滚轮放大缩小，默认禁用
        this.map.enableScrollWheelZoom(true)
        // 启用地图惯性拖拽，默认禁用
        this.map.enableContinuousZoom(true)

      } catch (err) {
        console.log(err, '沃日')
        this.$Message.error(err || '初始化地图报错');
      }
    },

    /** 上传excel表格*/
    async handleUpload(file) {
      console.log(file, '沃日')
      this.readWorkbookFromLocalFile(file.file, (workbook) => {
        this.readWorkbook(workbook);
      });
    },

    // 读取本地excel文件，读取Excel文件对象
    readWorkbookFromLocalFile(file, callback) {
      const reader = new FileReader();
      reader.onload = function (e) {
        const data = e.target.result;
        const workbook = XLSX.read(data, {type: 'binary'});
        console.log(workbook);
        if (callback) callback(workbook);
      };
      reader.readAsBinaryString(file);
    },
    /** 转成cvs 要注意Execel表格内容不能包含英文的,不然解析出来的数据格式会有问题 */
    readWorkbook(workbook) {
      const sheetNames = workbook.SheetNames; // 工作表名称集合
      const worksheet = workbook.Sheets[sheetNames[0]]; // 这里我们只读取第一张sheet
      const csv = XLSX.utils.sheet_to_csv(worksheet);
      const rows = csv.split('\n'); // 转化为数组
      rows.shift(); // 最后一行没用的
      const nRows = []
      rows.forEach(item => {
        const a = item.split(',')
        const o = {
          time: a[0],
          lat: a[1],
          lng: a[2]
        }
        nRows.push(o)
      })

      const xinRows = nRows.sort(this.dateData("time", true))

      console.log(xinRows,'数据')

      // 画坐标
      xinRows.forEach(async item=>{
        await this.handlePointSearch(item)
      })
    },

    /** 上传前校验 */
    beforeUpload(file) {
      const fileDir = file.name;
      const suffix = fileDir.substr(fileDir.lastIndexOf("."));
      if (".xls" !== suffix && ".xlsx" !== suffix) {
        this.$message.error('上传文件只能是 Excel 文件类型!');
        return false;
      }
      return true;
    },

    /** 数组排序 */
    // property是你需要排序传入的key,bol为true时是升序，false为降序
    dateData(property, bol) {
      return function (a, b) {
        const value1 = a[property];
        const value2 = b[property];
        if (bol) {
          // 升序
          return Date.parse(value1) - Date.parse(value2);
        } else {
          // 降序
          return Date.parse(value2) - Date.parse(value1)
        }
      }
    },

    /** 搜索提交 */
    async onSubmit() {
      if (!this.form.lat) {
        return
      }
      if (!this.form.lng) {
        return
      }
      const params = this.form
      try {
        await this.handlePointSearch(params)
      } catch (err) {

      }
    },

    getTime() {
      let date = new Date(),
          year = date.getFullYear(),
          month = date.getMonth() + 1,
          day = date.getDate(),
          hour = date.getHours() < 10 ? "0" + date.getHours() : date.getHours(),
          minute = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes(),
          second = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
      month >= 1 && month <= 9 ? (month = "0" + month) : "";
      day >= 0 && day <= 9 ? (day = "0" + day) : "";
      return year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + second;
    },

    /** 坐标查询 */
    async handlePointSearch(params) {
      const point = []
      if (!params.time) params.time = this.getTime();
      Axios({
        url: "https://qryloct.market.alicloudapi.com/lundear/qryloct",
        method: 'GET',
        params: params,
        headers: {
          'Authorization': 'APPCODE 7c9180ba9d32452ebebc71a1a2632efc',
          'Content-Type': 'multipart/form-data'
        }
      }).then((res) => {
        if (res.status === 200) {
          const result = res.data.result;
          const {address} = result
          const str = `时间: ${params.time},精度: ${params.lat},纬度: ${params.lng},${address};`
          this.desc.push(str)
          point.push({
            lat: params.lat,
            lng: params.lng
          })
        }
        this.coordinate = this.desc.join('\n')
        this.point = point

        // 画点
        if (point && point.length) {
          point.forEach(item => {
            const m = new window.BMapGL.Marker(new window.BMapGL.Point(item.lng, item.lat))
            this.map.addOverlay(m);
          })
        }

      }).catch((e) => {
        console.log(e, '错误')
      });
    }

  }
}


</script>

<style lang="less" src="./index.less" scoped></style>
