<template>
  <div>
    <Navbar title="定时开关机" :is-go-back="false" />
    <a-card>
      <a-divider class="divider-class" orientation="left" orientation-margin="0px">选择终端</a-divider>
      <a-row style="margin-bottom: 16px;">
        <a-col :span="24">
          <a-input-search
            v-model:value="searchValue" placeholder="请输入终端名称" style="width: 300px;" enter-button
            @search="onSearch"
          />
        </a-col>
      </a-row>
      <div class="custom-row">
        <a-col v-for="(item, groupIndex) in deviceDatas" :key="groupIndex" :span="4" style="margin-bottom: 8px;">
          <a-checkbox :key="item.id" v-model:checked="item.isChecked" :value="item.id" @change="selectChanged(item)">
            <DesktopOutlined style="color: #61a7f5;" /> {{ item.name }}
          </a-checkbox>
        </a-col>
      </div>


      <a-pagination
        v-model:current="currentPage" v-model:pageSize="pageSize" :total="totalItems" show-size-changer
        size="small" show-quick-jumper style="margin: 16px 0;text-align: right;" @change="handlePageChange"
        @show-size-change="handlePageSizeChange"
      />

      <a-divider class="divider-class" orientation="left" orientation-margin="0px">定时开关机</a-divider>

      <div class="container-box">
        <div class="left-panel">
          <a-row v-for="(day, index) in weekDayInfo" :key="index" :gutter="16">
            <a-col :span="24" class="day-col">
              <a-checkbox v-model:checked="day.isEnable" @change="startEnabled(day, index)" />
              <label class="day-label" :class="{ 'highColor': selectIndex === index }" @click="queryTime(day, index)">
                {{ day.label }}
              </label>
            </a-col>
          </a-row>
          <a-row :gutter="16">
            <a-col :span="24" class="day-col">
              <a-checkbox v-model:checked="allEnable" @change="allEnableChanged" />
              <label>全部启用</label>
            </a-col>
          </a-row>
        </div>
        <div class="right-panel">
          <a-radio-group
            v-model:value="type" size="small" button-style="solid" class="status-device"
            @change="typeChanged"
          >
            <a-radio-button value="Normally_Open">常开</a-radio-button>
            <a-radio-button value="Timer">定时</a-radio-button>
          </a-radio-group>
          <div class="date-range-grid">
            <div
              v-for="(field, fieldIndex) in weekDayDatas[weekDay]['deviceTimerWeekTimeDtos']" :key="fieldIndex"
              class="form-item"
            >
              <a-form-item style="height: 30px;margin-bottom: 14px;">
                <div class="input-container">
                  <a-time-picker
                    v-model:value="field.startTime" :disabled="isDisabled" :allow-clear="false"
                    size="small"
                  /><span style="margin: 0 8px;">至</span>
                  <a-time-picker
                    v-model:value="field.endTime" :disabled="isDisabled" :allow-clear="false"
                    size="small"
                  />
                  <a-switch
                    v-model:checked="field.isEnable" :disabled="isDisabled" size="small"
                    class="enable-button"
                  />
                  <DeleteOutlined @click="removeField(fieldIndex)" />
                </div>
              </a-form-item>
            </div>
            <div v-if="type === 'Timer'" class="add-field-button">
              <a-button :icon="h(PlusOutlined)" @click="addField">添加定时时间段</a-button>
            </div>
          </div>
        </div>
      </div>
      <a-button type="primary" style="margin-left: -8px;" @click="saveTimer(true)">保存定时开关机</a-button>
    </a-card>
    <Loading v-if="isLoading" />
  </div>
</template>

<script setup>
import Common from '../common/Common.js';
import { ref, onMounted, computed, h, watch } from 'vue';
import { message } from 'ant-design-vue';
import { DesktopOutlined, DeleteOutlined, PlusOutlined } from '@ant-design/icons-vue';
import { ajaxApi, ajaxApiGet } from '../api/workflow/workflow.js';
import dayjs from 'dayjs';
import 'dayjs/locale/zh-cn';
dayjs.locale('zh-cn');

const isLoading = ref(false);
// 所有终端数据
const deviceDatas = ref([]);
// 分页参数
const pagination = ref({
  start: 1,
  length: 20,
});

const searchValue = ref('');

const allEnable = ref(false);

// 当前页
const currentPage = ref(1);
// 每页条数
const pageSize = ref(10);
// 总条数
const totalItems = ref(0);

