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

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

import type { ColumnType, TableProps } from 'ant-design-vue/es/table';
import type { DeviceGroupItem, OperateLogItem, OptionItem, PageParams, RangeValue, UserPageItem } from '@/types';

const enum OperateResult {
  All = -1,
  Success,
  Failure,
}

const enum OperatorType {
  All = -2,
  Platform = -1,
}

const timeRange = ref<RangeValue>();
const selectedGroups = ref<number[][]>([]);
const deviceGroup = ref<DeviceGroupItem[]>([]);
const searchContent = ref('');
const selectedResult = ref<number>(OperateResult.All);
const selectedOperator = ref<number>(OperatorType.All);
const userList = ref<UserPageItem[]>([]);

const operatorList = computed<OptionItem<number>[]>(() => {
  return [
    { value: OperatorType.All, label: t('common.entire') },
    { value: OperatorType.Platform, label: t('common.platform') },
    ...userList.value.map((item) => ({
      value: item.id,
      label: item.userName,
    })),
  ];
});

const logList = ref<OperateLogItem[]>([]);
const logTotal = ref(0);
const pageParams = ref<PageParams>({
  pageIndex: 1,
  pageSize: 10,
});

const columns = computed<ColumnType<OperateLogItem>[]>(() => {
  return [
    {
      title: t('common.device'),
      dataIndex: 'deviceName',
      key: 'deviceName',
    },
    {
      title: t('logCenter.deviceParameterChange'),
      dataIndex: 'content',
      key: 'content',
    },
    {
      title: t('common.time'),
      dataIndex: 'createTime',
      key: 'createTime',
    },
    {
      title: t('common.result'),
      dataIndex: 'result',
      key: 'result',
    },
    {
      title: t('common.operator'),
      dataIndex: 'userName',
      key: 'userName',
    },
  ];
});

onMounted(() => {
  getDeviceGroups();
  getUserList();
  getLogList();
});

const { handleRequest } = useRequest();

const getDeviceGroups = () => {
  handleRequest(async () => {
    deviceGroup.value = await getPageList();
  });
};

const getUserList = () => {
  handleRequest(async () => {
    //
  });
};

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

const getLogList = () => {
  handleLogRequest(async () => {
    const { records, total } = await getOperateLog({
      ...pageParams.value,
      groupIds: selectedGroups.value.map((item) => item[1]),
      content: searchContent.value,
      startTime: timeRange.value?.[0].format('YYYY-MM-DD HH:mm:ss'),
      endTime: timeRange.value?.[1].format('YYYY-MM-DD HH:mm:ss'),
      result: selectedResult.value === OperateResult.All ? null : selectedResult.value,
      userId: selectedOperator.value === OperatorType.All ? null : selectedOperator.value,
    });

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

const filterOperator = (input: string, option: OptionItem<number>) => {
  return option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0;
};

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

const handleReset = () => {
  timeRange.value = undefined;
  selectedGroups.value = [];
  searchContent.value = '';
  selectedResult.value = OperateResult.All;
  selectedOperator.value = OperatorType.All;
  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="operate-log-query" :gutter="[80, 16]">
      <ACol :span="8">
        <div class="operate-log-label">{{ $t('logCenter.selectTimeRange') }}</div>
        <ARangePicker
          class="operate-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="operate-log-label">{{ $t('logCenter.selectDeviceGroup') }}</div>
        <ACascader
          v-model:value="selectedGroups"
          class="operate-log-input"
          :placeholder="$t('logCenter.plzSelectDeviceGroup')"
          :field-names="{ label: 'groupName', value: 'id', children: 'deviceGroupChilds' }"
          :options="deviceGroup"
          
          
          :max-tag-count="2"
          :max-tag-text-length="10"
          :show-checked-strategy="Cascader.SHOW_CHILD"
           change-on-select show-search multiple 
        />
      </ACol>
      <ACol :span="8">
        <div class="operate-log-label">{{ $t('common.operationContent') }}</div>
        <AInput
          v-model:value="searchContent"
          class="operate-log-input"
          :placeholder="$t('common.plzEnter')"
          allow-clear
        />
      </ACol>
      <ACol :span="8">
        <div class="operate-log-label">{{ $t('common.operationResult') }}</div>
        <ASelect v-model:value="selectedResult" class="operate-log-input">
          <ASelectOption :value="OperateResult.All">{{ $t('common.entire') }} </ASelectOption>
          <ASelectOption :value="OperateResult.Success">{{ $t('common.success') }} </ASelectOption>
          <ASelectOption :value="OperateResult.Failure">{{ $t('common.failure') }} </ASelectOption>
        </ASelect>
      </ACol>
      <ACol :span="8">
        <div class="operate-log-label">{{ $t('common.operator') }}</div>
        <ASelect
          v-model:value="selectedOperator"
          class="operate-log-input"
          :options="operatorList"
          show-search
          :filter-option="filterOperator"
        />
      </ACol>
      <ACol :span="8" class="operate-log-button">
        <AButton @click="handleReset">{{ $t('common.reset') }}</AButton>
        <AButton type="primary" @click="handleSearch">{{ $t('common.query') }}</AButton>
      </ACol>
    </ARow>
    <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"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'result'">
          <span class="operate-log-result operate-result-success" v-if="record.result === OperateResult.Success">
            {{ $t('common.success') }}
          </span>
          <span class="operate-log-result operate-result-failure" v-else-if="record.result === OperateResult.Failure">
            {{ $t('common.failure') }}
          </span>
        </template>
      </template>
    </ATable>
  </ACard>
</template>

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

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

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

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

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

.operate-log-button {
  display: flex;
  flex-direction: row-reverse;

  button + button {
    margin-right: 12px;
  }
}

.operate-log-result {
  height: 24px;
  padding: 2px 8px;
  font-size: 12px;
  line-height: 20px;
  text-align: center;
  border: 1px solid var(--antd-color-border);
  border-radius: 4px;

  &.operate-result-success {
    color: #52c41a;
    background: #f6ffed;
    border-color: #b7eb8f;
  }

  &.operate-result-failure {
    color: #f56c6c;
    background: #fff1f0;
    border-color: #ffa39e;
  }
}
</style>
