<template>
  <div class="app-container home">
    <el-row :gutter="20">
      <el-col :span="24" :xs="24">
        <el-form :model="queryParams" ref="queryRef" :inline="true" label-width="68px">
          <el-form-item label="设备名称">
            <el-select v-model="queryParams.devName" placeholder="请选择设备" @change="handleDevChange">
              <el-option v-for="item in devArr" :key="item.deviceId" :label="item.deviceName" :value="item.deviceId" />
            </el-select>
          </el-form-item>
          <el-form-item label="执行日期" prop="week">
            <el-select v-model="queryParams.week" placeholder="请选择执行日期" style="width: 240px">
              <el-option label="所有" value="0" />
              <el-option label="星期一" value="1" />
              <el-option label="星期二" value="2" />
              <el-option label="星期三" value="3" />
              <el-option label="星期四" value="4" />
              <el-option label="星期五" value="5" />
              <el-option label="星期六" value="6" />
              <el-option label="星期日" value="7" />
              <el-option label="每天" value="8" />
              <el-option label="仅此一次" value="9" />
            </el-select>
          </el-form-item>
<!--          <el-form-item label="执行时间" prop="time">-->
<!--            <el-select v-model="queryParams.time" placeholder="请选择" style="width: 240px">-->
<!--              <el-option label="00:00-02:00" value="1" />-->
<!--              <el-option label="02:00-03:00" value="2" />-->
<!--            </el-select>-->
<!--          </el-form-item>-->
          <el-form-item label="日期范围" style="width: 308px;">
            <el-date-picker v-model="queryParams.dateRange"
                            value-format="YYYY-MM-DD"
                            type="daterange"
                            range-separator="-"
                            start-placeholder="开始日期"
                            end-placeholder="结束日期"
            ></el-date-picker>
          </el-form-item>
          <el-form-item class="mr30">
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" icon="Plus" @click="handleAdd">新增</el-button>
          </el-col>
        </el-row>
          <div class="dev_control_table">
            <el-table :data="timingList" height="685px">
              <el-table-column label="序号" align="center" width="50"/>
              <el-table-column label="设备名称" align="center" prop="deviceId"/>
              <el-table-column label="指令内容" align="center" prop="controlContext" width="500"/>
              <el-table-column label="执行日期" align="center" prop="runday"/>
              <el-table-column label="执行时间" align="center" prop="runtime"/>
              <el-table-column label="创建时间" align="center" prop="createTime"/>
              <el-table-column label="操作" align="center" prop="handle">
                <template v-slot="scope">
                  <el-button type="danger" size="small" :icon="Delete" @click="getDeleteTimerFun(scope)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <el-pagination
                v-model:current-page="currentPage"
                v-model:page-size="pageSize"
                :page-sizes="[5, 10, 20, 50]"
                :small="small"
                :disabled="disabled"
                :background="background"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"/>
          </div>
      </el-col>
    </el-row>



    <!-- 新增对话框 -->
    <el-dialog :title="title" v-model="open" width="600px" append-to-body>
      <el-form :model="timingForm"  ref="userRef" label-width="80px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="设备名称">
              <el-select v-model="timingForm.dev" placeholder="请选择设备" @change="handleDevChange">
                <el-option v-for="item in devArr" :key="item.deviceId" :label="item.deviceName" :value="item.deviceId" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="指令内容" prop="content">
              <el-input v-model="timingForm.content" placeholder="请输入指令内容"/>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="执行星期">
              <el-radio-group v-model="timingForm.day">
                <el-radio style='width:90px' label="每天" @change="handleEveryday"/>
              </el-radio-group>
              <div class="collapse">
                <el-collapse v-model="activeName" accordion>
                  <el-collapse-item title="星期几" name="1">
                    <el-checkbox-group v-model="timingForm.week">
                      <el-checkbox style='width:90px' label="1" key="1">星期一</el-checkbox>
                      <el-checkbox style='width:90px' label="2" key="2">星期二</el-checkbox>
                      <el-checkbox style='width:90px' label="3" key="3">星期三</el-checkbox>
                      <el-checkbox style='width:90px' label="4" key="4">星期四</el-checkbox>
                      <el-checkbox style='width:90px' label="5" key="5">星期五</el-checkbox>
                      <el-checkbox style='width:90px' label="6" key="6">星期六</el-checkbox>
                      <el-checkbox style='width:90px' label="7" key="7">星期日</el-checkbox>
                    </el-checkbox-group>
                  </el-collapse-item>

                  <el-collapse-item title="仅此一次" name="2">
                    <el-date-picker v-model="value1" type="date" placeholder="请选择日期"/>
                  </el-collapse-item>
                </el-collapse>
              </div>

            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="执行时间" prop="executeTime">
              <el-time-picker v-model="timingForm.executeTime" placeholder="请选择执行时间" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Index">
