<template>
  <!-- 设置闹钟 -->
  <div class="alarmClockSetPage flex-col">
    <s-header :name="$t('device.setAlarm')" :noback="false"></s-header>
    <div class="alarmClockSetBox flex-col">
      <div style="width: 100%; height: 18px"></div>
      <van-field class="equipmentField" is-link readonly :label="$t('device.equipmentName')"
        :placeholder="$t('device.selectDevice')" v-model="equipmentIdsText" @click="equipmentShow = true" />
      <van-field v-model="hour" is-link readonly :label="$t('device.selectTime')" :placeholder="$t('device.selectTime')"
        @click="currentTimeShow = true" class="field" />
      <div class="repeatTimeBox">
        <span class="txt6">{{
          $t("device.selectTheNumberOfAlarmClockRepetitions")
        }}</span>
        <div class="o-pl-15 o-ptb-10">
          <van-checkbox @click="checkedAllClk" v-model="checkedAll">全选</van-checkbox>
        </div>
        <div class="l-flex-between dayCon">
          <div @click="selectDayClk(item.value)" class="dayName" :class="{ active: selectList.includes(item.value) }"
            v-for="(item, index) in weekDayList" :key="index">
            {{ item.name }}
          </div>
        </div>
      </div>
      <van-field v-model="alarmClockTypeText" is-link readonly :label="$t('device.alarmTypeLabel')"
        :placeholder="$t('device.alarmTypePlaceholder')" @click="alarmClockTypeShow = true" class="field" />
      <van-field v-model="alarmClockName" name="alarmClockName" :label="$t('device.alarmNameLabel')"
        :placeholder="$t('device.alarmNamePlaceholder')" />
      <div class="ImageText1 flex-col">
        <div class="mod4 flex-row justify-between">
          <div class="TextGroup1 flex-col">
            <span class="info4">{{ $t("device.effectiveImmediately") }}：</span>
          </div>
          <div class="section1 flex-col">
            <van-switch v-model="checked" />
          </div>
        </div>
      </div>
      <van-row justify="space-around" style="padding: 1em">
        <van-button span="5" round type="primary" style="height: 2em; padding: 0 2em" @click="submitSet">
          {{ $t("device.submitSettings") }}</van-button>
      </van-row>
    </div>
    <van-popup v-model:show="alarmClockTypeShow" round position="bottom">
      <van-cascader v-model="alarmClockType" :title="$t('device.alarmTypePlaceholder')" :options="alarmClockTypeOptions"
        @close="alarmClockTypeShow = false" @finish="alarmClockTypeFinish" />
    </van-popup>
    <van-popup v-model:show="currentTimeShow" round position="bottom">
      <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" />
              </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, styleUrl } 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 onConfirm = ({ selectedValues }) => {
      console.log(selectedValues);
      currentTime.value = selectedValues;
      currentTimeShow.value = false;
      hour.value = selectedValues.join(':');
      console.log(hour.value);
    };
    // 周
    const weekDayList = ref([
      {
        name: '日',
        value: '7',
      },
      {
        name: '一',
        value: '1',
      },
      {
        name: '二',
        value: '2',
      },
      {
        name: '三',
        value: '3',
      },
      {
        name: '四',
        value: '4',
      },
      {
        name: '五',
        value: '5',
      },
      {
        name: '六',
        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 { t } = useI18n();
    const user = getLoginUser();
    const route = useRoute();
    const router = useRouter();
    const equipmentIds = ref([]);
    const equipmentIdsText = ref("");
    const equipmentShow = ref(false);
    const equipmentList = ref([]);
    // 初始化页面获取列表
    onMounted(async () => {
      // 加载样式
      styleUrl('alarmClock');
      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(",");
        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);
      console.log("data", data);
      if (data.code) {
        showSuccessToast(t("device.successfullyAddedAlarmClock"));
        router.back();
      } 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>
@import "../../../common/style/common";
</style>
