<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>
    <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-btn" @click="setDeviceContorl('update_stm32')">主板升级</view>
            <view class="device-detail-btn" @click="setDeviceContorl('update')">物联网模块升级</view>
            <view class="device-detail-btn" @click="setDeviceContorl('reboot')">重启</view>
            <view class="device-detail-btn" @click="setDeviceContorl('test')">一键测试</view>
            <view class="device-detail-btn" @click="setDeviceContorl('yfwlw')">平台切换</view>
            <view class="device-detail-btn" @click="setDeviceContorl('paramconf1')">标配物联网</view>
            <view class="device-detail-btn" @click="setDeviceContorl('paramconf2')">物联网自清虫</view>
            <view class="device-detail-btn" @click="setDeviceContorl('paramconf3')">物联网光控</view>
            <view class="device-detail-btn" @click="setDeviceContorl('paramconf4')">物联网光控自清虫</view>
            <!-- <view class="device-detail-btn" @click="showMqttConfig">MQTT配置</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="showMqttConfig('imei')">更改IMEI</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 force-btn" @click="setDeviceContorl('takephoto')">拍照</view>
            <view class="device-detail-btn force-btn" @click="setDeviceContorl('update')">升级</view>
            <view class="device-detail-btn force-btn" @click="setDeviceContorl('reboot')">重启</view>
            <view class="device-detail-btn force-btn" @click="setDeviceContorl('autotakephoto')">对焦拍照</view>
            <view class="device-detail-btn force-btn" @click="setDeviceContorl('turn')">转仓</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" style="margin-left: 10rpx">
            设备编号
          </text>
          <view class="clear-btn">{{ equipContrlForm.imei || '-' }}</view>
        </view>
        <view class="device-detail-viewImage">
          <text class="device-detail-label" style="margin-left: 10rpx">
            设备名称
          </text>
          <view class="clear-btn">{{ equipContrlForm.device_name || '-' }}</view>
        </view> -->
        <view class="device-detail-viewImage">
          <text class="device-detail-label" style="margin-left: 10rpx">
            主板版本号
          </text>
          <view class="clear-btn">{{ equipContrlForm.stm8vs || '-' }}</view>
        </view>
        <view class="device-detail-viewImage">
          <text class="device-detail-label" style="margin-left: 10rpx">
            联网版本号
          </text>
          <view class="clear-btn">{{ equipContrlForm.dver || '-' }}</view>
        </view>
        <view class="device-detail-viewImage">
          <text class="device-detail-label" style="margin-left: 10rpx">
            设备开关
          </text>
          <u-switch
            v-model="equipContrlForm.ds"
            size="32"
            :active-value="1"
            :inactive-value="0"
            active-color="#0bbc58"
            style="position:absolute;right:0"
          ></u-switch>
        </view>
        <view class="device-detail-viewImage">
          <text class="device-detail-label" style="margin-left: 10rpx">
            定时模式
          </text>
          <view class="clear-btn" @click="timeSet('ts')">{{ equipContrlForm.ts === '0' ? '光控' : '时控' }}</view>
        </view>
        <view class="device-detail-viewImage" v-if="equipContrlForm.ts !== '1'">
          <u-icon name="clock" color="#0bbc58" size="46"></u-icon>
          <text class="device-detail-label" style="margin-left: 10rpx">
            定时时长(h)
          </text>
          <view class="clear-btn" @click="timeSetLang('tt')">{{ equipContrlForm.tt == '0'?'常亮':equipContrlForm.tt || '-' }}</view>
        </view>
        <view v-if="equipContrlForm.ts === '1'">
          <text class="device-detail-label" style="margin-left: 10rpx">
            开始结束时间
          </text>
        </view>
        <view class="time-container" v-if="equipContrlForm.ts === '1'">
          <view class="start-time" @click="showPickerHandler('start_time')">{{start_time_label || '开始时间'}}</view>-
          <view class="end-time" @click="showPickerHandler('end_time')">{{end_time_label || '结束时间'}}
          </view><u-icon name="clock" color="#4E5969" size="26" style="padding-right: 20rpx"></u-icon>
        </view>
        <view class="device-detail-viewImage">
          <text class="device-detail-label">数据间隔(min)
          {{ equipContrlForm.dattim }}</text>
        </view>
        <!-- <view class="slider-container">
          <view class="slider-min-value">50</view>
          <u-slider :value="equipContrlForm.dattim" @input="e => equipContrlForm.dattim = e" class="slider" :min="10" :max="120" active-color="#0bbc58"></u-slider>
          <view class="slider-max-value">70</view>
        </view> -->
        <view class="slider-container">
          <view class="slider-min-value">10</view>
          <view
            class="custom-progress"
            @touchstart.stop="onSliderTouchStart($event, 'dattim', 10, 120)"
            @touchmove.stop.prevent="onSliderTouchMove($event, 10, 120)"
            @touchend.stop="onSliderTouchEnd"
            @tap.stop="onSliderTap($event, 'dattim', 10, 120)"
          >
            <view class="progress-track">
              <view class="progress-fill" :style="{ width: getProgressWidth(equipContrlForm.dattim, 10, 120) + '%' }"></view>
              <view class="progress-thumb" :style="{ left: getProgressWidth(equipContrlForm.dattim, 10, 120) + '%' }"></view>
            </view>
          </view>
          <view class="slider-max-value">120</view>
        </view>
        <view class="device-detail-viewImage">
          <text class="device-detail-label">清虫间隔(min)
          {{ equipContrlForm.clt }}</text>
        </view>
        <!-- <view class="slider-container">
          <view class="slider-min-value">-30</view>
          <u-slider :value="equipContrlForm.clt" @input="e => equipContrlForm.clt = e" class="slider" :min="10" :max="120" active-color="#0bbc58"></u-slider>
          <view class="slider-max-value">20</view>
        </view> -->
        <view class="slider-container">
          <view class="slider-min-value">10</view>
          <view
            class="custom-progress"
            @touchstart.stop="onSliderTouchStart($event, 'clt', 10, 120)"
            @touchmove.stop.prevent="onSliderTouchMove($event, 10, 120)"
            @touchend.stop="onSliderTouchEnd"
            @tap.stop="onSliderTap($event, 'clt', 10, 120)"
          >
            <view class="progress-track">
              <view class="progress-fill" :style="{ width: getProgressWidth(equipContrlForm.clt, 10, 120) + '%' }"></view>
              <view class="progress-thumb" :style="{ left: getProgressWidth(equipContrlForm.clt, 10, 120) + '%' }"></view>
            </view>
          </view>
          <view class="slider-max-value">120</view>
        </view>
      </view>
    </view>
    <view class="device-detail-btn-footer" v-if="activeTab === 'viewImage'">
      <view class="device-detail-btn" @click="saveSettings">保存</view>
    </view>
    <u-popup v-model="show" mode="bottom">
      <view class="device-detail-content" style="height: 50vh">
        <view class="device-detail-item">
          <text class="device-detail-label">请输入imei</text>
          <u-input v-model="equipContrlForm.imei" placeholder="请输入imei"></u-input>
        </view>
      </view>
      <view class="device-detail-btn-footer">
        <view class="device-detail-btn" @click="setDeviceContorl('imei')">保存</view>
      </view>
		</u-popup>
		<u-select v-model="showPicker" :list="timeList" @confirm="confirmPicker"></u-select>
		<u-select v-model="showTimePicker" :list="list" @confirm="confirmTimePicker"></u-select>
		<u-select v-model="showTimeLangPicker" :list="list2" @confirm="confirmTimeLangPicker"></u-select>
  </view>
