<template>
  <view class="page">
    <BackBar title="时间管控" />
    <view class="content">
      <view v-for="(item, index) in cellData" :key="index" class="cell">
        <view class="top-cont">
          <view class="title">{{ item.name }}</view>
          <view
            ><wd-switch
              v-model="item.show"
              size="24px"
              active-color="#615DFF"
              @change="val => changeSwicth(val, item)"
          /></view>
        </view>
        <view class="tips">{{ item.tips }}</view>
        <view v-if="item.show" class="showContent">
          <view
            v-for="(item2, index2) in item.list"
            :key="index2"
            class="item"
            @click.capture="itemFun(item2, index, index2)"
          >
            <text class="itemKey">{{ item2.name }}</text>
            <view class="itemVal">
              <view>{{
                item2.val
                  ? item2.name.includes('重复')
                    ? item2.val.replace(/、/g, ' ')
                    : item2.val
                  : `请选择${item2.placeholderText}`
              }}</view>
            </view>
            <wd-icon name="arrow-right" size="20px"></wd-icon>
          </view>
        </view>
      </view>
    </view>
    <view v-if="cellData[0].show || cellData[1].show" class="footer">
      <view
        :class="{ submit: true, disabledBtn: disabled, activeBtn: !disabled }"
        @click="SubmitFun()"
      >
        提交
      </view>
    </view>
    <!-- 开始结束时间 -->
    <wd-popup
      v-model="pickerShow"
      safe-area-inset-bottom
      position="bottom"
      custom-style="padding: 15px 15px; border-radius: 20px 20px 0 0;"
      @close="cancelTimeSlotShow('time')"
    >
      <view class="popuTitle">{{ timePopupTitle }}</view>
      <view class="time_picker">
        <wd-datetime-picker-view
          v-if="timePopupTitle.includes('开始')"
          v-model="startTime"
          type="time"
          label="时分"
        />
        <wd-datetime-picker-view
          v-if="timePopupTitle.includes('结束')"
          v-model="endTime"
          type="time"
          label="时分"
        />
        <view class="colon">:</view>
      </view>
      <view class="buttonCont">
        <button class="butClos" @click="cancelTimeSlotShow('time')">取消</button>
        <button class="sub" @click="subFun">确定</button>
      </view>
    </wd-popup>

    <!-- 重复 -->
    <wd-popup
      v-model="repeatShow"
      safe-area-inset-bottom
      position="bottom"
      custom-style="padding: 15px 15px; border-radius: 20px 20px 0 0;"
      @close="repeatClose"
    >
      <view class="popuTitle">选择重复日</view>
      <wd-checkbox-group v-model="dayOfWeekVal">
        <wd-cell
          v-for="(item, index) in dayOfWeekList"
          :key="index"
          inline
          :title="item.name"
          center
          clickable
          class="week_cell"
        >
          <view>
            <wd-checkbox
              ref="checkBox1"
              :model-value="item.val"
              shape="square"
              checked-color="#615DFF"
            ></wd-checkbox>
          </view>
        </wd-cell>
      </wd-checkbox-group>

      <view class="buttonCont">
        <button class="butClos" @click="repeatShow = false">取消</button>
        <button class="sub" @click="repeatSubFun">确定</button>
      </view>
    </wd-popup>

    <!-- 使用时长 -->
    <wd-popup
      v-model="timeSlotShow"
      safe-area-inset-bottom
      position="bottom"
      custom-style="padding: 15px 15px; border-radius: 20px 20px 0 0;padding-bottom: 50px;"
      @close="cancelTimeSlotShow('timeSlot')"
    >
      <view class="popuTitle">选择使用时长</view>

      <wd-picker-view
        v-model="timeSlotVal"
        :columns="columns"
        label-key="label"
        value-key="label"
        @change="timeSlotConfirm"
        @getLabels="timeSlotSubFun"
      />

      <view class="buttonCont">
        <button class="butClos" @click="cancelTimeSlotShow('timeSlot')">取消</button>
        <button class="sub" @click="timeSlotSubFun">确定</button>
      </view>
    </wd-popup>
    <!-- 休息时长 -->
    <wd-popup
      v-model="restDurationShow"
      safe-area-inset-bottom
      position="bottom"
      custom-style="padding: 15px 15px; border-radius: 20px 20px 0 0;padding-bottom: 50px;"
      @close="cancelTimeSlotShow('timeSlot2')"
    >
      <view class="popuTitle">选择休息时长</view>

      <wd-picker-view
        v-model="timeSlotVal1"
        :columns="columns1"
        label-key="label"
        value-key="label"
        @change="timeSlotConfirm1"
        @getLabels="timeSlotSubFun1"
      />

      <view class="buttonCont">
        <button class="butClos" @click="cancelTimeSlotShow('timeSlot2')">取消</button>
        <button class="sub" @click="timeSlotSubFun1">确定</button>
      </view>
    </wd-popup>
  </view>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue'
