<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="outer4 flex-row justify-between">
          <div
            class="mod3 flex-col"
            :class="{ active: repeatTime === '1' }"
            @click="dayClick()"
          >
            <span class="word2">{{$t('device.everyDay')}}</span>
          </div>
          <button
            class="Button1 flex-col"
            :class="{ active: repeatTime === '2' }"
            @click="weekdayClick()"
          >
            <span class="word3">{{$t('device.weekday')}}</span>
          </button>
        </div>
        <div class="outer5 flex-row justify-between">
          <div
            class="bd1 flex-col"
            :class="{ active: repeatTime === '3' }"
            @click="weekendClick()"
          >
            <span class="word4">{{$t('device.weekend')}}</span>
          </div>
          <div
            class="bd2 flex-col"
            :class="{ active: repeatTime === '4' }"
            @click="customClick()"
          >
            <span class="word5">{{$t('device.custom')}}</span>
          </div>
        </div>
      </div>
      <van-field
        v-if="repeatTime === '4'"
        v-model="week"
        name="week"
        label="{{$t('device.repetitionsLabel')}}"
        :placeholder="$t('device.repetitionsPlaceholder')"
      />
      <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-datetime-picker
        v-model="currentTime"
        type="time"
        title="{{$t('device.clickToSelectTheTime')}}"
        @confirm="
          currentTimeShow = false;
          hour = currentTime;
        "
        @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>
    <nav-bar></nav-bar>
  </div>
</template>
<script>
import { Toast } from "vant";
import { onMounted, ref } from "vue";
import navBar from "@/components/NavBar";
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, navBar },
  setup() {
    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 () => {
      console.log('onMounted', route.query.alarmId);
      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;
        hour.value = data.data.hour;
        alarmClockName.value = data.data.name;
        checked.value = data.data.status === '1';
        alarmClockType.value = data.data.type;
        repeatTime.value === '4'
        if (data.data.week === '1,2,3,4,5,6,7') {
          repeatTime.value === '1';
        }
        if (data.data.week === '1,2,3,4,5') {
          repeatTime.value === '2';
        }
        if (data.data.week === '6,7') {
          repeatTime.value === '3';
        }
        week.value = data.data.week;
        equipmentIds.value = data.data.equipmentIds.split(',');
        isEquipemntIdsText();
      } else { Toast.fail(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) => {
            return { label: item.name, value: item.id.toString() };
          })
        );
        isEquipemntIdsText();
      } else {
        Toast.fail(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("");
    const currentTimeShow = ref(false);

    const repeatTime = ref("1");
    const dayClick = () => { repeatTime.value = "1"; };
    const weekdayClick = () => { repeatTime.value = "2"; };
    const weekendClick = () => { repeatTime.value = "3"; };
    const customClick = () => {
      repeatTime.value = "4";
    };
    const week = ref('');

    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');
      let weekParams = '';
      if (repeatTime.value === '1') { weekParams = '1,2,3,4,5,6,7'; }
      if (repeatTime.value === '2') { weekParams = '1,2,3,4,5'; }
      if (repeatTime.value === '3') { weekParams = '6,7'; }
      if (repeatTime.value === '4') { weekParams = week.value; }
      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 (route.query.alarmId) { params.id = oldAlarmClock.id; }
      const { data } = await route.query.deviceId ? addAlaramClock(params) : await alaramClockUpdate(params);
      if (data.code) {
        Toast.success(t('device.successfullyAddedAlarmClock'));
        router.back();
      } else { Toast.fail(data.message); }
    }
    return {
      equipmentIds,
      equipmentIdsText,
      equipmentShow,
      equipmentList,
      equipementCheckItem,
      equipemntIdsChange,
      hour,
      currentTime,
      currentTimeShow,
      repeatTime,
      week,
      dayClick,
      weekdayClick,
      weekendClick,
      customClick,
      alarmClockTypeText,
      alarmClockTypeShow,
      alarmClockType,
      alarmClockTypeOptions,
      alarmClockTypeFinish,
      alarmClockName,
      checked,
      submitSet
    };
  },
};
</script>
<style lang="less" scoped>
@import "../../../common/style/common";
@import "./index.less";
</style>
  