<script setup lang="ts">
import { computed, onMounted, ref } from 'vue';

import { useRequest } from '@/hooks/request';
import { t } from '@/i18n';
import { getSmartCtrlLog, noPaginationDevicesList } from '@/api';
import { disabledDate } from '@/utils';

import type { ColumnType, TableProps } from 'ant-design-vue/es/table';
import type { AllDevicesList, PageParams, RangeValue, SmartCtrlLogItem } from '@/types';

const timeRange = ref<RangeValue>();
const selectedDevices = ref<number[]>([]);
const deviceList = ref<AllDevicesList[]>([]);
const searchContent = ref('');

const logList = ref<SmartCtrlLogItem[]>([]);
const logTotal = ref(0);
const pageParams = ref<PageParams>({
  pageIndex: 1,
  pageSize: 10,
  pageSorts: [
    {
      column: 'id',
      asc: false,
    },
  ],
});

const columns = computed<ColumnType<SmartCtrlLogItem>[]>(() => {
  return [
    {
      title: t('common.device'),
      dataIndex: 'deviceName',
      key: 'deviceName',
    },
    {
      title: t('common.content'),
      dataIndex: 'content',
      key: 'content',
    },
    {
      title: t('common.time'),
      dataIndex: 'updateTime',
      key: 'updateTime',
    },
  ];
});

onMounted(() => {
  getDeviceList();
  getLogList();
});

const { handleRequest } = useRequest();

const getDeviceList = () => {
  handleRequest(async () => {
    deviceList.value = await noPaginationDevicesList();
  });
};

const { isLoading: isLogLoading, handleRequest: handleLogRequest } = useRequest();

const getLogList = () => {
  handleLogRequest(async () => {
    const { records, total } = await getSmartCtrlLog({
      ...pageParams.value,
      deviceIds: selectedDevices.value.join(','),
      searchContent: searchContent.value,
      startTime: timeRange.value?.[0].format('YYYY-MM-DD HH:mm:ss'),
      endTime: timeRange.value?.[1].format('YYYY-MM-DD HH:mm:ss'),
    });

    logList.value = records;
    logTotal.value = total;
  });
};

const filterDevice = (input: string, option: AllDevicesList) => {
  return option.deviceName.toLowerCase().indexOf(input.toLowerCase()) >= 0;
};

const handleSearch = () => {
  pageParams.value.pageIndex = 1;
  getLogList();
};

const handleReset = () => {
  timeRange.value = undefined;
  selectedDevices.value = [];
  searchContent.value = '';
  handleSearch();
};

const handleLogTableChange: TableProps['onChange'] = (pagination) => {
  pageParams.value.pageIndex = pagination.current || 1;
  pageParams.value.pageSize = pagination.pageSize || 10;
  getLogList();
};
</script>

<template>
  <ACard :bordered="false">
    <ARow class="smart-ctrl-log-query" :gutter="[80, 16]">
      <ACol :span="8">
        <div class="smart-ctrl-log-label">{{ $t('logCenter.selectTimeRange') }}</div>
        <ARangePicker
          class="smart-ctrl-log-time"
          v-model:value="timeRange"
          :placeholder="[$t('common.startTime'), $t('common.endTime')]"
          :separator="$t('common.to')"
          :disabled-date="disabledDate"
          show-time
        >
          <template #suffixIcon>
            <SvgIcon name="calendar" color="#333" />
          </template>
        </ARangePicker>
      </ACol>
      <ACol :span="8">
        <div class="smart-ctrl-log-label">{{ $t('logCenter.selectDevice') }}</div>
        <ASelect
          v-model:value="selectedDevices"
          class="smart-ctrl-log-input"
          :options="deviceList"
          :field-names="{ label: 'deviceName', value: 'id' }"
          mode="multiple"
          :max-tag-count="2"
          :max-tag-text-length="10"
          :filter-option="filterDevice"
          :placeholder="$t('logCenter.plzSelectDevice')"
          allow-clear
        />
      </ACol>
      <ACol :span="8">
        <div class="smart-ctrl-log-label">{{ $t('common.inputContent') }}</div>
        <AInput
          v-model:value="searchContent"
          class="smart-ctrl-log-input"
          :placeholder="$t('logCenter.plzEnterContent')"
          allow-clear
        />
      </ACol>
    </ARow>
    <div :span="8" class="smart-ctrl-log-button">
      <AButton @click="handleReset">{{ $t('common.reset') }}</AButton>
      <AButton type="primary" @click="handleSearch">{{ $t('common.query') }}</AButton>
    </div>
    <ATable
      class="hvac-table"
      :data-source="logList"
      :columns="columns"
      row-key="id"
      :loading="isLogLoading"
      :pagination="{
        current: pageParams.pageIndex,
        pageSize: pageParams.pageSize,
        total: logTotal,
        showSizeChanger: true,
        showQuickJumper: true,
        hideOnSinglePage: false,
        showTotal: (total) => $t('common.pageTotal', { total }),
      }"
      @change="handleLogTableChange"
    />
  </ACard>
</template>

<style lang="scss" scoped>
.smart-ctrl-log-query {
  margin-bottom: 16px;

  > .ant-col {
    display: flex;
    align-items: center;
  }
}

.smart-ctrl-log-label {
  width: 70px;
  margin-right: 12px;
  font-size: 14px;
  line-height: 22px;
  color: var(--antd-color-text);
  text-align: right;
}

.smart-ctrl-log-time {
  :deep(input) {
    text-align: center;
  }
}

.smart-ctrl-log-time,
.smart-ctrl-log-input {
  flex: 1;
}

.smart-ctrl-log-button {
  display: flex;
  flex-direction: row-reverse;
  margin-block: 16px;

  button + button {
    margin-right: 12px;
  }
}
</style>
