<template>
  <!-- 设置闹钟 -->
  <div class="alarm-config-container">
    <s-header :name="$t('device.setAlarm')" :noback="false" />

    <!-- 主表单区域 -->
    <div class="config-card">
      <!-- 设备选择 -->
      <van-field v-model="equipmentIdsText" is-link readonly center :label="$t('device.equipmentName')"
        :placeholder="$t('device.selectDevice')" class="form-field" @click="equipmentShow = true">
        <template #left-icon>
          <van-icon name="cluster-o" class="field-icon" />
        </template>
      </van-field>

      <!-- 时间选择 -->
      <van-field v-model="hour" is-link readonly center :label="$t('device.selectTime')"
        :placeholder="$t('device.selectTime')" class="form-field" @click="currentTimeShow = true">
        <template #left-icon>
          <van-icon name="clock-o" class="field-icon" />
        </template>
      </van-field>
      <!-- 闹钟类型 -->
      <van-field v-model="alarmClockTypeText" is-link readonly center :label="$t('device.alarmTypeLabel')"
        :placeholder="$t('device.alarmTypePlaceholder')" class="form-field" @click="alarmClockTypeShow = true">
        <template #left-icon>
          <van-icon name="flag-o" class="field-icon" />
        </template>
      </van-field>

      <!-- 重复周期 -->
      <div class="repeat-section">
        <h3 class="section-title">
          <van-icon name="replay" class="title-icon" />
          {{ $t("device.selectTheNumberOfAlarmClockRepetitions") }}
        </h3>
        <div class="quick-select">
          <van-checkbox v-model="checkedAll" shape="square" @click="checkedAllClk">
            {{ $t("alarmClockSet.checkedAll") }}
          </van-checkbox>
        </div>
        <div class="day-grid">
          <div v-for="(item, index) in weekDayList" :key="index" class="day-item"
            :class="{ active: selectList.includes(item.value) }" @click="selectDayClk(item.value)">
            {{ item.name }}
          </div>
        </div>
      </div>


      <!-- 闹钟名称 -->
      <van-field v-model="alarmClockName" center :label="$t('device.alarmNameLabel')"
        :placeholder="$t('device.alarmNamePlaceholder')" class="form-field">
        <template #left-icon>
          <van-icon name="edit" class="field-icon" />
        </template>
      </van-field>

      <!-- 立即生效 -->
      <div class="switch-section">
        <span class="switch-label">
          <van-icon name="certificate" class="switch-icon" />
          {{ $t("device.effectiveImmediately") }}
        </span>
        <van-switch v-model="checked" size="18px" />
      </div>
    </div>

    <!-- 提交按钮 -->
    <div class="action-bar">
      <van-button round type="primary" class="submit-btn" @click="submitSet">
        <van-icon name="passed" class="btn-icon" />
        {{ $t("device.submitSettings") }}
      </van-button>
    </div>

    <!-- 弹出层（保持原有逻辑，优化样式） -->
    <van-popup v-model:show="alarmClockTypeShow" round position="bottom" class="custom-popup">
      <van-cascader v-model="alarmClockType" :title="$t('device.alarmTypePlaceholder')" :options="alarmClockTypeOptions"
        active-color="#2c87c8" @close="alarmClockTypeShow = false" @finish="alarmClockTypeFinish" />
    </van-popup>

    <van-popup v-model:show="currentTimeShow" round position="bottom" class="custom-popup">
      <van-time-picker v-model="currentTime" :title="$t('device.clickToSelectTheTime')" @confirm="onConfirm"
        @cancel="currentTimeShow = false" />
    </van-popup>

    <van-popup v-model:show="equipmentShow" position="bottom">
      <div class="van-picker__toolbar">
        <button type="button" class="van-picker__cancel" style="margin: 0 0.5em" @click="equipmentShow = false">
          {{ $t("device.cancel") }}
        </button>
        <div class="van-ellipsis van-picker__title">
          {{ $t("device.selectDevice") }}
        </div>
        <button type="button" class="van-picker__confirm" style="margin: 0 0.5em" @click="equipmentShow = false">
          {{ $t("device.confirm") }}
        </button>
      </div>
      <div class="checkbox-con" style="max-height: 264px; overflow-y: auto">
        <van-checkbox-group v-model="equipmentIds" @change="equipemntIdsChange" ref="checkboxGroup">
          <van-cell-group>
            <van-cell v-for="(item, index) in equipmentList" clickable :key="index" :title="item.label"
              @click="equipementCheckItem(item.value)">
              <template #right-icon>
                <van-checkbox :name="item.value" @click.stop />
              </template>
            </van-cell>
          </van-cell-group>
        </van-checkbox-group>
      </div>
    </van-popup>
  </div>
