<template>
  <view class="device-detail">
    <view class="device-detail__header">
      <u-icon
        size="36"
        class="arrow-left"
        name="arrow-left"
        @click="handleBack"
      ></u-icon>
      {{ title }}
    </view>
		<u-select v-model="show" :list="list" @confirm="confirmHandler"></u-select>
    <view class="device-detail__body">
      <view class="tabs">
        <view class="tab-container">
          <view class="tab-item" v-if="myuser_type" :class="activeTab === 'pestAnalysis'?'active':''" @click="handleTabClick('pestAnalysis')">
            管理员
          </view>
          <view class="tab-item" :class="activeTab === 'viewImage'?'active':''" @click="handleTabClick('viewImage')">
            设置
          </view>
        </view>
      </view>
      <view class="device-detail-content" v-if="activeTab === 'pestAnalysis'">
        <view class="device-detail-item">
          <text class="device-detail-label">识别种类</text>
          <view class="device-detail-btn-container">
            <view class="device-detail-btns" @click="show2 = true" size="mini">{{getSelectPest(selectPest)}}</view>
            <view class="device-detail-btn" @click="setBindPest">{{selectPest.pest_id == '' ? '恢复默认' : '绑定设备'}}</view>
          </view>
        </view>
        <view class="device-detail-item">
          <text class="device-detail-label">联网模块</text>
          <view class="device-detail-btn-container">
            <view class="device-detail-btn" @click="setDeviceContorl('reboot')">数据单元重启</view>
            <view class="device-detail-btn" @click="setDeviceContorl('upgradeApp')">数据单元升级</view>
          </view>
        </view>
        <view class="device-detail-item">
          <text class="device-detail-label">设备操作</text>
          <view class="device-detail-btn-container">
            <view class="device-detail-btn" @click="setDeviceContorl('takephoto')">测试拍照</view>
            <view class="device-detail-btn" @click="setDeviceContorl('getLocation')">获取定位</view>
          </view>
        </view>
      </view>
      <view class="device-detail-content" style="padding-bottom: 50rpx" v-if="activeTab === 'viewImage'">
        <view class="device-detail-viewImage">
          <text class="device-detail-label">拍照频率(min):</text>
            <u-input
              v-model="equipContrlForm.takePhotoIntervalMinutes"
              type="number"
              :border="false"
              height="40"
              style="width: 100rpx"
              auto-height="true"
              input-align="right"
            />
        </view>
        <view class="device-detail-viewImage">
          <text class="device-detail-label">控制模式:</text>
          <text @click="show = true">{{ formatCtrlMode(equipContrlForm.ctrlMode) }}</text>
        </view>
        <view class="device-detail-viewImage">
          <text class="device-detail-label">时控时长:</text>
          <text @click="show1 = true">{{ fromTime(equipContrlForm.startHour) }} - {{ fromTime(equipContrlForm.endHour) }}</text>
        </view>
      </view>
    </view>
    <view class="device-detail-btn-footer" v-if="activeTab === 'viewImage'">
      <view class="device-detail-btn" @click="saveSettings">保存</view>
    </view>
	  <u-select v-model="show1" mode="mutil-column" :list="list2" @confirm="confirmDateHandler"></u-select>
	  <u-select v-model="show2" :list="list3" @confirm="confirmDateHandler2"></u-select>
  </view>
</template>
<script>

