<template>
  <div>
    <van-nav-bar title="我的车辆" left-text="返回" left-arrow @click-left="$router.replace('more')" />

    <div v-if="list.length">
      <van-cell-group v-for="item in list" :key="item.id">
        <van-cell :title="item.device_info.name" >
          <template #icon>
            <div style="padding-right:5px;display: flex;flex-direction: column;align-items: center;">
              <van-image
                  width="35px"
                  height="35px"
                  fit="fill"
                  round
                  :src="item.avatar || default_avatar"
              />
              <van-uploader :after-read="afterRead(item.imei)" :max-size="500 * 1024" @oversize="onOversize">
                <span style="font-size:10px;color:#2196f3">更换头像</span>
              </van-uploader>
            </div>
          </template>
          <template #default>
            <van-icon name="edit" @click="showUpdateDialog(item)" color="#03a9f4"></van-icon>
          </template>
          <template #label>
            <p>IMEI：{{item.device_info.imei}}</p>
          </template>
        </van-cell>

        <van-cell title="">
          <!-- <template #title>
            <div  class="loc-ways">
            <van-button type="primary" @click="showPopup(item)" size="mini">定位模式</van-button>
              <van-popup v-model="show" :style="{width:'80%'}" @close="close(dev_info)">
               <van-radio-group v-model="dev_info.pos_mode">
                <van-cell-group>
                  <van-cell v-for="mode in modes" :key="mode.value" :title="mode.text" clickable @click="choice_mode(mode)">
                    <template #right-icon>
                      <van-radio :name="mode.value"/>
                    </template>
                  </van-cell>
                  <van-field 
                    v-model="dev_info.stopped_rtc_invl"
                    type="digit" 
                    label="定位采样间隔"
                    required
                    placeholder="请输入采样间隔"
                    v-show="setTimeShow"
                    />
                  <van-field 
                    v-model="dev_info.stopped_rpt_invl" 
                    type="digit"
                    label="定位上报间隔"
                    required
                    placeholder="请输入上报间隔"
                    v-show="setTimeShow"
                  />
                  <van-button
                   type="primary" 
                   size="mini" 
                   v-show="setTimeShow" 
                   style="float:right;margin-right:20px"
                   @click="confirmSet(dev_info)"
                   >确认模式</van-button>
                </van-cell-group>
              </van-radio-group>
              </van-popup>
              <span class="custom-title">{{item.custom_title}}</span>
            </div>
          </template> -->

 
          <template #default>
            <van-button @click="goPage('buyInsure',{vehicle_info:item})" type="primary" size="small">购买保险</van-button>
            <van-button @click="showActionSheet(item)" type="info" size="small">车辆详情</van-button>
          </template>
        </van-cell>
      </van-cell-group>
    </div>
    <van-empty v-else description="暂无数据" />

    <!-- <div v-if="showBindBtn" class="fl-buttomright-button" @click="goPage('bindDevice')"> 绑定 </div> -->
    

    <van-dialog v-model="showDialog" title="修改信息" show-cancel-button @confirm="editName">
      <van-field v-model="device_name" label="设备名称" placeholder="请输入设备名称" />
    </van-dialog>
    <van-action-sheet v-model="showActions" title="车辆详情">
      <div class="content">
          <van-cell-group inset>
            <van-cell title="车牌号" :value="currentDeviceInfo.license_plate" />
            <van-cell title="所属部门" :value="currentDeviceInfo.department_name" />
            <van-cell title="开户时间" :value="currentDeviceInfo.license_time" />
            <van-cell title="开户员工" :value="currentDeviceInfo.creator" />
            <van-cell title="设备编号" :value="currentDeviceInfo.device_info.imei" />
            <van-cell title="定位模式" :value="currentDeviceInfo.device_info.loc_mode" />
         
           
            <!-- <van-cell title="单元格" value="内容" label="描述信息" /> -->
          </van-cell-group>
      </div>
    </van-action-sheet>
  </div>
</template>

<script type="text/babel">
import Vue from 'vue';
import { ActionSheet,Image as VanImage, Notify, NavBar, Tag, Icon, Dialog,Empty, CellGroup, Cell, Field ,Uploader,Popup,Button,RadioGroup, Radio,Toast} from 'vant';

