<template>
  <div>
    
    <van-nav-bar title="设备详情" left-text="返回" left-arrow @click-left="$router.back()" />

    <!-- 设备位置地图 -->
    <div id="location-map">
    </div>

    <van-cell-group title="">
      <van-field
        v-model="device_info.device_name"
        label="设备名称"
        readonly
        input-align="right"
      />
      <van-field
        v-model="device_info.imei"
        label="设备IMEI"
        readonly
        input-align="right"
      />
      <van-field
        v-model="device_info.device_type"
        label="设备分类"
        readonly
        input-align="right"
      />
      
      <!-- <van-field
        type="textarea"
        v-model="device_info.address"
        label="最后定位地址"
        readonly
        input-align="right"
        :right-icon="device_info.last_location ? 'location-o' : ''"
      /> -->
      <van-field
        v-model="device_info.factory_number"
        label="出厂编号"
        readonly
        input-align="right"
      />
      <van-field
        v-model="device_info.last_online_time"
        label="最后在线时间"
        readonly
        input-align="right"
      />
      <van-field
        v-model="device_info.check_next_time"
        label="上次校验时间"
        readonly
        input-align="right"
      />
      <van-field
        v-model="device_info.check_next_time"
        label="下次校验时间"
        readonly
        input-align="right"
      />
      
      <van-field
        label="历史轨迹"
        readonly
        input-align="right"
      >
        <template #input>
          <span style="color:blue;" @click="historyRoute">点击查看</span>
        </template>
      </van-field>
    </van-cell-group>
    <van-divider>文件上传</van-divider>
    <van-form @submit="onSubmit">
      

     
      <van-field

        v-model="uploadFile"
        label="选择文件"
        type="file"
        readonly
        input-align="right"
      />

      <div style="margin: 16px">
        <van-button
          round
          block
          type="info"
          size="small"
          native-type="submit"
        >提交</van-button
      >
      </div>
    </van-form>

  </div>
</template>

<script>
import Vue from "vue";
import {
  Form,
  Field,
  CellGroup,
  Button,
  Divider,
  RadioGroup,
  Radio,
  NavBar,
  Dialog,
} from "vant";

Vue.use(NavBar);
Vue.use(Form);
Vue.use(Field);
Vue.use(CellGroup);
Vue.use(Button);
Vue.use(Divider);
Vue.use(RadioGroup);
Vue.use(Radio);