export default {
  data(){
    return {
      show: false,
      show1: false,
      show2: false,
      list2:[],
      list3:[],
      list: [
        { value: '0', label: '光控模式' },
        { value: '1', label: '时控模式' },
      ],
      selectPest: {},
      value: 10,
      cmd1: '0001',
      imageList: [],
      equipContrlForm: {},
      time: '',
      activeTab: 'pestAnalysis',
      title: '设置控制',
      deviceType: '',
      location: '',
      d_id: '',
      checked: false,
      sliderField: '',
      sliderMin: 0,
      sliderMax: 100,
      myuser_type: false,
      sliderRect: null
    }
  },
  onLoad(options){
    this.d_id = options.d_id
    const time1 = [];
    const time2 = [];
    for(let i = 0;i< 24;i++){
      let j = i;
      if(i < 10){
        j = '0' + i
      }
      time1.push({
        value: i,
        label: j + ':00'
      })
      time2.push({
        value: i,
        label: j + ':00'
      })
    }
    uni.getStorage({
      key:"myuser_type",
      success:(res)=>{
        if(Number(res.data) == 1){
          this.myuser_type = true
          this.activeTab = 'pestAnalysis'
        }else{
          this.activeTab = 'viewImage'
        }
      }
    })
    this.list2 = [time1, time2];
    this.deviceType = options.device_type
    this.getControlDeviceConfigInfo()
    this.getFollowPest()
    this.getAllPestList()
  },
  methods: {
    getSelectPest(selectPest){
      if(selectPest?.pest_name == '清空' || !selectPest?.pest_name){
        return '请选择识别种类'
      }else{
        return selectPest.pest_name
      }
    },
    async getAllPestList() {
      const res = await this.$myRequest({
        url: '/api/api_gateway?method=forecast.pest_info.pest_dict',
        data: {
          type_name: 1
        }
      })
      const pestList = [];
      for(let pest in res){
        pestList.push({
          value: pest,
          label: res[pest]
        })
      }
      pestList.unshift({
        value: '',
        label: '清空'
      })
      this.list3 = pestList
    },
    formatCtrlMode(ctrlMode){
      if(ctrlMode == 1){
        return '时控模式'
      }else if(ctrlMode == 0){
        return '光控模式'
      }
      return '请选择控制模式'
    },
    getProgressWidth(value, min, max) {
      if (max === min) return 0
      return ((value - min) / (max - min)) * 100
    },
    onSliderTouchStart(e, field, min, max) {
      this.sliderField = field
      this.sliderMin = min
      this.sliderMax = max
      const query = uni.createSelectorQuery().in(this)
      query.select('.custom-progress').boundingClientRect(rect => {
        this.sliderRect = rect
      }).exec()
      this.updateSliderValue(e.touches[0].clientX, field, min, max)
    },
    onSliderTouchMove(e, min, max) {
      if (!this.sliderField || !this.sliderRect) return
      this.updateSliderValue(e.touches[0].clientX, this.sliderField, min, max)
    },
    onSliderTouchEnd() {
      this.sliderField = ''
    },
    onSliderTap(e, field, min, max) {
      const query = uni.createSelectorQuery().in(this)
      query.select('.custom-progress').boundingClientRect(rect => {
        this.sliderRect = rect
        this.updateSliderValue(e.detail.x + rect.left, field, min, max)
      }).exec()
    },
    updateSliderValue(clientX, field, min, max) {
      if (!this.sliderRect) return
      let ratio = (clientX - this.sliderRect.left) / this.sliderRect.width
      ratio = Math.max(0, Math.min(1, ratio))
      const value = Math.round(min + ratio * (max - min))
      this.$set(this.equipContrlForm, field, value)
    },
    fromTime(time){
      if(time < 10){
        time = '0' + time + ':00'
      }else{
        time = time + ':00'
      }
      return time
    },
    confirmDateHandler2(e){
      console.log(e,'e')
      this.show2 = false
      this.selectPest.pest_id = e[0].value
      this.selectPest.pest_name = e[0].label
    },
    confirmDateHandler(e){
      console.log(e,'e')
      this.show1 = false
      this.equipContrlForm.startHour = e[0].value
      this.equipContrlForm.endHour = e[1].value
    },
    confirmHandler(item){
      this.equipContrlForm.ctrlMode = item[0].value
    },
    formart(cmd1){
      let text = ''
      this.list.forEach(item => {
        if(item.value === cmd1){
          text = item.label
        }
      })
      return text
    },
    handleBack() {
      uni.navigateBack({
        delta: 1
      });
    },
    handleTabClick(tab) {
      this.activeTab = tab;
    },
    async getFollowPest(){
      const res = await this.$myRequest({
        url: '/api/api_gateway?method=forecast.new_cbd.get_follow_pest',
        data: {
          d_id: this.d_id,
        }
      })
      if (res) {
        this.selectPest = res?.pest_list[0] || {}
      } else {
        this.showToast({
          title: '获取绑定设备失败',
          icon: 'error',
        });
      }
    },
    setBindPest(){
      let pest_data = {}
      if(this.selectPest.pest_id){
        pest_data = JSON.stringify([{
          pest_id: this.selectPest.pest_id,
          pest_name: this.selectPest.pest_name,
        }]);
      }else{
        pest_data = ''
      }
      const data = {
        d_id: this.d_id,
        disable: 0,
        pest_data
      }
      this.$myRequest({
        url: '/api/api_gateway?method=forecast.new_cbd.modify_follow_pest',
        method: 'POST',
        data
      }).then(res => {
        if (res) {
          uni.showToast({
            title: '绑定设备成功！',
            icon: 'success',
          });
        } else {
          uni.showToast({
            title: '绑定设备失败',
            icon: 'error',
          });
        }
      })
    },
    async setDeviceContorl(type){
      const data = {
        device_type_id: this.deviceType,
        d_id: this.d_id,
        cmd: type,
      }
      if(type === 'imei'){
        data.imei = this.equipContrlForm.imei
      }else{
        delete data.imei
      }
      this.$myRequest({
        url: '/api/api_gateway?method=forecast.send_control.admin_device_control',
        method: 'POST',
        data
      }).then(res => {
        if (res) {
          uni.showToast({
            title: '设备控制修改成功！',
            icon: 'success',
          });
        } else {
          uni.showToast({
            title: '设备控制修改失败',
            icon: 'error',
          });
        }
      });
    },
    saveSettings(){
      let newForm = Object.assign({}, this.equipContrlForm) // 深拷贝
      this.$myRequest({
        url: '/api/api_gateway?method=new_gateway.device_info.update_device_config',
        method: 'POST',
        data: {
          device_type_id: this.deviceType,
          id: this.d_id,
          ...newForm,
        }
      }).then(res => {
        if (res) {
          // 设备控制修改成功
          uni.showToast({
            title: '设备控制修改成功！',
            icon: 'success',
          });
        } else {
          uni.showToast({
            title: '设备控制修改失败',
            icon: 'error',
          });
        }
      })
    },
    async getControlDeviceConfigInfo(){
      const res = await this.$myRequest({
        url: '/api/api_gateway?method=new_gateway.device_info.get_device_config',
        method: 'POST',
        data: {
          device_type_id: this.deviceType,
          id: this.d_id,
        },
      });
      console.log(res,'resresres')
      if(!res?.startHour){
        res.startHour = '0'
      }
      if(!res?.endHour){
        res.endHour = '0'
      }
      this.equipContrlForm = res
    },
  }
}
</script>
<style scoped lang="scss">
.device-detail {
  display: flex;
  width: 100%;
  height: calc(100vh - 112rpx);
  padding-top: 112rpx;
  flex-direction: column;
  align-items: center;
  background: linear-gradient(180deg, #ffffff00 0%, #F5F6FA 23.64%, #F5F6FA 100%), linear-gradient(102deg, #BFEADD 6.77%, #B8F1E7 40.15%, #B9EEF5 84.02%);
  .device-detail__header {
    width: 100%;
    font-size: 28rpx;
    color: #999;
    color: #042118;
    font-family: 'Source Han Sans CN VF';
    font-weight: 700;
    position: relative;
    text-align: center;
    .arrow-left {
      position: absolute;
      left: 32rpx;
      margin-right: 12rpx;
    }
  }
  .device-detail__body {
    width: calc(100% - 64rpx);
    margin: 0 auto;
    border-radius: 16rpx;
    overflow-x: hidden;
    overflow-y: auto;
    // 隐藏滚动条
    -ms-overflow-style: none;
    scrollbar-width: none;
  }
  .tabs {
    margin: 24rpx 0;
    border-radius: 16rpx;
    padding: 16rpx 0;
    padding-top: 0;
    .tab-container{
      display: flex;
      width: 100%;
      height: 88rpx;
      line-height: 88rpx;
      text-align: center;
      font-size: 28rpx;
      font-weight: 700;
      color: #042118;
      font-family: 'Source Han Sans CN VF';
    }
    .tab-item {
      margin-right: 40rpx;
      color:#999999;
    }
    .active{
      position: relative;
      color: #303133;
      text-align: center;
      font-family: "Source Han Sans CN VF";
      font-size: 28rpx;
      font-weight: 700;
      &::after {
        content: '';
        position: absolute;
        bottom: 10rpx;
        left: 50%;
        transform: translateX(-50%);
        width: 100%;
        height: 36rpx;
        border-bottom: 6rpx solid #303133;
      }
    }
  }
  .device-detail-content{
    display: flex;
    padding: 24rpx 32rpx;
    flex-direction: column;
    align-items: flex-start;
    gap: 20rpx;
    border-radius: 16rpx;
    background: #FFF;
    .device-detail-item{
      .device-detail-label{
        color: #303133;
        font-family: "Source Han Sans CN VF";
        font-size: 28rpx;
        font-weight: 400;
      }
      .device-detail-btn-container{
        display: flex;
        gap: 24rpx;
        margin-top: 12rpx;
      }
      .device-detail-btns{
        display: flex;
        padding: 16rpx 24rpx;
        justify-content: center;
        align-items: center;
        gap: 16rpx;
        border: 1rpx solid #0BBC58;
        border-radius: 16rpx;
        color: #0BBC58;
        font-family: "Source Han Sans CN VF";
        font-size: 24rpx;
        font-weight: 400;
      }
      .device-detail-btn{
        display: flex;
        padding: 16rpx 24rpx;
        justify-content: center;
        align-items: center;
        gap: 16rpx;
        border-radius: 16rpx;
        background: #0BBC58;
        color: #ffffff;
        font-family: "Source Han Sans CN VF";
        font-size: 24rpx;
        font-weight: 400;
      }
      .force-btn{
        background: #FB4E52;
      }
    }
    .device-detail-viewImage{
      width: 100%;
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding-bottom: 20rpx;
    }
  }
  .slider-container{
    position: relative;
    margin: 10rpx 0 20rpx 0;
    .slider-min-value{
      position: absolute;
      left: 0;
      top: -50rpx;
    }
    .slider{
      width: 600rpx;
    }
    .slider-max-value{
      position: absolute;
      right: 0;
      top: -50rpx;
    }
  }
  .custom-progress{
    width: 600rpx;
    padding: 0;
    .progress-track{
      position: relative;
      height: 12rpx;
      background-color: #ebedf0;
      border-radius: 6rpx;
    }
    .progress-fill{
      position: absolute;
      left: 0;
      top: 0;
      height: 100%;
      background-color: #0BBC58;
      border-radius: 6rpx;
      transition: width 0.2s;
    }
    .progress-thumb{
      position: absolute;
      top: 50%;
      width: 28rpx;
      height: 28rpx;
      margin-left: -14rpx;
      margin-top: -14rpx;
      border-radius: 50%;
      background-color: #fff;
      box-shadow: 0 1px 4px rgba(0,0,0,0.3);
      transition: left 0.2s;
    }
  }
  .device-detail-btn-footer{
    position: fixed;
    bottom: 0;
    left: 0;
    width: 100%;
    height: 112rpx;
    line-height: 112rpx;
    text-align: center;
    font-size: 28rpx;
    font-weight: 700;
    color: #042118;
    font-family: 'Source Han Sans CN VF';
    background: #ffffff;
    display: flex;
    justify-content: center;
    align-items: center;
    .device-detail-btn{
      display: flex;
      height: 100rpx;
      width: 90%;
      margin: 0 auto;
      padding: 10rpx 20rpx;
      justify-content: center;
      align-items: center;
      gap: 8rpx;
      border-radius: 16rpx;
      background:#0BBC58;
      color: #ffffff;
      text-align: center;
      font-family: "Source Han Sans CN VF";
      font-size: 14px;
      font-style: normal;
      font-weight: 500;
    }
  }
}
</style>