<template>
  <el-form :inline="true" :model="searchDevice" ref="searchDeviceForm">
    <el-form-item label="选择站点">
      <el-select v-model="searchDevice.device" 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="选择日期" class="ml-6">
      <el-date-picker
        v-model="searchDevice.value1"
        type="monthrange"
        range-separator="~"
        start-placeholder="开始月份"
        end-placeholder="结束月份"
      >
      </el-date-picker>
    </el-form-item>
    <el-form-item class="ml-6">
      <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(['getDate']);

const searchDevice = reactive({ device: '', value1: '' });

const searchDeviceForm = ref(null); // form

const store = useStore();
const devices = computed(() => store.state.device.devices);

// 日期格式转换
const timeChange = time => {
  const d = new Date(time);
  const y = d.getFullYear();
  let m = d.getMonth() + 1;
  m = m < 10 ? `0${m}` : m;
  return `${y}-${m}`;
};

const onSubmit = () => {
  searchDeviceForm.value.validate(valid => {
    if (valid) {
      const options = { ...searchDevice };
      let date = [];
      if (options.value1) {
        const start = timeChange([...options.value1][0]);
        const end = timeChange([...options.value1][1]);
        date = [start, end];
      }
      const params = { deviceId: options.device, date };
      emit('getDate', params);
    }
  });
};
</script>
