<template>
  <div class="h-full overflow-hidden">
    <n-card title="事件管理" :bordered="false" class="rounded-16px shadow-sm">
      <n-space class="pb-12px" justify="space-between">
        <n-space>
          <n-button type="primary" @click="handleAddTable">
            <icon-ic-round-plus class="mr-4px text-20px" />
            新增
          </n-button>
          <n-button type="success">
            <icon-uil:export class="mr-4px text-20px" />
            导出Excel
          </n-button>
        </n-space>
        <n-space align="center" :size="18">
          <n-input-group>
            <n-input v-model:value="eventName" />
            <n-button type="primary" @click="handleSearch">搜索</n-button>
          </n-input-group>
          <n-button size="small" type="primary" @click="getTableData">
            <icon-mdi-refresh class="mr-4px text-16px" :class="{ 'animate-spin': loading }" />
            刷新表格
          </n-button>
        </n-space>
      </n-space>
      <n-data-table :columns="columns" :data="tableData" :loading="loading" :pagination="pagination" />
      <table-action-modal v-model:visible="visible" :type="modalType" :edit-data="editData" />
      <table-condition-modal
        v-model:conditionVisible="conditionVisible"
        :type="modalConditionType"
        :edit-data="editData"
      />
      <table-setting-modal v-model:settingVisible="settingVisible" :type="ModalSettingType" :edit-data="editData" />
    </n-card>
  </div>
</template>

<script setup lang="tsx">
import { reactive, ref } from 'vue';
import type { Ref } from 'vue';
import { NButton, NPopconfirm, NSpace, NTag } from 'naive-ui';
import type { DataTableColumns, PaginationProps } from 'naive-ui';
import { EventIsShowLabels } from '@/constants';
import { useBoolean, useLoading } from '@/hooks';
import { fetchEventDelete, fetchEventList } from '@/service/api/event';
import type { ModalType } from './components/table-action-modal.vue';
import type { ModalConditionType } from './components/table-condition-modal.vue';
import TableSettingModal, { ModalSettingType } from './components/table-setting-model.vue';
import TableActionModal from './components/table-action-modal.vue';
import TableConditionModal from './components/table-condition-modal.vue';

const { loading, startLoading, endLoading } = useLoading(false);
const { bool: visible, setTrue: openModal } = useBoolean();
const { bool: conditionVisible, setTrue: openEventModal } = useBoolean();
const { bool: settingVisible, setTrue: openSettingModal } = useBoolean();

const eventName = ref('');
const tableData = ref<BackgroundEvent.Event[]>([]);

function setTableData(data: BackgroundEvent.Event[]) {
  tableData.value = data;
}

async function getTableData() {
  startLoading();
  const { data } = await fetchEventList(1, 100, eventName.value);
  if (data) {
    setTimeout(() => {
      setTableData(data);
      endLoading();
    }, 1000);
  }
}

const columns: Ref<DataTableColumns<BackgroundEvent.Event>> = ref([
  {
    type: 'selection',
    align: 'center'
  },
  {
    key: 'index',
    title: '序号',
    align: 'center'
  },
  {
    key: 'name',
    title: '事件名称',
    align: 'center'
  },
  {
    key: 'is_show',
    title: '是否启用',
    align: 'center',
    render: row => {
      if (row.is_show) {
        const tagTypes: Record<BackgroundEvent.IsShowKey, NaiveUI.ThemeColor> = {
          '0': 'error',
          '1': 'success',
          '2': 'warning'
        };

        return <NTag type={tagTypes[row.is_show]}>{EventIsShowLabels[row.is_show]}</NTag>;
      }

      return <span></span>;
    }
  },
  {
    key: 'remarks',
    title: '事件描述',
    align: 'center'
  },
  {
    key: 'conditions',
    title: '事件执行条件',
    align: 'center',
    render: row => {
      return (
        <NSpace justify={'center'}>
          <NButton type="info" size={'small'} onClick={() => handleCondition(row.id)}>
            设置
          </NButton>
        </NSpace>
      );
    }
  },
  {
    key: 'actions',
    title: '操作',
    align: 'center',
    render: row => {
      return (
        <NSpace justify={'center'}>
          <NButton type="info" size={'small'} onClick={() => handleEditTable(row.id)}>
            编辑
          </NButton>
          <NButton type="warning" size={'small'} onClick={() => handleSetting(row.id)}>
            影响设置
          </NButton>
          <NPopconfirm onPositiveClick={() => handleDeleteTable(row.id)}>
            {{
              default: () => '确认删除',
              trigger: () => (
                <NButton type="error" size={'small'}>
                  删除
                </NButton>
              )
            }}
          </NPopconfirm>
        </NSpace>
      );
    }
  }
]) as Ref<DataTableColumns<BackgroundEvent.Event>>;

const modalType = ref<ModalType>('add');
const modalConditionType = ref<ModalConditionType>('add');
const modalSettingType = ref<ModalSettingType>('add');

function setModalType(type: ModalType) {
  modalType.value = type;
}

function setModalConditionType(type: ModalConditionType) {
  modalConditionType.value = type;
}

function setModalSettingType(type: ModalSettingType) {
  modalSettingType.value = type;
}

const editData = ref<BackgroundEvent.Event | null>(null);

function setEditData(data: BackgroundEvent.Event | null) {
  editData.value = data;
}

function handleAddTable() {
  openModal();
  setModalType('add');
}

function handleEditTable(rowId: number) {
  const findItem = tableData.value.find(item => item.id === rowId);
  if (findItem) {
    setEditData(findItem);
  }
  setModalType('edit');
  openModal();
}

/**
 * 影响设置
 */
function handleSetting(rowId: number) {
  const findItem = tableData.value.find(item => item.id === rowId);
  if (findItem) {
    setEditData(findItem);
  }
  setModalSettingType('edit');
  openSettingModal();
}

/*
 * 执行条件设置
 */
function handleCondition(rowId: number) {
  const findItem = tableData.value.find(item => item.id === rowId);
  if (findItem) {
    setEditData(findItem);
  }
  setModalConditionType('edit');
  openEventModal();
}

function handleDeleteTable(rowId: number) {
  const data = fetchEventDelete(rowId);
  data.then(res => {
    if (res.data) {
      window.$message?.success('删除成功！');
    }
  });
  init();
}

const pagination: PaginationProps = reactive({
  page: 1,
  pageSize: 10,
  showSizePicker: true,
  pageSizes: [10, 15, 20, 25, 30],
  onChange: (page: number) => {
    pagination.page = page;
  },
  onUpdatePageSize: (pageSize: number) => {
    pagination.pageSize = pageSize;
    pagination.page = 1;
  }
});

function handleSearch() {
  if (!eventName.value) {
    window.$message?.warning('请输入字段名称');
  } else {
    window.$message?.warning(eventName.value);
  }
}

function init() {
  getTableData();
}

// 初始化
init();
</script>

<style scoped></style>
