<template>
  <div class="container">
    <a-card class="general-card">
      <a-row>
        <a-col :flex="1">
          <a-form
            :model="formModel"
            :label-col-props="{ span: 4 }"
            :wrapper-col-props="{ span: 18 }"
            label-align="left"
          >
            <a-row :gutter="16">
              <a-col :span="6">
                <a-form-item
                  field="address"
                  :label="t('device.form.address')"
                  label-col-flex="50px"
                >
                  <a-input
                    v-model="formModel.address"
                    :placeholder="t('device.form.address')"
                    allow-clear
                  />
                </a-form-item>
              </a-col>
              <a-col :span="6">
                <a-form-item
                  field="name"
                  :label="t('device.form.name')"
                  label-col-flex="50px"
                >
                  <a-input
                    v-model="formModel.name"
                    :placeholder="t('device.form.name')"
                    allow-clear
                  />
                </a-form-item>
              </a-col>
              <a-col :span="6">
                <a-form-item
                  field="entityType"
                  :label="t('device.form.entityType')"
                  label-col-flex="60px"
                >
                  <a-select
                    v-model="formModel.entityType"
                    :placeholder="t('device.form.entityType')"
                    allow-clear
                    @clear="formModel.entityType = null"
                  >
                    <a-option
                      v-for="item of deviceTypeList"
                      :value="item.dictCode"
                      :label="item.name"
                    />
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :span="6">
                <a-form-item
                  field="status"
                  :label="t('device.form.status')"
                  label-col-flex="60px"
                >
                  <a-select
                    v-model="formModel.status"
                    :placeholder="t('device.form.status')"
                    allow-clear
                    @clear="formModel.status = null"
                  >
                    <a-option
                      v-for="item of deviceStatusList"
                      :value="item.dictCode"
                      :label="item.name"
                    />
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :span="6">
                <a-form-item
                  :label="t('device.form.timeRange')"
                  label-col-flex="60px"
                >
                  <a-range-picker v-model="formModel.time" />
                </a-form-item>
              </a-col>
            </a-row>
          </a-form>
        </a-col>
        <a-divider :style="{ height: '84px' }" direction="vertical" />
        <a-col :flex="'86px'">
          <a-space :size="10">
            <a-button type="primary" @click="search">
              <template #icon>
                <icon-search />
              </template>
              {{ t('searchTable.form.search') }}
            </a-button>
            <a-button @click="reset">
              <template #icon>
                <icon-refresh />
              </template>
              {{ t('searchTable.form.reset') }}
            </a-button>
          </a-space>
          <a-space class="right-side">
            <a-button type="primary" @click="downloadExcel">
              <template #icon>
                <icon-download />
              </template>
              {{ t('searchTable.form.export') }}
            </a-button>
          </a-space>
        </a-col>
      </a-row>
      <a-table
        row-key="name"
        :loading="loading"
        :pagination="pagination"
        :columns="cloneColumns as TableColumnData[]"
        :data="renderData"
        :bordered="false"
        :size="size"
        :scrollbar="true"
        @page-change="onPageChange"
        @row-dblclick="handleClick"
      >
        <template #index="{ rowIndex }">
          {{ rowIndex + 1 + (pagination.current - 1) * pagination.pageSize }}
        </template>

        <template #entityType="{ record }">
          <span>
            {{
              deviceTypeList.find(item => item.dictCode === record.entityType)
                ?.name
            }}
          </span>
        </template>
        <template #status="{ record }">
          <BTag :status="record.status">
            {{
              deviceStatusList.find(item => item.dictCode === record.status)
                ?.name
            }}
          </BTag>
        </template>
        <template #time="{ record }">
          <span>{{
            record.time && dayjs(record.time).format('YYYY-MM-DD HH:mm:ss')
          }}</span>
        </template>
      </a-table>
    </a-card>
    <DeviceInfoDialog
      v-model="showDeviceInfoDialog"
      :id="deviceId"
      :deviceInfo="deviceInfo"
      :deviceType="deviceType"
    >
    </DeviceInfoDialog>
  </div>
</template>

<script lang="ts" setup name="DevicePage">
import {
  ref,
  reactive,
  shallowRef,
  h,
  getCurrentInstance,
  computed,
} from 'vue';
import { queryDeviceList, exportDeviceList } from '@/api/device';
import type { DeviceParams, DataList } from '@/api/device';
import { SizeProps, Pagination } from '@/types/global';
import BTag from '@/components/business/b-tag/index.vue';
import type { TableColumnData } from '@arco-design/web-vue';
import useLoading from '@/hooks/loading';
import { useI18n } from 'vue-i18n';
import type { AdditionalProp } from '@/api/dict';
import dayjs from 'dayjs';
import { useIntervalFn } from '@vueuse/core';
import DeviceInfoDialog from './device-info/index.vue';
import useDictList from '@/hooks/dict-list';
import { downLoadFun, DeviceInfo } from '@/utils/const';

