<template>
  <view class="container">

      <view class="header-image">

        <image style="width: 100%" :src="imgUrl+'/precharge/precharge.png'"/>
      </view>

      <view class="charge-type">

       <view class="charge-type-container">
         <view @click="changeType(0)" class="type-left" :class="chargeType == 0?'type-choose':''">单次</view>
         <view @click="changeType(1)" class="type-right" :class="chargeType == 1?'type-choose':''">自定义</view>
       </view>
      </view>

    <view class="time-area"  v-if="chargeType == 0">
      <!--      <view class="one-date">{{ oneTime.date }}</view>-->

      <view class="one-time">{{ oneTime.time }}</view>

      <view class="one-setting"><uni-datetime-picker @change="changeDate" v-model="oneTime.time" :hide-second	="true">选择时间</uni-datetime-picker></view>
    </view>


    <view class="time-area" style="padding-left:0px;padding-right: 0px"  v-if="chargeType == 1">
           <view style=";text-align: center;">
             <view class="one-date" style="display:inline-block;font-size: 12px;padding:0 2px" v-for="item in array">{{ item.name }}</view>
           </view>
      <view class="one-setting" @click="showChoose">选择重复日期</view>
      <view class="one-time">{{time}}</view>

      <picker mode="time" start="00:00" end="23:59" @change="bindTimeChange">
        <view class="one-setting">选择时间</view>
      </picker>
    </view>

    <view style="margin:5vh 7vw;">
      <button @click="saveConfig"  style="background: #0E9F9B;color: white;" type="default" >确认</button>
    </view>

    <uni-popup ref="popup" type="bottom">

      <view class="uni-list">
        <checkbox-group @change="checkboxChange">
          <label class="uni-list-cell uni-list-cell-pd" v-for="item in items" :key="item.value">
            <view style="width: 90%">{{item.name}}</view>
            <view>
              <checkbox :value="item.value" :checked="item.checked" />
            </view>
          </label>
        </checkbox-group>
        <view style="text-align: center">
          <button size="mini" @click="chooseDay" style="background: #1cbbb4;color: white;" type="default" >确认</button>
        </view>
      </view>


    </uni-popup>
  </view>
</template>

<script>
	import {save} from '@/api/device/plan.js'