</template>
<script>
import { showSuccessToast, showFailToast, showToast } from "vant";
import { onMounted, ref, watch } from "vue";
import sHeader from "@/components/SimpleHeader";
import { getLoginUser } from "@/common/js/utils";
import {
  getListEquipment,
  addAlaramClock,
  getAlaramClock,
  alaramClockUpdate,
} from "@/service/device";
import { useRoute, useRouter } from "vue-router";
import { useI18n } from "vue-i18n";

export default {
  name: "alarm-clock-set",
  components: { sHeader },
  setup() {
    const { t } = useI18n();
    const onConfirm = ({ selectedValues }) => {
      currentTime.value = selectedValues;
      currentTimeShow.value = false;
      hour.value = selectedValues.join(':');
    };
    // 周
    const weekDayList = ref([
      {
        name: t("alarmClockSet.sunday"),
        value: '7',
      },
      {
        name: t("alarmClockSet.monday"),
        value: '1',
      },
      {
        name: t("alarmClockSet.tuesday"),
        value: '2',
      },
      {
        name: t("alarmClockSet.wednesday"),
        value: '3',
      },
      {
        name: t("alarmClockSet.thursday"),
        value: '4',
      },
      {
        name: t("alarmClockSet.friday"),
        value: '5',
      },
      {
        name: t("alarmClockSet.saturday"),
        value: '6',
      },
    ]);
    // 选中的周
    const selectList = ref(['1', '2', '3', '4', '5', '6', '7']);
    // 点击周
    const selectDayClk = (val) => {
      // 如果已经选过了，则需要取消
      if (selectList.value.includes(val)) {
        const idx = selectList.value.indexOf(val);
        selectList.value.splice(idx, 1);
      } else {
        selectList.value.push(val);
      }
    };
    // 全选
    const checkedAll = ref(true);
    const checkedAllClk = () => {
      checkedAll.value = !checkedAll.value;
      if (!checkedAll.value) {
        selectList.value = ['1', '2', '3', '4', '5', '6', '7'];
      } else {
        selectList.value = [];
      }
    };
    // 监听选中的周
    watch(() => selectList, (newVal) => {
      if (newVal.value.length === 7) {
        checkedAll.value = true;
      } else {
        checkedAll.value = false;
      }
    }, { immediate: true, deep: true });
    const user = getLoginUser();
    const route = useRoute();
    const router = useRouter();
    const equipmentIds = ref([]);
    const equipmentIdsText = ref("");
    const equipmentShow = ref(false);
    const equipmentList = ref([]);
    // 初始化页面获取列表
    onMounted(async () => {
      if (route.query.deviceId) {
        equipmentIds.value.push(route.query.deviceId);
      }
      if (route.query.alarmId) {
        getAlaramClockFun();
      }
      getListEquipmentFun();
    });
    let oldAlarmClock = {};
    // 闹钟回显
    const getAlaramClockFun = async () => {
      const { data } = await getAlaramClock({ id: route.query.alarmId });
      if (data.code) {
        oldAlarmClock = data.data;
        // 回显时间
        const hourVal = data.data.hour.slice(0, 5).split(":");
        currentTime.value = hourVal;
        hour.value = data.data.hour.slice(0, 5);
        alarmClockName.value = data.data.name;
        checked.value = data.data.status === "1";
        alarmClockType.value = data.data.type;
        // 选中的周
        selectList.value = data.data.week.split(',');
        equipmentIds.value = data.data.equipmentIds.split(",");
        equipmentIds.value = equipmentIds.value.filter((item) => item !== "");
        isEquipemntIdsText();
        // 回显闹钟类型
        const statusTxt = alarmClockTypeOptions.value.filter(
          (item) => item.value === data.data.type
        );
        alarmClockTypeText.value = statusTxt[0]["text"];
      } else {
        showFailToast(data.message);
      }
    };
    // 获取旗下机器
    const getListEquipmentFun = async () => {
      const { data } = await getListEquipment({ adminId: user.id });
      if (data.code === "00000") {
        equipmentList.value = [
          { label: t("device.allMachines"), value: "All" },
        ].concat(
          data.data.map((item, index) => {
            return { label: item.name || index, value: item.id.toString() };
          })
        );
        isEquipemntIdsText();
      } else {
        showFailToast(data.message);
      }
    };
    // 设备多选
    const equipementCheckItem = (index) => {
      const list = equipmentIds.value.filter((v) => v === index);
      if (list.length > 0) {
        equipmentIds.value = equipmentIds.value.filter((v) => v !== index);
      } else {
        equipmentIds.value.push(index);
      }
      isAllEquipement();
    };
    const equipemntIdsChange = (event) => {
      const isAll = equipmentIds.value.filter((v) => v === "All");
      if (
        isAll.length > 0 &&
        equipmentIds.value.length !== equipmentList.value.length
      ) {
        equipmentIds.value = [];
        isAllEquipement();
      } else {
        equipmentIds.value = event;
        isEquipemntIdsText();
      }
    };
    const isEquipemntIdsText = () => {
      const equipmentLabelList = [];
      const isAll = equipmentIds.value.filter((v) => v === "All");
      if (isAll.length > 0) {
        equipmentLabelList.push(t("device.allMachines"));
      } else {
        equipmentIds.value.forEach((item) => {
          const equipment = equipmentList.value.filter((v) => v.value === item);
          if (equipment.length > 0) {
            equipmentLabelList.push(equipment[0].label);
          }
        });
      }
      equipmentIdsText.value = equipmentLabelList.join(",");
    };
    const isAllEquipement = () => {
      const isAll = equipmentIds.value.filter((v) => v === "All");
      if (isAll.length > 0) {
        equipmentIds.value = equipmentList.value.map((item) => {
          return item.value;
        });
      }
      isEquipemntIdsText();
    };

    const hour = ref("");
    const currentTime = ref(['12', '00']);
    const currentTimeShow = ref(false);
    const alarmClockTypeText = ref("");
    const alarmClockType = ref("");
    const alarmClockTypeShow = ref(false);
    const alarmClockTypeOptions = ref([
      { text: t("device.furnaceHeadOn"), value: "0" },
      { text: t("device.furnaceHeadClosed"), value: "1" },
      { text: t("device.startSleep"), value: "2" },
      { text: t("device.endSleep"), value: "3" },
    ]);
    const alarmClockTypeFinish = ({ selectedOptions }) => {
      alarmClockTypeShow.value = false;
      alarmClockTypeText.value = selectedOptions
        .map((option) => option.text)
        .join("/");
    };

    const alarmClockName = ref("");
    const checked = ref(false);
    const submitSet = async () => {
      const equipmentIdsList = equipmentIds.value.filter((v) => v !== "All");
      // 选中的周
      const weekParams = selectList.value.join(',');
      const params = {
        adminId: user.id,
        equipmentIds: equipmentIdsList.join(","),
        hour: hour.value,
        name: alarmClockName.value,
        status: checked.value ? "1" : "0",
        type: alarmClockType.value,
        week: weekParams,
      };
      // 校验
      if (!params.equipmentIds) {
        showToast(t("device.selectDevice"));
        return;
      } else if (!params.hour) {
        showToast(t("device.selectTime"));
        return;
      } else if (!params.week) {
        showToast(t("device.repetitionsPlaceholder"));
        return;
      } else if (!params.type) {
        showToast(t("device.alarmTypePlaceholder"));
        return;
      }
      if (route.query.alarmId) {
        params.id = oldAlarmClock.id;
      }
      const { data } = route.query.deviceId
        ? await addAlaramClock(params)
        : await alaramClockUpdate(params);
      if (data.code) {
        route.query.deviceId
          ? showSuccessToast(t("device.successfullyAddedAlarmClock"))
          : showSuccessToast(t("device.modificationSucceeded"));
        setTimeout(() => {
          router.back();
        }, 1000);
      } else {
        showFailToast(data.message);
      }
    };
    return {
      equipmentIds,
      equipmentIdsText,
      equipmentShow,
      equipmentList,
      equipementCheckItem,
      equipemntIdsChange,
      hour,
      currentTime,
      currentTimeShow,
      alarmClockTypeText,
      alarmClockTypeShow,
      alarmClockType,
      alarmClockTypeOptions,
      alarmClockTypeFinish,
      alarmClockName,
      checked,
      submitSet,
      weekDayList,
      selectList,
      selectDayClk,
      checkedAll,
      checkedAllClk,
      onConfirm,
    };
  },
};
</script>
<style lang="less" scoped>
.alarm-config-container {
  --card-bg: #ffffff;
  --border-color: #ebedf0;
  --primary-color: #2c87c8;
  --text-primary: #323233;
  --text-secondary: #969799;

  background: #f7f8fa;
  min-height: 100vh;

  .config-card {
    margin: 16px;
    padding: 16px;
    background: var(--card-bg);
    border-radius: 12px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);

    .form-field {
      margin: 8px 0;
      padding: 12px 16px;
      background: #f8f9fa;
      border-radius: 8px;

      :deep(.van-field__label) {
        width: 6em;
        color: var(--text-primary);
      }

      .field-icon {
        font-size: 18px;
        margin-right: 12px;
        color: var(--primary-color);
      }
    }
  }

  .repeat-section {
    margin: 20px 0;

    .section-title {
      display: flex;
      align-items: center;
      font-size: 15px;
      color: var(--text-primary);
      margin: 0 0 16px 0;

      .title-icon {
        margin-right: 8px;
        color: var(--primary-color);
      }
    }

    .quick-select {
      margin-bottom: 12px;

      :deep(.van-checkbox) {
        --van-checkbox-size: 18px;
      }
    }

    .day-grid {
      display: grid;
      grid-template-columns: repeat(4, 1fr);
      gap: 10px;

      .day-item {
        padding: 10px;
        text-align: center;
        border-radius: 6px;
        background: #f8f9fa;
        color: var(--text-secondary);
        transition: all 0.2s;

        &.active {
          background: var(--primary-color);
          color: white;
          font-weight: 500;
        }
      }
    }
  }

  .switch-section {
    display: flex;
    align-items: center;
    gap: 30px; // 控制文字和按钮间距
    padding: 13px 15px;
    background: #f8f9fa;
    border-radius: 8px;
    margin-bottom: 10px;


    .switch-label {
      display: flex;
      align-items: center;
      color: var(--text-primary);

      .switch-icon {
        font-size: 20px;
        margin-right: 15px;
        color: var(--primary-color);
      }
    }
  }

  .action-bar {
    padding: 0 16px 32px;

    .submit-btn {
      width: 100%;
      height: 44px;
      font-size: 16px;
      letter-spacing: 1px;

      .btn-icon {
        font-size: 16px;
        margin-right: 2px;
        vertical-align: -2px;
      }
    }
  }
}
</style>