const { t } = useI18n();
const { loading, setLoading } = useLoading(true);
const cloneColumns = computed(() => [
  {
    title: t('searchTable.table.number'),
    dataIndex: 'index',
    slotName: 'index',
    ellipsis: true,
    tooltip: true,
    width: 70,
  },
  {
    title: t('device.table.time'),
    dataIndex: 'time',
    slotName: 'time',
    ellipsis: true,
  },
  {
    title: t('device.form.status'),
    dataIndex: 'status',
    slotName: 'status',
    width: 120,
  },
  {
    title: t('device.form.name'),
    dataIndex: 'name',
    slotName: 'name',
  },
  {
    title: t('device.form.entityType'),
    dataIndex: 'entityType',
    slotName: 'entityType',
  },

  {
    title: t('device.form.address'),
    dataIndex: 'address',
    ellipsis: true,
    tooltip: true,
  },
]);
const basePagination: Pagination = {
  current: 1,
  pageSize: 20,
};
const pagination = reactive({
  ...basePagination,
});
const generateFormModel = () => {
  return {
    pageIndex: 1,
    pageSize: 20,
    name: null,
    address: null,
    status: null,
    startTime: null,
    endTime: null,
    time: ['', ''],
    entityType: null,
  } as DeviceParams;
};
const renderData = ref<DataList[]>([] as DataList[]);
const size = ref<SizeProps>('medium');
const formModel = ref<DeviceParams>(generateFormModel());
const showDeviceInfoDialog = shallowRef<boolean>(false);
const this_ = getCurrentInstance()?.appContext.config.globalProperties;
const deviceInfo = ref<DeviceInfo[]>([] as DeviceInfo[]);
const deviceTypeList = ref<AdditionalProp[]>([] as AdditionalProp[]);
const deviceStatusList = ref<AdditionalProp[]>([] as AdditionalProp[]);
const deviceId = shallowRef<number>(0);
const deviceType = shallowRef<number | null>(1);
useDictList(['DeviceType', 'DeviceStatus']).then(res => {
  deviceTypeList.value.push(...res['DeviceType']);
  deviceStatusList.value.push(...res['DeviceStatus']);
});
function searchTable() {
  // setLoading(true);
  const [startTime, endTime] = formModel.value.time
    ? formModel.value.time
    : ['', ''];
  formModel.value.startTime = startTime ? startTime : null;
  formModel.value.endTime = endTime ? endTime : null;

  queryDeviceList(formModel.value)
    .then(res => {
      pagination.current = formModel.value.pageIndex;
      pagination.pageSize = pagination.pageSize;
      pagination.total = res.totalCount;
      renderData.value = res.data;
    })
    .finally(() => {
      setLoading(false);
    });
}
searchTable();
const { pause, resume, isActive } = useIntervalFn(() => {
  /* your function */
  formModel.value.pageIndex = 1;
  searchTable();
}, 1000);
const search = () => {
  searchTable();
};
const reset = () => {
  formModel.value = generateFormModel();
};
const downloadExcel = () => {
  setLoading(true);
  const [startTime, endTime] = formModel.value.time;
  formModel.value.startTime = startTime ? startTime : null;
  formModel.value.endTime = endTime ? endTime : null;
  exportDeviceList(formModel.value)
    .then(res => {
      if (!res.success) {
        return;
      }
      const url = res.data;
      downLoadFun(url);
    })
    .finally(() => {
      setLoading(false);
    });
};
const onPageChange = (current: number) => {
  formModel.value.pageIndex = current;
  if (current === 1) {
    resume();
  } else {
    pause();
  }
  searchTable();
};

const handleClick = (value: DataList) => {
  if (value.data) {
    deviceInfo.value.length = 0;
    const obj = JSON.parse(value.data);
    for (const key in obj) {
      deviceInfo.value.push({
        label: key,
        value: obj[key],
      });
    }
    console.log('dddd', value.entityType);
    deviceType.value = value.entityType;
    showDeviceInfoDialog.value = true;
  } else {
    this_ &&
      this_.$message.warning('No device information available at the moment');
  }
};
</script>

<style lang="less" scoped>
.container {
  padding: 10px 10px 20px;

  .general-card {
    padding-top: 20px;

    .right-side {
      margin-top: 20px;
    }
  }
}
</style>
