<template>
  <el-form ref="searchDeviceForm" :inline="true" :model="searchDevice">
    <el-form-item label="选择站点">
      <el-select v-model="searchDevice.deviceId" placeholder="请选择站点" @change="change">
        <el-option v-if="showAll" label="全部" value></el-option>
        <el-option v-for="item in devices" :key="item.deviceId" :label="item.address" :value="item.deviceId"></el-option>
      </el-select>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="onSubmit"><i class="el-icon-search mr-2"></i>查询</el-button>
    </el-form-item>
    <el-form-item v-if="showRefresh">
      <el-button type="primary" @click="$emit('refresh')"><i class="el-icon-refresh mr-2"></i>刷新</el-button>
    </el-form-item>
  </el-form>
</template>

<script setup>
import { computed, defineEmits, defineProps, reactive, ref, watch } from 'vue';
import { useStore } from 'vuex';
import { useRouter } from 'vue-router';

defineProps({ showRefresh: Boolean });
const emit = defineEmits(['getDate', 'refresh']);
const router = useRouter();
const searchDevice = reactive({ deviceId: '' });

const searchDeviceForm = ref(null); // form

const store = useStore();
const devices = computed(() => store.state.device.devices);
const currentDeviceId = computed(() => store.state.device.currentDeviceId); // 正在操作的设备的id
const showAll = computed(() => router.currentRoute.value.name === 'devices'); // 是否显示全部

// 监听currentDeviceId
watch(
  () => currentDeviceId.value,
  newValue => {
    if (newValue && searchDevice.deviceId !== newValue) {
      searchDevice.deviceId = newValue;
    }
  },
  { immediate: true },
);

const change = e => {
  store.commit('device/setCurrentDeviceId', e);
};

const onSubmit = () => {
  searchDeviceForm.value.validate(() => {
    emit('search');
  });
};
</script>