const deviceId = ref(null); // 终端id
const deviceName = ref(null); // 终端名称

const dayId = ref(null); // 星期id
const type = ref('Normally_Open'); // 定时类型
const selectIndex = ref(null); // 定时类型

// 处理是星期几
const weekDayInfo = ref([
  { id: 'Monday', label: '星期一', isEnable: false },
  { id: 'Tuesday', label: '星期二', isEnable: false },
  { id: 'Thursday', label: '星期四', isEnable: false },
  { id: 'Friday', label: '星期五', isEnable: false },
  { id: 'Saturday', label: '星期六', isEnable: false },
  { id: 'Sunday', label: '星期日', isEnable: false },
]);

watch(weekDayInfo, newVal => {
  if (newVal.length > 0) {
    allEnable.value = newVal.every(item => item.isEnable);
  }
}, { deep: true, immediate: true });

// 搜索终端
const onSearch = value => {
  currentPage.value = 1;
  fetchData();
};

// 全部启用
const allEnableChanged = () => {
  if (!deviceId.value) {
    message.warning('请您先选择终端。');
    allEnable.value = false;
    return;
  }
  weekDayInfo.value.forEach(item => {
    item.isEnable = allEnable.value;
  });
  for (let key in weekDayDatas.value) {
    weekDayDatas.value[key]['isEnable'] = allEnable.value;
  }
};

// 是否启用这一天
const startEnabled = (data, index) => {
  if (!deviceId.value) {
    message.warning('请您先选择终端。');
    data.isEnable = false;
    return;
  }
  queryTime(data, index);
};

// 当为常开时禁用定时
const isDisabled = computed(() => {
  return type.value === 'Normally_Open' ? true : false;
});

// 更新星期几的类型
const typeChanged = e => {
  let value;
  if (e.target.value === 'Normally_Open') {
    value = 'Timer';
  } else {
    value = 'Normally_Open';
  }
  if (!deviceId.value) {
    message.warning('请您先选择终端。');
    type.value = value;
    return;
  }
  if (!dayId.value) {
    message.warning('请你先选择需要修改星期几的定时类型。');
    type.value = value;
    return;
  }
  weekDayDatas.value[weekDay.value]['deviceManagementTimerType'] = e.target.value;
};

// 删除星期几内的时间段
const removeField = fieldIndex => {
  weekDayDatas.value[weekDay.value]['deviceTimerWeekTimeDtos'].splice(fieldIndex, 1);
};

// 添加新的时间段到星期几
const addField = () => {
  if (!deviceId.value) {
    message.warning('请您先选择终端。');
    return;
  }
  if (!dayId.value) {
    message.warning('请您先选择需要添加到星期几。');
    return;
  }
  weekDayDatas.value[weekDay.value]['deviceTimerWeekTimeDtos'].push({ startTime: null, endTime: null, isEnable: true });
};

// 获取所选终端对应的开关机信息
const selectChanged = record => {
  const copyDatas = JSON.parse(JSON.stringify(deviceDatas.value));
  deviceDatas.value = copyDatas.map(item => item.id === record.id ? item : { ...item, isChecked: false });
  queryTimeInfo(record.id, record.name);
};

// 查询终端数据
const fetchData = () => {
  pagination.value.start = (currentPage.value - 1) * pageSize.value;
  pagination.value.length = pageSize.value;
  queryDevice();
};

// 分页变化
const handlePageChange = page => {
  currentPage.value = page;
  setTimeout(() => {
    fetchData();
  }, 100);
};

// 每页条数变化
const handlePageSizeChange = (current, size) => {
  setTimeout(() => {
    currentPage.value = 1;
  });
  pageSize.value = size;
};

// 时间默认值（00:00:00 ~ 23:59:59）
const rangeTime = [{ startTime: dayjs('00:00:00', 'HH:mm:ss'), endTime: dayjs('23:59:59', 'HH:mm:ss'), isEnable: true }];

const weekDay = ref('Monday'); // 当前所选星期几

