<template>
  <el-form :inline="true" :model="searchDevice" ref="searchDeviceForm">
    <el-form-item label="选择站点">
      <el-select v-model="searchDevice.deviceId" placeholder="请选择站点">
        <el-option label="全部" value></el-option>
        <el-option :label="item.address" :value="item.deviceId" v-for="item in devices" :key="item.deviceId"></el-option>
      </el-select>
    </el-form-item>

    <el-form-item label="选择日期">
      <el-date-picker
        v-model="searchDevice.date"
        type="daterange"
        range-separator="-"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
      ></el-date-picker>
    </el-form-item>

    <el-form-item>
      <el-button type="primary" @click="onSubmit">查询</el-button>
    </el-form-item>
  </el-form>
</template>

<script setup>
import { reactive, ref, computed, defineEmits } from 'vue';
import { useStore } from 'vuex';

const emit = defineEmits(['search']);
const searchDevice = reactive({ deviceId: '', date: '' });
const searchDeviceForm = ref(null); // form
const store = useStore();
const devices = computed(() => store.state.device.devices);

/**
 * 格式化日期
 * @param {Date} date 选择的日期
 */
const formatDate = date => {
  const year = date.getFullYear();
  const month = date.getMonth() + 1;
  const day = date.getDate();
  return `${year}-${month}-${day}`;
};

// 提交
const onSubmit = () => {
  searchDeviceForm.value.validate(() => {
    const { deviceId, date } = searchDevice;
    if (date) {
      const daterange = [formatDate(date[0]), formatDate(date[1])];
      emit('search', { deviceId, date: daterange });
    } else {
      emit('search', { deviceId, date });
    }
  });
};
</script>
