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

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

    <van-cell-group title="">
      <van-field
        v-model="device_info.name"
        label="设备名称"
        readonly
        input-align="right"
      />
       <van-field
        v-model="device_info.fixed_asset_number"
        label="资产编号"
        readonly
        input-align="right"
      />
      <van-field
        v-model="device_info.imei"
        v-show="isshow"
        label="设备IMEI"
        readonly
        input-align="right"
      />
      <van-field
        v-model="device_info.device_type"
        label="设备分类"
        readonly
        input-align="right"
      />
       <van-field
        v-model="device_info.status_name"
        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.online_time"
        label="最后在线时间"
        readonly
        input-align="right"
        v-show="isshow"
      />
      <van-field
        v-model="device_info.check_last_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" v-show="isshow"
      >
        <template #input>
          <span style="color:blue;" @click="historyRoute">点击查看</span>
        </template>
      </van-field>
    </van-cell-group>
    <van-divider>文件上传</van-divider>
        <van-cell-group title="">
          <van-uploader
              :after-read="afterRead"
              :before-read="beforeRead"
              @delete="deletePreview"
              v-model="fileList"
          
            accept="txt/pdf/xlsx/xls/mp4/mp3/jpg/png/gif/jpeg/zip/7z/rar/docx/doc"
          />
     

    </van-cell-group>

    <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,
  Uploader
} 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);
Vue.use(Uploader);
export default {
  data() {
    return {
      id: null, // 告警id
      isshow:false,//是不是泵  如果是泵就展示 而 不展示
      device_info: {}, // 设备信息
      uploadFile:"",
      handleResult: "1",
      comment: "",
      handleTime: '',
      userid: null,
      // 地图
      map: null,
      fileList: [],
      files: [],
    };
  },
  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('地图数据初始化出错，请刷新重试');
          
            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) {
              
                reject(false);
            }
        });
    },
    // 获取告警详情
    getDetail() {
      let url = 'getEquipment?openid='+this.openid+'&userid='+this.userid+'&id='+this.id;
  
       this.$http.get(url).then((resp) => {
          if (resp.data.code !== 10000 || !resp.data) {
            this.$notify(resp.data.message || '获取数据失败，请刷新页面重试')
            return;
          }
          this.device_info = resp.data.data || {};

         this.comment = this.device_info.comment || '';
         if (this.device_info.equipment_type == 2)
         {
           this.isshow = true;
         }

         if (this.device_info.equipment_type == 2) {
          // let location = this.device_info.last_location.split(',');
            // 添加坐标点
            let markerPos = new AMap.LngLat(this.device_info.longitude, this.device_info.latitude);
            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.factory_number;
            if (this.device_info.name) {
              label = label + '（' + this.device_info.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.equipment_type != 2) {
        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.factory_number});

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

    },
    onSubmit(vals) {
      let data = {
        eq_id: this.device_info.id,
        fileList:this.files
      };
    
      if (this.files.length==0)
      {
       
        this.$notify({ type: "warning", message: "请上传文件" });
        return false;
      }
      //提交上传的文件
      this.$http.post('saveUploadFile?openid='+this.openid+'&userid='+this.userid, JSON.stringify(data))
        .then((resp) => {
          if (resp.data.code == 10000) {
            this.$notify({ type: "success", message: '上传成功' });
            this.fileList = [];
            this.files = [];
           // this.$router.back();
          } else {
            this.$notify({ message: resp.data.message });
          }
        })
        .catch((err) => {
          this.$notify({ type: "warning", message: "出错了" });
        });
    },

    beforeRead(file) {	//上传之前校验
 
      if (file.size>4*1024*1024) {
        this.$notify({ type: "warning", message: "文件不能超过4M" });
        return false
      }
      return true
    },
    async afterRead(file) {	//文件读取完成后的回调函数
      let uploadImg = await this.upLoaderImg(file.file)//使用上传的方法。file.file
     
    },
    //删除预览图
    deletePreview(file,res)
    {
      this.files.splice(res.index,1);
    },

  upLoaderImg(file) {	//file为 你读取成功的回调文件信息
  //new 一个FormData格式的参数
  let params = new FormData()
  params.append('file', file)
  let config = {
    headers: { //添加请求头
      'Content-Type': 'multipart/form-data'
    }
  }
  return new Promise((resolve, reject) => {
    //把 uploadUrl 换成自己的 上传路径
    this.$http.post('uploadFile?openid=' + this.openid + '&userid=' + this.userid, params, config).then(res => {
      if (res.data.code == 10000) {
        this.files.push(res.data.data);
        
        resolve(res.data)
      } else {
        //否则 Toast 提示
        this.$notify({ type: "warning", message: res.data.message });
        reject(res.data)
      }
    }).catch(err => {
      this.$notify({ type: "warning", message: "上传异常" });
      reject(err)
    });
  })
}


  },
};
</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>