export default {

  data() {
    return {
      deviceId: "",
      ccid:"",
	    repeatTime: '',
      cb:"",
      chargeType:0,
      oneTime:{
        time:"",
      },
      port:1,
      time:"",
      index:0,
      array: [],
      items: [{
        value: '7',
        name: '周日'
      },
        {
          value: '1',
          name: '周一',
        },
        {
          value: '2',
          name: '周二'
        },
        {
          value: '3',
          name: '周三'
        },
        {
          value: '4',
          name: '周四'
        },
        {
          value: '5',
          name: '周五'
        },
        {
          value: '6',
          name: '周六'
        }
      ]
    }
  },
  computed: {
    imgUrl: function () {
      return getApp().globalData.config.imgUrl;
    }
  },
  onLoad(opt){
    this.deviceId = opt.id;
    this.ccid = opt.ccid;
    this.port = opt.port;
  },
  methods: {
    chooseDay(){
      this.array = [];
      let items = this.items;
      for (var i = 0, lenI = items.length; i < lenI; ++i) {
        const item = items[i]
        if(item.checked){
          this.array.push(item)
        }
      }
      this.$refs.popup.close();
    },
    checkboxChange: function (e) {
      var items = this.items,
          values = e.detail.value;
      for (var i = 0, lenI = items.length; i < lenI; ++i) {
        const item = items[i]
        if(values.includes(item.value)){
          this.$set(item,'checked',true)
        }else{
          this.$set(item,'checked',false)
        }
      }
    },
    showChoose(){
      this.$refs.popup.open("center");
      var items = this.items;
      let values = [];
      for (let i = 0; i < this.array.length; i++) {
          let curItem = this.array[i];
          values.push(curItem.value);
      }
      for (var i = 0, lenI = items.length; i < lenI; ++i) {
        const item = items[i]
        if(values.includes(item.value)){
          this.$set(item,'checked',true)
        }else{
          this.$set(item,'checked',false)
        }
      }
    },
    bindTimeChange(e){
      let time = e.detail;
      this.time = time.value;
	    this.repeatTime = time.value;
    },
    open(){
      // 通过组件定义的ref调用uni-popup方法 ,如果传入参数 ，type 属性将失效 ，仅支持 ['top','left','bottom','right','center']
      this.$refs.popup.open('top')
    },
    changeDate(date){
      let hasMin =  date.split(":")
      let self = this;
      if(hasMin.length == 1){
       setTimeout(function(){
         date = date.trim();
         self.oneTime.time = date+" 00:00";
       },100);
      }
    },
    changeType(type){
      if(this.chargeType == type){
        return;
      }
      this.chargeType = type;
      this.array = [];
      this.time = "";
      this.oneTime.time = "";
    },
     async saveConfig() {
   		 // debugger
   // 		 const time = new Date(this.chargeType === 0 ? this.oneTime.time : this.time);
   // 		 const minute = time.getMinutes();
   // 		 time.setMinutes(minute + 1, 0, 0); // 将时间的秒数和毫秒数设置为 0，并将分钟数加 1。
   // 		 const repeatTime = time.toISOString(); // 将时间对象转换成 ISO 格式的字符串。
		 // const repeatTimeString = repeatTime.substring(0, repeatTime.length - 1); // 去除字符串末尾的 "Z" 字符。
   		  let runTime = null;
   		   if (this.chargeType === 0) {
   		     runTime = this.oneTime.time;
            if(!runTime){
              this.$modal.showToast("请设置时间");
              return;
            }
   		   }else{
            if(!this.repeatTime || this.array.length == 0){
              this.$modal.showToast("请设置重复时间");
              return;
            }
         }
             const params = {
                // createTime: new Date().toLocaleTimeString(),
                planType: this.chargeType === 0 ? 1 : 2, // 计划类型（单次或自定义）
                status: 1, // 状态（默认为未完成）
                runTime: runTime,
                repeatDays: this.chargeType === 1 ? this.array.map(item => item.value).join(',') : '',
                repeatTime: this.chargeType === 1 ?  this.repeatTime : '',
                deviceId: this.deviceId, // 设备 ID
                ccid:this.ccid
             };
        params.port = this.port;
   		  console.log(params);
          save(params).then(res => {
            this.$modal.loading("预约成功");
            setTimeout(()=>{
              uni.navigateBack();
            },1000)
            })
          },
     }
   }
</script>

<style>

.container{
  position: absolute;
  inset:0;
  background: rgb(249, 252, 255);
}
.header-image{
  width: 100%;
}
.charge-type{
  text-align: center;
  width: 100%;
  margin-top:2vh;
}
.charge-type-container{
  margin:0 20vw;
  border:1px solid #0E9F9B;
  border-radius: 2px;
}
.charge-type-container view{
  display: inline-block;
  padding:2vw;
  width: 50%;
  border-radius: 2px;

}
.type-left{

}
.type-choose{
  background: #0E9F9B;
  color:white;
}
.type-right{

}
.time-area{
  border: 1px solid #E6E6E6;
  border-radius: 10px;
  margin:0 11vh;
  margin-top:5vh;
  height: 25vh;
  text-align: center;
  padding: 8vw;
  line-height: 5vh;
}
.one-date{
  text-align: center;
  color: #0E9F9B;
}
.one-time{
  font-weight: bold;
  color: #0E9F9B;
  font-size: 24px;
}
.one-setting{
  font-weight: 400;
  color: #B2B2B2;
}
.uni-list-cell {
  justify-content: flex-start
}
.uni-list-cell{
  display: flex;
  flex-direction: row;
  padding:10px 10px

}
.uni-list{
  background:  rgb(249, 252, 255);
  width: 300px;
}
</style>