import { deviceTimeControl, getDeviceScreenControlApi } from '@/api'

import { onLoad } from '@dcloudio/uni-app'

const endTime = ref<string>('00:00')
const startTime = ref<string>('00:00')

const simSerialNumber = ref()
const pickerShow = ref(false) // fux

const timePopupTitle = ref('选择开始时间')
const repeatShow = ref(false)
const timeSlotShow = ref(false)
const restDurationShow = ref(false) // 休息时长
const currentIndex = ref()
const currentIndex2 = ref()
const timeSlotVal = ref()
const timeSlotVal1 = ref()
const disabled = ref(false) // 禁止点击
const columns = ref([
  {
    label: '15分钟',
    val: 900,
  },
  {
    label: '30分钟',
    val: 1800,
  },
  {
    label: '1小时',
    val: 3600,
  },
  {
    label: '2小时',
    val: 7200,
  },
  {
    label: '3小时',
    val: 10800,
  },
])
const columns1 = ref([
  {
    label: '5分钟',
    val: 300,
  },
  {
    label: '10分钟',
    val: 600,
  },
  {
    label: '15分钟',
    val: 900,
  },
  {
    label: '20分钟',
    val: 1200,
  },
  {
    label: '25分钟',
    val: 1500,
  },
  {
    label: '30分钟',
    val: 1800,
  },
  {
    label: '35分钟',
    val: 2100,
  },
  {
    label: '40分钟',
    val: 2400,
  },
  {
    label: '45分钟',
    val: 2700,
  },
  {
    label: '50分钟',
    val: 3000,
  },
  {
    label: '55分钟',
    val: 3300,
  },
  {
    label: '60分钟',
    val: 3600,
  },
])
const cellData = reactive([
  {
    type: 1,
    name: '可用时段',
    tips: '设定学习机可用时段，非使用时段内，设备将自动进入锁屏状态，无法使用视频观看等功能。',
    show: false,
    list: [
      {
        name: '开始时间',
        type: 'startTime',
        placeholderText: '开始时间',
        val: '',
      },
      {
        name: '结束时间',
        type: 'endTime',
        placeholderText: '结束时间',
        val: '',
      },
      {
        name: '重复',
        type: 'picker',
        placeholderText: '',
        val: '',
      },
    ],
  },
  {
    type: 2,
    name: '护眼模式',
    tips: '在可用时段内，每使用一段时间需强制休息一会，期间设备将自动进入锁屏状态，无法使用视频观看等功能。',
    show: false,
    list: [
      {
        name: '使用时长',
        type: 'timeSlot',
        placeholderText: '使用时长',
        val: '',
      },
      {
        name: '休息时长',
        type: 'timeSlot2',
        placeholderText: '休息时长',
        val: '',
      },
    ],
  },
])
const dayOfWeekVal = ref([])
const dayOfWeekList = reactive([
  {
    name: '周一',
    val: 1,
  },
  {
    name: '周二',
    val: 2,
  },
  {
    name: '周三',
    val: 3,
  },
  {
    name: '周四',
    val: 4,
  },
  {
    name: '周五',
    val: 5,
  },
  {
    name: '周六',
    val: 6,
  },
  {
    name: '周日',
    val: 7,
  },
])