Vue.use(ActionSheet);
Vue.use(NavBar);
Vue.use(Tag);
Vue.use(Icon);
Vue.use(Dialog);
Vue.use(Notify);
Vue.use(Empty);
Vue.use(CellGroup);
Vue.use(Cell);
Vue.use(Field);
Vue.use(Uploader);
Vue.use(VanImage);
Vue.use(Popup);
Vue.use(Button);
Vue.use(Radio);
Vue.use(RadioGroup);
Vue.use(Toast);
export default {
  data() {
    return {
      showBindBtn: true,
      list: [],
      showActions: false,
      showDialog: false, // 显示修改设备名称dialog
      currentDeviceInfo: {
        device_info:{},
      }, // 当前设备信息
      device_name: '', // 设备名称
      userid: null,
      openid: null,
      default_avatar: '/static/avatar_default.png',
      deviceAvatar: '',
      actions: [{ 
          name: '解除绑定', 
          action: 'unbind',
        },
        /* { 
          name: '补卡',
          action: 'makeupCard',
        } */
        ],
      show: false,

      // custom_title:'定位模式',
      // pos_mode: '',
      // stopped_rtc_invl:'',
      // stopped_rpt_invl:'',
      dev_info:{},
      modes:[
        {
          value:'0',
          text:'常规模式'
        },
          {
          value:'1',
          text:'追踪模式'
        },
          {
          value:'2',
          text:'定时模式'
        }
      ],
    };
  },
  created() {
    this.userid = localStorage.getItem("userid");
    this.openid = localStorage.getItem("openid");
    this.userType = localStorage.getItem('userType');
    this.deviceType = localStorage.getItem('deviceType');

    if (this.userType == 'group' && this.deviceType == 'card') {
        this.showBindBtn = false;
    }
    //  let mode_config = JSON.parse(localStorage.getItem('mode_config_*'));
    //  console.log(mode_config);
    //      this.custom_title = mode_config.text
    //      if(mode_config.value == '2'){
    //        if(mode_config.stopped_rtc_invl != 'undefind'){
    //           this.stopped_rtc_invl = mode_config.stopped_rtc_invl
    //        }
    //        if(mode_config.stopped_rpt_invl != 'undefind'){
    //           this.stopped_rpt_invl = mode_config.stopped_rpt_invl
    //        }
    //        this.setTimeShow = true
    //      }
    this.getList();
  },
  methods: {
    /**
     * 显示修改设备dialog
     */
    showUpdateDialog(info) {
      this.showDialog = true;
      this.device_name = info.device_info.name;
      this.currentDeviceInfo = info;
    },
     showPopup(info) {
      //  console.log(info);
        this.dev_info = info.device_info
        this.show = true;
        let mode_config = JSON.parse(localStorage.getItem('mode_config_'+this.dev_info.imei));
        if(mode_config){
          this.dev_info.pos_mode = mode_config.value
          this.dev_info.custom_title = mode_config.text
          if(mode_config.value == '2'){
              if(mode_config.stopped_rtc_invl != 'undefind'){
                this.dev_info.stopped_rtc_invl = mode_config.stopped_rtc_invl
              }
              if(mode_config.stopped_rpt_invl != 'undefind'){
                this.dev_info.stopped_rpt_invl = mode_config.stopped_rpt_invl
              }
              this.setTimeShow = true
          }
        }
    },
    close(info){
      let config = JSON.parse(localStorage.getItem('mode_config_' + info.imei))
      if(config){
        if(info.pos_mode != config.value){
          this.dev_info.pos_mode = config.value
          this.dev_info.custom_title = config.text
        }
      }
      this.setTimeShow = false
    },
    choice_mode(mode){
        this.dev_info.pos_mode = mode.value
        this.dev_info.custom_title = mode.text
        console.log(mode);
        if(mode.value == '2'){//定时模式
          this.setTimeShow = true
        }else{
          //下发配置
          
          let data = {
            id:this.dev_info.id,
            imei:this.dev_info.imei,
            pos_mode:this.dev_info.pos_mode
          }
          if(this.sendMode(data)){
             //关闭弹窗
            this.show = false
          }
          
          this.dev_info.setTimeShow = false
          localStorage.setItem('mode_config_'+this.dev_info.imei, JSON.stringify(mode));
        }
        
    },
    confirmSet(info){
      // console.log(info);
      if(!info.stopped_rtc_invl){
        Toast.fail('采样间隔不能为空');
        return
      }
      if(info.stopped_rtc_invl<300){
        Toast.fail('采样间隔不能小于300秒');
        return
      }
      if(!info.stopped_rpt_invl){
        Toast.fail('上报间隔不能为空');
        return
      }
       if(info.stopped_rpt_invl<300){
        Toast.fail('上报间隔不能小于300秒');
        return
      }
       //下发配置
      let data = {
        id:info.id,
        imei:info.imei,
        pos_mode:info.pos_mode,
        stopped_rpt_invl:info.stopped_rpt_invl,
        stopped_rtc_invl:info.stopped_rtc_invl
      }
      if(this.sendMode(data)){
       //关闭弹窗
       this.show = false
      }
      let mode_config = {
         value:'2',
         text:'定时模式',
         stopped_rtc_invl:info.stopped_rtc_invl,
         stopped_rpt_invl:info.stopped_rpt_invl
       }
       localStorage.setItem('mode_config_'+this.dev_info.imei, JSON.stringify(mode_config));
    },
    sendMode(params){
      return this.$http.post('setLocModel&userid=' + this.userid + '&openid=' + this.openid, JSON.stringify(params))
          .then(resp => {
            if (!resp.data.success) {
              this.$notify(resp.data.message || '切换失败');
              return false
            }
            this.$notify({
              type: 'success',
              message: resp.data.message || '切换成功',
            })
            return true
          })
    },
    /**
     * 修改设备名称
     */
    editName() {
      let device_name = this.device_name.trim();
      if (device_name === '') {
        this.$notify('设备名称不能为空')
        return;
      }
      
      let postData = {
        device_id: this.currentDeviceInfo.id,
        device_name: device_name,
      }
      this.$http.post('updateDeviceInfo&userid=' + this.userid + '&openid=' + this.openid, JSON.stringify(postData))
          .then(resp => {
            if (!resp.data.success) {
              this.$notify(resp.data.message || '修改失败');
              return;
            }
            this.$notify({
              type: 'success',
              message: resp.data.message || '修改成功',
            })

            this.getList();
          })
    },
    /**
     * 解绑之前
     */
    beforeUnbindDevice(info) {
      Dialog.confirm({
        title: '提醒',
        message: '确定要解绑设备吗？',
      })
      .then(resp => {
        this.unbindDevice(info);
      }).catch(()=>{})
    },
    /**
     * 解绑设备
     */
    unbindDevice(info) {
      let postData = {
        device_id: info.id,
      }
      this.$http.post('userUnbindDevice&userid=' + this.userid + '&openid=' + this.openid, JSON.stringify(postData))
          .then(resp => {
            if (!resp.data.success) {
              this.$notify(resp.data.message || '解绑失败');
              return;
            }
            this.$notify({
              type: 'success',
              message: resp.data.message || '解绑成功',
            })

            this.getList();
          })
    },
    /**
     * 获取设备列表
     */
    getList() {

      this.$http.get("/getMyDevices&userid=" + this.userid + '&openid=' + this.openid)
        .then(res => {
          if (!res.data.success) {
            this.$notify(res.data.message || '获取失败');
            return;
          }

          this.list = res.data.data || [];
          // Object.keys(this.list).forEach(key => {
         
          //   let mode_config = JSON.parse(localStorage.getItem('mode_config_'+this.list[key].device_info.imei))
          //   if(mode_config){
          //   this.list[key].pos_mode = mode_config.value
          //   this.list[key].custom_title = mode_config.text
          //    if(mode_config.value == '2'){
          //       if(mode_config.stopped_rtc_invl != 'undefind'){
          //          this.list[key].stopped_rtc_invl = mode_config.stopped_rtc_invl
          //       }
          //       if(mode_config.stopped_rpt_invl != 'undefind'){
          //           this.list[key].stopped_rpt_invl = mode_config.stopped_rpt_invl
          //       }
          //       this.list[key].setTimeShow = true
          //    }else{
          //      this.list[key].setTimeShow = false
          //    }
          //   }
          // })
          // console.log(this.list);
        })
        .catch(res => {
            this.$notify('出错了');
        });
    },
    /**
     * 跳转绑定设备页面
     */
    goPage(name, query = {}){
      this.$router.push({name: name, query: query});
    },

    afterRead(imei){

        return file =>{
        
          let that= this;
          console.log(file)
          console.log(imei)
          let postData = {
              imei: imei,
              avatar64content: file.content
          }
          that.$http({
              method: "post",
              url: "/saveDeviceAvatar",
              data: JSON.stringify(postData) ,
              })
          .then(({ data }) => {
              that.getList()
              console.log(data, 'save res');
          });
        }

    },
    onOversize(file){
        Dialog({ message: "头像勿超过500KB"});
    },
    /**
     * 显示选项
     */
    showActionSheet(info) {
      this.showActions = true;
      this.currentDeviceInfo = info;
      console.log(this.currentDeviceInfo)
    },
    // 选中action
    onSelect(item) {
      let action = item.action

      if (action == 'unbind') { // 解绑
        this.beforeUnbindDevice(this.currentDeviceInfo);
      }
      
    },
  }
};
</script>
<style scoped="less">
.fl-buttomright-button{
  position: fixed;
  bottom: 24px;
  right: 16px;
  display: flex;
  flex-direction: column;
  border-radius: 50%;
  height: 54px;
  width: 54px;
  background-color: #2196f3;
  box-shadow:0 0 6px gray ;
  font-size: 14px;
  justify-content: center;
  align-items: center;
  color: white;
  padding: 12px;
}
.loc-ways{
  display:flex;
}
.custom-title{
  margin-left:10px;
  color:#06a2edfc;
  font-size: 12px;
}
</style>