</template>
<script>

export default {
  data(){
    return {
      showPicker: false,
      value: 10,
      timeList: [],
      imageList: [],
      start_time_label: '',
      end_time_label: '',
      start_time: '',
      end_time: '',
      list: [{
        value: '0',
        label: '光控'
      },
      {
        value: '1',
        label: '时控'
      }],
      list2: [{
        value: '0',
        label: '常亮'
      },
      {
        value: '1',
        label: '1'
      },
      {
        value: '2',
        label: '2'
      },
      {
        value: '3',
        label: '3'
      },
      {
        value: '4',
        label: '4'
      },
      {
        value: '5',
        label: '5'
      },
      {
        value: '6',
        label: '6'
      },
      {
        value: '7',
        label: '7'
      }],
      coll_time:[{
        start_time: '',
        start_time_label: '',
        end_time: '',
        end_time_label: '',
      }],
      equipContrlForm: {
      },
      time: '',
      activeTab: 'pestAnalysis',
      title: '设置控制',
      deviceType: '',
      location: '',
      d_id: '',
      show: false,
      checked: false,
      showTimePicker: false,
      showTimeLangPicker: false,
      currentIndex: -1,
      myuser_type: false,
      currentType: ''
    }
  },
  onLoad(options){
    this.d_id = options.d_id;
    this.getControlDeviceConfigInfo();
    this.timeList = [];
    for(let i = 0;i<24;i++){
      this.timeList.push({
        value:i,
        label:i < 10 ? '0' + i + ':00' : i + ':00'
      })
    }
    uni.getStorage({
      key:"myuser_type",
      success:(res)=>{
        if(Number(res.data) == 1){
          this.myuser_type = true
          this.activeTab = 'pestAnalysis'
        }else{
          this.activeTab = 'viewImage'
        }
      }
    })
  },
  methods: {
    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)
    },
    confirmTimePicker(e){
      const value = e[0].value;
      this.equipContrlForm.ts = value;
    },
    confirmTimeLangPicker(e){
      const value = e[0].value;
      this.equipContrlForm.tt = value;
    },
    timeSet(){
      this.showTimePicker = true;
    },
    timeSetLang(type){
      this.showTimeLangPicker = true;
    },
    clearTime(){
      this.coll_time.forEach(item => {
        item.start_time = '';
        item.start_time_label = '';
        item.end_time = '';
        item.end_time_label = '';
      })
    },
    confirmPicker(e){
      const value = e[0].value;
      const label = e[0].label;
      if(this.currentType == 'start_time'){
        this.start_time_label = label
        this.start_time = value
      }else{
        this.end_time_label = label
        this.end_time = value
      }
    },
    showPickerHandler(type){
      this.currentType = type
      this.showPicker = true;
    },
    closePicker(){
      this.showPicker = false;
      this.currentType = ''
      this.currentIndex = -1
    },
    handleBack() {
      uni.navigateBack({
        delta: 1
      });
    },
    handleTabClick(tab) {
      this.activeTab = tab;
    },
    showMqttConfig(){
      this.show = true;
    },
    closeMqttConfig(){
      this.show = false;
    },
    async setDeviceContorl(cmd){
      this.$myRequest({
        url: '/api/api_gateway?method=forecast.send_control.admin_device_control',
        method: 'POST',
        data: {
          device_type_id: 2,
          d_id: this.d_id,
          cmd
        }
      }).then(res => {
        this.closeMqttConfig()
        if (res) {
          uni.showToast({
            title: '设备控制修改成功！',
            icon: 'success',
          });
        } else {
          uni.showToast({
            title: '设备控制修改失败',
            icon: 'error',
          });
        }
      });
    },
    saveSettings(){
      let newForm = Object.assign({}, this.equipContrlForm) // 深拷贝
      newForm.ds = newForm.ds ? 1 : 0
      newForm.st = this.start_time
      newForm.et = this.end_time
      this.$myRequest({
        url: '/api/api_gateway?method=forecast.send_control.device_control',
        method: 'POST',
        data: {
          device_type_id: 2,
          d_id: this.d_id,
          config: JSON.stringify(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=forecast.send_control.device_control_info',
        method: 'POST',
        data: {
          d_id: this.d_id,
          cmd:'paramconf'
        },
      });

      this.equipContrlForm = {
        st: res.st,
        et: res.et,
        ds: res.ds,
        ts: res.ts,
        tt: res.tt,
        dver: res.dver,
        dattim: res.dat_f,
        clt: res.clt_t,
        stm8vs: res.stm8vs
      };
      this.start_time = res?.st || ''
      this.end_time = res?.et || ''
      this.start_time_label = this.start_time >= 10 ? this.start_time + ':00' : '0' + this.start_time + ':00'
      this.end_time_label = this.end_time >= 10 ? this.end_time + ':00' : '0' + this.end_time + ':00'
      // const coll_time = res?.coll_time || [];
      // for(let i = 0;i< coll_time.length;i++){
      //   const coll_item = coll_time[i];
      //   const start_time = coll_item.split('-')[0];
      //   const end_time = coll_item.split('-')[1];
      //   this.coll_time[i]['start_time'] = start_time;
      //   this.coll_time[i]['end_time'] = end_time;
      //   this.coll_time[i]['start_time_label'] = start_time >= 10 ? start_time + ':00' : '0' + start_time + ':00';
      //   this.coll_time[i]['end_time_label'] = end_time >= 10 ? end_time + ':00' : '0' + end_time + ':00';
      // }
      // 确保值是数字类型，并且使用默认值时也要在合理范围内
    },
  }
}
</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;
    }
  }
  .time-container{
    display: flex;
    justify-content: center;
    align-items: center;
    color: #999999;
    border-radius: 8rpx;
    background:#F6F8FC;
    gap: 12rpx;
    .start-time{
      width: 250rpx;
      height: 50rpx;
      line-height: 50rpx;
      text-align: left;
      font-size: 24rpx;
      color: #999999;
      font-family: 'Source Han Sans CN VF';
      border-radius: 16rpx;
      padding: 0 24rpx;
    }
    .end-time{
      width: 200rpx;
      height: 50rpx;
      line-height: 50rpx;
      text-align: left;
      font-size: 24rpx;
      color: #999999;
      font-family: 'Source Han Sans CN VF';
      border-radius: 16rpx;
      padding: 0 24rpx;
    }
  }
  .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;
      color: #042118;
      font-family: 'Source Han Sans CN VF';
    }
    .tab-item {
      margin-right: 40rpx;
      color:#999999;
    }
    .active{
      position: relative;
      color: #0bbc58;
      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 #0bbc58;
      }
    }
  }
  .device-detail-content{
    display: flex;
    padding: 24rpx;
    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: grid;
        grid-template-columns: repeat(3, 1fr);
        gap: 24rpx;
        margin-top: 12rpx;
      }
      .device-detail-btn{
        display: flex;
        padding: 10rpx;
        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;
      align-items: center;
      padding-bottom: 20rpx;
      position: relative;
      .clear-btn{
        position: absolute;
        right: 0rpx;
        border-radius: 8rpx;
        padding: 4rpx 12rpx;
        font-size: 26rpx;
        font-family: 'Source Han Sans CN VF';
        font-weight: 400;
      }
    }
  }
  .slider-container{
    position: relative;
    margin-bottom: 20rpx;
    .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: 80rpx;
      width: 90%;
      margin: 0 auto;
      padding: 0rpx 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>