function changeSwicth(val, i) {
  isEmpty()
  if (val.value) return
  let obj = submitData()
  deviceTimeControl(obj).then(res => {
    uni.showToast({
      title: '提交成功！',
    })
  })
}
function SubmitFun() {
  let obj = submitData()
  deviceTimeControl(obj).then(res => {
    uni.showToast({
      title: '提交成功！',
    })
    setTimeout(() => {
      uni.navigateBack()
    }, 2000)
  })
}
function submitData() {
  let useTime = columns.value.filter(item => {
    return item.label === cellData[1].list[0].val
  })
  let restTime = columns1.value.filter(item => {
    return item.label === cellData[1].list[1].val
  })
  if (disabled.value) return
  let obj = {
    deviceUsageScheduleDto: cellData[0].show
      ? {
          dayOfWeekList: dayOfWeekVal.value,
          startTime: cellData[0].list[0].val,
          endTime: cellData[0].list[1].val,
          simSerialNumber: simSerialNumber.value,
        }
      : {},
    eyeFlag: cellData[1].show ? 1 : 0,
    usageFlag: cellData[0].show ? 1 : 0,
    usageDuration: cellData[1].show ? useTime[0].val : '', // 使用时间
    restDuration: cellData[1].show ? restTime[0].val : '', // 休息时间
    simSerialNumber: simSerialNumber.value,
  }
  return obj
}
// 判断是否有为空
function isEmpty() {
  let empty1 = false
  let empty2 = false
  if (cellData[0].show) {
    empty1 = cellData[0].list.some(obj => !obj.val)
  }
  if (cellData[1].show) {
    empty2 = cellData[1].list.some(obj => !obj.val)
  }
  disabled.value = empty1 || empty2
}

// 时长选择
function timeSlotClose() {}

function timeSlotConfirm(e: any) {
  timeSlotVal.value = columns.value[e.index].label
}

function timeSlotConfirm1(e: any) {
  timeSlotVal1.value = columns1.value[e.index].label
}

function timeSlotSubFun() {
  cellData[currentIndex.value].list[currentIndex2.value].val = timeSlotVal.value
  timeSlotShow.value = false
  isEmpty()
}

function cancelTimeSlotShow(type: any) {
  switch (type) {
    case 'timeSlot2':
      // 休息时长
      restDurationShow.value = false
      timeSlotVal1.value = cellData[1].list[1].val
      break
    case 'timeSlot':
      // 使用时长
      timeSlotShow.value = false
      timeSlotVal.value = cellData[1].list[0].val
      break
    case 'time':
      // 开始时间
      if (timePopupTitle.value.includes('开始')) {
        startTime.value = cellData[0].list[currentIndex2.value].val
      } else {
        endTime.value = cellData[0].list[currentIndex2.value].val
      }
      pickerShow.value = false
      break
  }
}
function timeSlotSubFun1() {
  cellData[currentIndex.value].list[currentIndex2.value].val = timeSlotVal1.value
  restDurationShow.value = false
  isEmpty()
}
function handleRepeatData() {
  dayOfWeekVal.value.sort((a, b) => a - b)
  cellData[0].list[2].val = ''
  let filterArray = dayOfWeekList.filter(item1 =>
    dayOfWeekVal.value.some(item2 => item2 === item1.val),
  )
  filterArray.forEach(item => {
    cellData[0].list[2].val = String(cellData[0].list[2].val) + item.name + '、'
  })
}
function repeatSubFun() {
  handleRepeatData()
  repeatShow.value = false
  isEmpty()
}

function subFun() {
  if (timePopupTitle.value.includes('开始')) {
    cellData[currentIndex.value].list[currentIndex2.value].val = startTime.value
  } else {
    cellData[currentIndex.value].list[currentIndex2.value].val = endTime.value
  }

  pickerShow.value = false
  isEmpty()
}

function repeatClose() {}