// 每一天的数据
const weekDayDatas = ref({
  Monday: { id: null, weekDay: 'Monday', isEnable: false, deviceManagementTimerType: 'Normally_Open', deviceTimerWeekTimeDtos: rangeTime },
  Tuesday: { id: null, weekDay: 'Tuesday', isEnable: false, deviceManagementTimerType: 'Normally_Open', deviceTimerWeekTimeDtos: rangeTime },
  Wednesday: { id: null, weekDay: 'Wednesday', isEnable: false, deviceManagementTimerType: 'Normally_Open', deviceTimerWeekTimeDtos: rangeTime },
  Thursday: { id: null, weekDay: 'Thursday', isEnable: false, deviceManagementTimerType: 'Normally_Open', deviceTimerWeekTimeDtos: rangeTime },
  Friday: { id: null, weekDay: 'Friday', isEnable: false, deviceManagementTimerType: 'Normally_Open', deviceTimerWeekTimeDtos: rangeTime },
  Saturday: { id: null, weekDay: 'Saturday', isEnable: false, deviceManagementTimerType: 'Normally_Open', deviceTimerWeekTimeDtos: rangeTime },
  Sunday: { id: null, weekDay: 'Sunday', isEnable: false, deviceManagementTimerType: 'Normally_Open', deviceTimerWeekTimeDtos: rangeTime },
});

// 根据星期ID查时间段
const queryTime = (info, index) => {
  if (!deviceId.value) {
    message.warning('请您先选择终端。');
    return;
  }
  selectIndex.value = index;
  dayId.value = info.id;
  weekDay.value = info.weekDay;
  weekDayDatas.value[weekDay.value]['isEnable'] = info.isEnable;
  type.value = weekDayDatas.value[weekDay.value]['deviceManagementTimerType'];
  if (!info.isSelected) {
    queryTimeById(info.id);
    info.isSelected = true;
  }
};


// 保存定时任务数据
const saveTimer = (flag, allEnableFlag) => {
  const dtos = [];
  for (let key in weekDayDatas.value) {
    weekDayDatas.value[key]['deviceTimerWeekTimeDtos'].forEach((item, index) => {
      if (!item.startTime || !item.endTime) weekDayDatas.value[key]['deviceTimerWeekTimeDtos'].splice(index, 1);
    });
    dtos.push(weekDayDatas.value[key]);
  }
  const timeDtos = dtos.map(item => {
    return {
      id: item.id,
      weekDay: item.weekDay,
      isEnable: allEnableFlag ? allEnable.value : item.isEnable,
      deviceManagementTimerType: item.deviceManagementTimerType,
      deviceTimerWeekTimeDtos: item.deviceTimerWeekTimeDtos.map(timeItem => {
        if (timeItem.startTime && timeItem.endTime) {
          return {
            isEnable: timeItem.isEnable ? true : false,
            startTime: dayjs(timeItem.startTime).format('HH:mm:ss'),
            endTime: dayjs(timeItem.endTime).format('HH:mm:ss'),
          };
        }
      }),

    };
  });
  const params = {
    id: deviceId.value,
    name: deviceName.value,
    deviceTimerWeekDtos: timeDtos,
  };
  const url = 'DeviceTimerWeekResource/saveDeviceTimerWeek';
  isLoading.value = true;
  ajaxApi(url, params).then(
    success => {
      if (success.errorCode === 0) {
        if (flag) message.success(success.errorMessage);
        queryTimeById(dayId.value);
      } else {
        message.warning(success.errorMessage);
      }
      isLoading.value = false;
    },
    error => {
      isLoading.value = false;
      Common.processException(error);
    },
  );
};

// 查询终端数据
const queryDevice = () => {
  const params = {
    condition: searchValue.value,
    range: { ...pagination.value },
  };
  const url = 'DeviceManagementResource/queryDeviceManagementDtoByScreenAndRfid';
  isLoading.value = true;
  ajaxApi(url, params).then(
    success => {
      if (success.dataList && success.dataList.length > 0) {
        success.dataList.forEach(item => {
          item.isChecked = false;
        });
        deviceDatas.value = success.dataList;
        totalItems.value = success.totalSize;
      } else {
        totalItems.value = 0;
        deviceDatas.value = [];
      }
      isLoading.value = false;
    },
    error => {
      Common.processException(error);
      isLoading.value = false;
    },
  );
};