import {Delete} from '@element-plus/icons-vue'
import {ElMessage, ElMessageBox} from "element-plus";
import {ref,reactive,watch,onMounted} from "vue";
import { getList,getAddTimer,getDeleteTimer } from '@/api/control/timer'
import { getDevice } from '@/api/control/manual'


/** 页面加载时*/
onMounted(()=>{
  formattedDateFun()
  getListFun()
  getAllDev()
})


/** 格式化日期*/
const YYYYMMDD = ref();
const timer = ref()
function formattedDateFun(){
  let date = new Date()
  let year = date.getFullYear()
  let month = (date.getMonth()+1).toString().padStart(2, '0');
  let day = date.getDate().toString().padStart(2, '0');
  let hours = date.getHours()
  let minutes = date.getMinutes()
  let seconds = date.getSeconds()
  YYYYMMDD.value = `${year}-${month}-${day}`
  timer.value = `${hours}:${minutes}:${seconds}`
  console.log(YYYYMMDD.value)
  console.log(timer.value)
}



/** 筛选处理 */
//选择的日期
// const dateRange = ref([]);
const startDate = ref()
const endDate = ref()
const data = reactive({
  queryParams: {
    devName:'',
    week: '',
    time: '',
    dateRange:[],
  }
});
//监听开始日期和结束日期
const wacthSelectDate = watch(()=> data.queryParams.dateRange,(val) =>{
  console.log(val[0])
  startDate.value = val[0]
  console.log(val[1])
  endDate.value = val[1]
})
//搜索按钮
function handleQuery(){
  getListFun()
}
//重置按钮
function resetQuery(){
  data.queryParams.dateRange = [];
  currentPage.value = 1;
  pageSize.value = 20;
  startDate.value = null;
  endDate.value = null;
  devId.value = null;
  getListFun()
}


/** 数据表格处理 */
const timingList = ref([])
const currentPage = ref(1)
const pageSize = ref(20)
const total = ref()
const small = ref(false)
const background = ref(false)
const disabled = ref(false)

function getListFun(){
  getList({
    "timerId":null,
    "deviceId":devId.value,
    "controlContext":null,
    "timerStatus":null,
    "createStart":startDate.value,
    "createEnd": endDate.value,
    "pageNum": currentPage.value,
    "pageSize": pageSize.value
  }).then((res)=>{
    total.value = res.total
    timingList.value = res.rows
  })
}

const handleSizeChange = (val) => {
  console.log(`${val}`)
  getListFun()
}
const handleCurrentChange = (val) => {
  console.log(`${val}`)
  getListFun()
}

//删除定时任务
function getDeleteTimerFun(e){
  ElMessageBox.confirm(
    '确定要删除此条定时任务吗？',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }).then(() => {
    console.log(e.row.deviceId)
      getDeleteTimer(e.row.deviceId).then((res)=>{
        console.log(res)
        // if(res.code == 200){
          // ElMessage({
          //   type: 'success',
          //   message: '删除成功！',
          // })
        // }
      })
  }).catch(() => {})
}