function itemFun(e: any, i: number, ii: number) {
  currentIndex.value = i
  currentIndex2.value = ii
  switch (e.type) {
    case 'startTime':
      startTime.value = cellData[0].list[0].val
      timePopupTitle.value = '选择开始时间'
      pickerShow.value = true
      break
    case 'endTime':
      endTime.value = cellData[0].list[1].val
      timePopupTitle.value = '选择结束时间'
      pickerShow.value = true
      break
    case 'picker':
      {
        repeatShow.value = true
        dayOfWeekVal.value = []
        let repeatWeek = cellData[0].list[2].val.split('、').filter(i => i)
        let filterArray = dayOfWeekList.filter(item1 =>
          repeatWeek.some(item2 => item2 === item1.name),
        )
        filterArray.forEach(item => {
          dayOfWeekVal.value.push(item.val)
        })
      }
      break
    case 'timeSlot':
      timeSlotVal.value = cellData[currentIndex.value].list[currentIndex2.value].val || '15分钟'
      timeSlotShow.value = true
      break
    case 'timeSlot2':
      timeSlotVal1.value = cellData[currentIndex.value].list[currentIndex2.value].val || '5分钟'
      restDurationShow.value = true
      break
  }
}
async function fetchDeviceScreen() {
  try {
    uni.showLoading({
      title: '加载中...',
    })
    const { data } = await getDeviceScreenControlApi(simSerialNumber.value)
    if (!data) return
    cellData[0].show = data.usageFlag === 1 ? true : false
    cellData[1].show = data.eyeFlag === 1 ? true : false
    if (cellData[0].show) {
      cellData[0].list[0].val = data.deviceUsageScheduleVo.startTime
      cellData[0].list[1].val = data.deviceUsageScheduleVo.endTime
      dayOfWeekVal.value = data.deviceUsageScheduleVo.dayOfWeekList
      handleRepeatData()
    }
    if (cellData[1].show) {
      cellData[1].list[0].val = columns.value.filter(item => {
        return Number(item.val) === Number(data.usageDuration)
      })[0].label
      cellData[1].list[1].val = columns1.value.filter(item => {
        return Number(item.val) === Number(data.restDuration)
      })[0].label
    }
  } finally {
    uni.hideLoading()
  }
}

onLoad(option => {
  simSerialNumber.value = option.simSerialNumber
  fetchDeviceScreen()
})
</script>

<style lang="scss" scoped>
.page {
  box-sizing: border-box;
  padding-bottom: 120rpx;
  .content {
    padding: 30upx;
  }

  .cell {
    width: 100%;
    display: flex;
    flex-direction: column;
    padding: 30upx;
    box-sizing: border-box;
    border-radius: 20upx;
    background-color: #fff;
    gap: 20upx;
    margin-bottom: 30upx;

    .top-cont {
      width: 100%;
      display: flex;
      align-items: center;

      .title {
        flex: 1;
        font-size: 32upx;
      }
    }

    .tips {
      width: 100%;
      font-size: 28upx;
      color: #666666;
    }
  }

  .showContent {
    width: 100%;
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 30upx;
    font-size: 30upx;
    .item {
      width: 100%;
      display: flex;
      align-items: center;
      background-color: #f9f9fb;
      border-radius: 20upx;
      padding: 24upx 20upx;
      box-sizing: border-box;

      .itemKey {
        flex: 1;
      }
      .itemVal {
        color: #a9aab5;
        input {
          text-align: right;
          // width: 200upx;
        }
      }
    }
  }
}

.popuTitle {
  width: 100%;
  font-size: 32upx;
  color: #333333;
  font-weight: 500;
}
.time_picker {
  position: relative;

  .colon {
    position: absolute;
    top: 44%;
    left: 50%;
  }
}

.buttonCont {
  width: 100%;
  display: flex;
  align-items: center;
  margin-top: 16upx;
  font-size: 30upx;
  gap: 20upx;
  .butClos {
    width: 230upx;
    height: 90upx;
    background-color: #efefff;
    color: #615dff;
    border-radius: 20upx;
  }
  .sub {
    width: 440upx;
    height: 90upx;
    background-color: #615dff;
    color: #fff;
    border-radius: 20upx;
  }
}
.footer {
  position: fixed;
  bottom: 0;
  padding: 16rpx 0 0 0;
  box-sizing: border-box;
  display: flex;
  justify-content: center;
  background-color: #fff;
  width: 100%;
  height: 126rpx;
  border-top: 1rpx solid #eeeeee;

  .submit {
    width: 440upx;
    height: 90upx;
    border-radius: 20upx;
    font-size: 30upx;
    display: flex;
    align-items: center;
    justify-content: center;
  }
  .activeBtn {
    color: #fff;
    background-color: rgba(97, 93, 255, 1);
  }
  .disabledBtn {
    color: #b0b1bb;
    background: #e2e2e7;
  }
}

.week_cell {
  border-bottom: 1rpx solid #ebebeb;
  padding: 0;
  margin: 0 35rpx;
}
:deep(.wd-cell.is-center .wd-cell__wrapper) {
  padding-right: 0 !important;
}
:deep(.uni-picker-view-content) {
  color: #a9aab5;
}
:deep(.wd-picker-view-column__item--active) {
  color: #0a1f13 !important;
}
:deep(.wd-picker-view__roller) {
  background: #fff;
  border-top: 1rpx solid #ebebeb;
  border-bottom: 1rpx solid #ebebeb;
}
</style>