// 根据终端信息id查询定时开关机信息
const queryTimeInfo = (id, name) => {
  const url = `DeviceTimerWeekResource/queryDeviceManagementTimerDtoByDeviceManagementId?deviceManagementId=${id}`;
  ajaxApiGet(url).then(
    success => {
      if (success.errorCode === 0) {
        if (success.data && success.data.deviceTimerWeekDtos) {
          deviceId.value = id;
          deviceName.value = name;
          const { deviceTimerWeekDtos } = success.data;
          allEnable.value = deviceTimerWeekDtos.every(item => item.isEnable);
          deviceTimerWeekDtos.forEach(item => {
            if (item.weekDay === 'Monday') {
              item.label = '星期一';
            } else if (item.weekDay === 'Tuesday') {
              item.label = '星期二';
            } else if (item.weekDay === 'Wednesday') {
              item.label = '星期三';
            } else if (item.weekDay === 'Thursday') {
              item.label = '星期四';
            } else if (item.weekDay === 'Friday') {
              item.label = '星期五';
            } else if (item.weekDay === 'Saturday') {
              item.label = '星期六';
            } else if (item.weekDay === 'Sunday') {
              item.label = '星期日';
            }
            if (!item.deviceManagementTimerType) {
              item.deviceManagementTimerType = 'Normally_Open';
            }
            for (let key in weekDayDatas.value) {
              if (key === item.weekDay) {
                weekDayDatas.value[key]['id'] = item.id;
                weekDayDatas.value[key]['isEnable'] = item.isEnable;
                weekDayDatas.value[key]['deviceManagementTimerType'] = item.deviceManagementTimerType;
                weekDayDatas.value[key]['deviceTimerWeekTimeDtos'] = [{ startTime: dayjs('00:00:00', 'HH:mm:ss'), endTime: dayjs('23:59:59', 'HH:mm:ss'), isEnable: true }];
              }
            }
          });
          weekDayInfo.value = deviceTimerWeekDtos;
          type.value = deviceTimerWeekDtos[0].deviceManagementTimerType;
          queryTime(deviceTimerWeekDtos[0], 0, true);
        }
      } else {
        message.warning(success.errorMessage);
      }
    },
    error => {
      Common.processException(error);
    },
  );
};

// 根据星期id查询定时开关机时间段信息
const queryTimeById = id => {
  isLoading.value = true;
  const url = `DeviceTimerWeekResource/queryDeviceTimerWeekDtoByDeviceTimerWeekId?deviceTimerWeekId=${id}`;
  ajaxApiGet(url).then(
    success => {
      if (success.errorCode === 0) {
        if (success.datas && success.datas.length) {
          success.datas.forEach(time => {
            time.startTime = dayjs(time.startTime, 'HH:mm:ss');
            time.endTime = dayjs(time.endTime, 'HH:mm:ss');
          });
          weekDayDatas.value[weekDay.value]['deviceTimerWeekTimeDtos'] = success.datas;
        } else {
          weekDayDatas.value[weekDay.value]['deviceTimerWeekTimeDtos'] = [{ startTime: dayjs('00:00:00', 'HH:mm:ss'), endTime: dayjs('23:59:59', 'HH:mm:ss'), isEnable: true }];
        }
      } else {
        message.warning(success.errorMessage);
      }
      isLoading.value = false;
    },
    error => {
      isLoading.value = false;
      Common.processException(error);
    },
  );
};


onMounted(() => {
  fetchData();
});


</script>

<style scoped>
.divider-class {
  margin: 12px 0 12px 0 !important;
}

:deep(.ant-pagination) {
  margin: 0 !important;
}

.checkbox-container {
  display: flex;
  flex-direction: column;
}

.checkbox-item {
  margin-top: 8px;
}

.checkbox-item {
  margin-bottom: 8px;
  border-bottom: 1px solid #e8e8e8;
}

.container-box {
  display: flex;
}

.left-panel {
  width: 76px;
}

.right-panel {
  margin-left: 80px;
  width: 26%;
  height: 360px;
  overflow: auto;
}

.day-col {
  border-bottom: 1px solid #ddd;
  margin-bottom: 8px;
}

.day-label {
  margin-left: 6px;
  cursor: pointer;
}

.highColor {
  color: #008fff;
}

.status-device {
  margin-bottom: 10px;
}

.input-container {
  display: flex;
  align-items: center;
  background: #efefef;
  padding: 0 20px;
}

.add-field-button {
  text-align: center;
}

.enable-button {
  margin: 12px;
}

:deep(.input-container .anticon svg) {
  font-size: 18px;
}

.custom-row {
  display: flex;
  flex-wrap: wrap;
}

.custom-row .ant-col {
  flex: 1 1 calc(20% - 20px);
  min-width: calc(20% - 20px);
}
</style>