export default {
  data() {
    return {
      id: null, // 告警id

      device_info: {}, // 设备信息
      uploadFile:"",
      handleResult: "1",
      comment: "",
      handleTime: '',
      userid: null,
      // 地图
      map: null,
    };
  },
  created() {
    this.openid = localStorage.getItem("openid");
    this.userid = localStorage.getItem("yysUserid");

    this.id = this.$route.query.id;

    // this.getDetail();
  },
  mounted() {
    let that = this;
    this.initMap()
        .then((result) => {
            if(result === false){
                this.$toast('地图初始化失败，请刷新重试');
                return;
            }

            that.getDetail();
        })
        .catch((err) => {
            this.$toast('地图数据初始化出错，请刷新重试');
            console.log(err);
            return;
        })

  },
  destroyed() {
    this.map && this.map.clearMap() && this.map.destroy();
    this.map = null;
  },
  methods: {
    /**
     * 初始化地图
     */
    initMap(){
        let that = this;

        return new Promise((resolve, reject) => {
            try {
                var map = new AMap.Map('location-map', {
                    zoom:15,//级别
                    center: [119.5,32.9],//中心点坐标
                    // viewMode:'3D',//使用3D视图
                    // mapStyle: 'amap://styles/light',
                    showBuildingBlock: true
                });
                AMap.plugin([
                    'AMap.ToolBar',
                    'AMap.Scale',
                    'AMap.Geolocation',
                ], function(){
                    // 在图面添加工具条控件，工具条控件集成了缩放、平移、定位等功能按钮在内的组合控件
                    map.addControl(new AMap.ToolBar({position: 'RT'}));
                    // 在图面添加比例尺控件，展示地图在当前层级和纬度下的比例尺
                    map.addControl(new AMap.Scale({position: 'LT'}));
                    // // 在图面添加类别切换控件，实现默认图层与卫星图、实施交通图层之间切换的控制
                    // map.addControl(new AMap.MapType());
                    // 定位按钮
                    map.addControl(new AMap.Geolocation({
                        enableHighAccuracy: true,//是否使用高精度定位，默认:true
                        timeout: 10000,          //超过10秒后停止定位，默认：5s
                        position:'RB',    //定位按钮的停靠位置
                        buttonOffset: new AMap.Pixel(10, 20),//定位按钮与设置的停靠位置的偏移量，默认：Pixel(10, 20)
                        zoomToAccuracy: true,   //定位成功后是否自动调整地图视野到定位点
                    }));
                });

                that.map = map;
                
                resolve(that.map);
            } catch (error) {
                console.log(error)
                reject(false);
            }
        });
    },
    // 获取告警详情
    getDetail() {
      let url = 'getDeviceDetail&openid='+this.openid+'&userid='+this.userid+'&id='+this.id;

      let resp={
        status:200,
        data:{
          success:true,
          message:"获取成功",
          data: {"id":"79","imei":"869678040089818","rfid":"40089818","iccid":null,"device_name":"测试设备1","device_type":"0","use_state":"1","loc_mode":null,"loc_ploy":null,"net_state":"2","online_time":"0","department_id":"1","battery_level":"0","longitude":"120.200973","latitude":"30.191684","address":null,"wifi_macs":null,"wifi_latitude":null,"badge_user_id":null,"user_id":"246","alarm_state":"0","creator_id":"232","created_at":"1642144743","updated_at":"1642144743","deleted_at":"0","authorize":"0","avatar":null,"sync_status":"1","loc_ploy_state":"1","last_online_time":"2022-09-01 08:00:00","last_location":"120.194413,30.185947","device_type":"液压工具","factory_number":"2022090210121425","check_last_time": "2022-07-14","check_next_time": "2022-07-05"}
          

        }
      }
      // this.$http.get(url).then((resp) => {
          if (resp.status !== 200 || !resp.data || !resp.data.success) {
            this.$notify(resp.data.message || '获取数据失败，请刷新页面重试')
            return;
          }
          this.device_info = resp.data.data || {};


     
          this.comment = this.device_info.comment || '';

          if (this.device_info.last_location) {
            let location = this.device_info.last_location.split(',');
            // 添加坐标点
            let markerPos = new AMap.LngLat(location[0], location[1]);
            let image = 'https://rlfd.oss-cn-hangzhou.aliyuncs.com/wxt_school/smart_card.png';
  
            var marker = new AMap.Marker(
                {
                    position: markerPos,
                    icon: new AMap.Icon({
                        size: new AMap.Size(30, 30),
                        imageSize: new AMap.Size(30, 30),
                        image: image,
                        
                    }), // 添加 Icon 图标 URL 
                    offset: new AMap.Pixel(-15,-30),
                }
            )
            // 添加marker
            // this.map.add(marker);
            marker.setMap(this.map);
            // 设置文本
            let label = this.device_info.imei;
            if (this.device_info.device_name) {
              label = label + '（' + this.device_info.device_name +'）';
            }
            marker.setLabel({
                direction:'top',
                offset: new AMap.Pixel(0, -2),  //设置文本标注偏移量
                content: label, //设置文本标注内容
            });
            // 设置中心点
            this.map.panTo(markerPos);

          }

        // }).catch((err) => {
        //   this.$notify({ type: "warning", message: "获取数据失败" });
        // });
    },
    /**
     * 历史轨迹
     */
    historyRoute() {
      if (!this.device_info.last_location) {
        this.$notify({type: 'warning', message: '暂无定位数据'});
        return;
      }
      if (!this.device_info.imei) {
        this.$notify({type: 'warning', message: '未获取到设备IMEI'})
        return;
      }

      this.$router.push({path: '/yys_route_search/'+this.device_info.imei});

      /* Dialog.confirm({
          title: '提醒', 
          message: '确定离开当前页面前往查看历史轨迹吗？',
      })
      .then(resp => {
        this.$router.push({path: '/yys_route_search/'+this.device_info.imei});
      }).catch(resp => {}) */

    },
    onSubmit(vals) {
      let data = {
        id: this.id,
        result: vals.result,
        comment: vals.comment,
      };

      // this.$http.post('handleAlarm&openid='+this.openid+'&userid='+this.userid, JSON.stringify(data))
      //   .then((resp) => {
      //     if (resp.status === 200 && resp.data && resp.data.success) {
      //       this.$notify({ type: "success", message: resp.data.message });
      //       this.$router.back();
      //     } else {
      //       this.$notify({ message: resp.data.message });
      //     }
      //   })
      //   .catch((err) => {
      //     this.$notify({ type: "warning", message: "出错了" });
      //   });
    },
  },
};
</script>
<style lang="scss" scoped>

#location-map {
  width: 100%;
  height: 200px;
}
/deep/ .amap-marker-label {
  border: 0;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.2);
}
</style>