<template>
  <el-form :inline="true" :model="searchDevice" ref="searchDeviceForm">
    <el-form-item label="选择站点">
      <el-select v-model="searchDevice.deviceId" placeholder="请选择站点" @change="change">
        <!-- <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-item v-if="showExport">
      <el-button type="primary" @click="onExport">导出</el-button>
    </el-form-item>
  </el-form>
</template>

<script setup>
import { reactive, ref, computed, defineProps, defineEmits, watch } from 'vue';
import { useStore } from 'vuex';
import dayjs from 'dayjs';
import { exportHistory } from 'apis/index';

const emit = defineEmits(['search']);
const searchDevice = reactive({ deviceId: '', date: [new Date(), new Date()] });
const searchDeviceForm = ref(null); // form
const store = useStore();
const devices = computed(() => store.state.device.devices);
const currentDeviceId = computed(() => store.state.device.currentDeviceId); // 正在操作的设备的id

defineProps({ showExport: Boolean });

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

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

// 生成查询参数
function generateParams() {
  const { deviceId, date } = searchDevice;
  let params = { deviceId, date };

  if (date) {
    const start = +dayjs(date[0]).format('x');
    const end = +dayjs(date[1]).format('x');
    const daterange = [start, end];
    params = { deviceId, date: daterange };
  }

  return params;
}

// 提交
const onSubmit = () => {
  searchDeviceForm.value.validate(() => {
    const params = generateParams();
    emit('search', params);
  });
};

// 导出
async function onExport() {
  try {
    const params = generateParams();
    const resData = await exportHistory(params);
    resData && (window.location.href = resData);
  } catch (error) {
    throw new Error(error);
  }
}
</script>