/** 新增定时处理 */
const open = ref(false);
const title = ref();
const activeName = ref('1')
const value1 = ref('')
const devArr = ref([])
const devId = ref()
const selectDate = ref()
const selectTimer = ref()
const timingForm = reactive({
  dev:'',
  content:'',
  day:'',
  week:[],
  executeTime:'',
})
//拿到选择的设备id
function handleDevChange(id){
  devId.value = id
  console.log('选择的设备id',devId.value)
}
//监听：输入的指令内容
const watchContent = watch(()=> timingForm.content,(val)=>{
  console.log(val)
})
//监听：勾选的星期
const watchWeek = watch(()=> timingForm.week,(val) => {
  console.log('监听勾选的星期',val)
  if(timingForm.week.length === 7){
    timingForm.day = '每天';
  }else if(timingForm.week.length < 7 && timingForm.week.length > 0){
    timingForm.day = ''
  }
})
//监听：选择仅此一次将每天和星期几清空
const watchValue1 = watch(()=> value1.value,(val) => {
  const date = new Date(val.toLocaleString());
  const year = date.getFullYear();
  const month = (date.getMonth() + 1).toString().padStart(2, '0');
  const day = date.getDate().toString().padStart(2, '0');
  selectDate.value = `${year}-${month}-${day}`;
  console.log('选择的日期',selectDate.value)
  if(value1.value != null){
    timingForm.day = '';
    timingForm.week = [];
  }
})
//监听：选择的执行时间
const watchTime = watch(()=> timingForm.executeTime, (val) => {
  let date = new Date(val)
  let hours = date.getHours()
  let minutes = date.getMinutes()
  let seconds = date.getSeconds()
  selectTimer.value = `${hours}:${minutes}:${seconds}`
  console.log(selectTimer.value)
})
//获取所有设备
function getAllDev(){
  getDevice().then((res)=>{
    devArr.value = res.data
  })
}
//选中每天
function handleEveryday(){
  console.log('点击每天')
  value1.value = '';
  timingForm.week = [];
}
//新增按钮
function handleAdd() {
  open.value = true;
  title.value = "新增定时任务";
};
//确定新增
function submitForm() {
  open.value = false;
  getAddTimer({
    "deviceId":devId.value,
    "controlKey":"intemp",
    "controlValue":timingForm.content,
    "status":"0",
    "runday":selectDate.value,
    "runtime":selectTimer.value
  }).then((res)=>{
    if(res.code == 200){
      ElMessage({
        message: res.msg,
        type: 'success',
      })
    }
  })
};
//取消新增
function cancel() {
  open.value = false;
};





const { queryParams } = toRefs(data);
</script>

<style scoped lang="scss">
.dev_control_table{
  position: relative;
  width: 100%;
  min-height: 745px;
  background-color: #2F3D8A;
}
.mr30{
  margin-left: 100px;
  margin-top: -4px;
}
.collapse{
  margin-bottom: -1px;
}
::v-deep .el-button{
  border-radius: 2px;
}
::v-deep .el-pagination{
  position: absolute;
  bottom: 10px;
  left: 50%;
  transform: translateX(-50%);
}
::v-deep .el-pagination__total{
  color: #f3ffff;
}
::v-deep .el-pagination__jump{
  color: #f3ffff;
}
::v-deep .el-pager{
  margin: 0 5px;
}
::v-deep .el-table .el-table__body-wrapper{
  background-color: #2F3D8A;
}
::v-deep .el-form-item__content{
  display: inline-block;
}
::v-deep .el-input__inner{
  color: #f3ffff !important;
}
::v-deep .el-date-editor .el-range-input{
  color: #f3ffff;
}
::v-deep .el-scrollbar__wrap.el-scrollbar__wrap--hidden-default{
  background-color: rgba(47,61,138);
}
</style>

