<template>
  <page-container>
    <div class="ant-pro-table">
      <div class="ant-pro-table-search">
        <h-form layout="horizontal">
          <h-row :gutter="16" type="flex" justify="start">
            <h-col :xs="24" :sm="24" :md="12" :lg="7">
              <h-form-item label="规则名称">
                <h-input v-model:value="queryParam.ruleName" placeholder="please enter" />
              </h-form-item>
            </h-col>
            <h-col :xs="24" :sm="24" :md="12" :lg="7">
              <h-form-item label="描述">
                <h-input v-model:value="queryParam.desc" placeholder="please enter" />
              </h-form-item>
            </h-col>
            <h-col :xs="24" :sm="24" :md="12" :lg="7">
              <h-form-item label="服务调用次数">
                <h-input v-model:value="queryParam.callNo" placeholder="please enter" />
              </h-form-item>
            </h-col>
            <h-col :xs="24" :sm="24" :md="12" :lg="3">
              <h-form-item>
                <h-button @click="handleSearch" type="primary">搜索</h-button>
              </h-form-item>
            </h-col>
          </h-row>
        </h-form>
      </div>
      <h-card :body-style="{ padding: 0 }" ref="elRef">
        <div class="ant-pro-table-list-toolbar">
          <div class="ant-pro-table-list-toolbar-container">
            <div class="ant-pro-table-list-toolbar-left">
              <div class="ant-pro-table-list-toolbar-title">查询表格</div>
            </div>
            <div class="ant-pro-table-list-toolbar-right">
              <h-space align="center">
                <h-button type="primary" @click="modalVisible = true">
                  <plus-outlined />
                  新建
                </h-button>
                <div class="ant-pro-table-list-toolbar-setting-item">
                  <h-tooltip title="表格斑马纹">
                    <h-switch
                      checked-children="开"
                      un-checked-children="关"
                      v-model:checked="fetchDataContext.stripe"
                    />
                  </h-tooltip>
                </div>
              </h-space>
              <div class="ant-pro-table-list-toolbar-divider">
                <h-divider type="vertical" />
              </div>
              <div class="ant-pro-table-list-toolbar-setting-item">
                <h-tooltip title="刷新">
                  <reload-outlined @click="reload" />
                </h-tooltip>
              </div>
              <div class="ant-pro-table-list-toolbar-setting-item">
                <h-tooltip title="密度">
                  <h-dropdown :trigger="['click']" placement="bottomRight">
                    <column-height-outlined />
                    <template #overlay>
                      <h-menu
                        style="width: 80px"
                        :selected-keys="[state.tableSize]"
                        @click="
                          ({ key }) => {
                            fetchDataContext.tableSize = String(key);
                          }
                        "
                      >
                        <h-menu-item key="default">
                          <a href="javascript:;">默认</a>
                        </h-menu-item>
                        <h-menu-item key="middle">
                          <a href="javascript:;">中等</a>
                        </h-menu-item>
                        <h-menu-item key="small">
                          <a href="javascript:;">紧凑</a>
                        </h-menu-item>
                      </h-menu>
                    </template>
                  </h-dropdown>
                </h-tooltip>
              </div>
              <div class="ant-pro-table-list-toolbar-setting-item">
                <h-popover
                  placement="bottomRight"
                  arrowPointAtCenter
                  trigger="click"
                  overlayClassName="ant-pro-table-column-setting-overlay"
                >
                  <template #title>
                    <div class="ant-pro-table-column-setting-title">
                      <h-checkbox
                        v-model:checked="columnState.checkAll"
                        :indeterminate="columnState.indeterminate"
                        @change="handleColumnAllClick"
                      >
                        列展示 / 排序
                      </h-checkbox>
                      <a @click="reset">重置</a>
                    </div>
                  </template>
                  <template #content>
                    <span class="ant-pro-table-column-setting-list">
                      <drag-container
                        lockAxis="y"
                        dragClass="ant-pro-table-drag-ghost"
                        dropClass="ant-pro-table-drop-ghost"
                        @drop="({ removedIndex, addedIndex }) => move(removedIndex, addedIndex)"
                      >
                        <draggable :key="column.key" v-for="column in dynamicColumnItems">
                          <div class="ant-pro-table-column-setting-list-item">
                            <drag-icon />
                            <h-checkbox
                              :checked="column.checked"
                              @change="handleColumnChange($event, column)"
                            >
                              {{ column.label }}
                            </h-checkbox>
                          </div>
                        </draggable>
                      </drag-container>
                    </span>
                  </template>
                  <h-tooltip title="列设置">
                    <setting-outlined />
                  </h-tooltip>
                </h-popover>
              </div>
              <div class="ant-pro-table-list-toolbar-setting-item">
                <h-tooltip :title="screenState ? '退出全屏' : '全屏'">
                  <fullscreen-outlined v-if="!screenState" @click="setFull" />
                  <fullscreen-exit-outlined v-else @click="exitFull" />
                </h-tooltip>
              </div>
            </div>
          </div>
        </div>
        <h-table
          :row-class-name="stripe"
          :size="state.tableSize"
          :loading="state.loading"
          :columns="dynamicColumns"
          :data-source="state.dataSource"
          :pagination="{
            current: state.current,
            pageSize: state.pageSize,
            total: state.total,
          }"
          ref="tableRef"
          :getPopupContainer="_trigger => tableRef.$el"
          @change="handleTableChange"
        >
          <template #rowIndex="{ index }">
            {{ index }}
          </template>
          <template #bodyCell="{ text, column, record }">
            <template v-if="column.dataIndex === 'status'">
              <h-badge :status="statusMap[text].status" :text="statusMap[text].text" />
            </template>
            <template v-else-if="column.dataIndex === 'action'">
              <a>编辑</a>
              <h-divider type="vertical" />
              <h-popconfirm title="确定要删除吗 ?" @confirm="onDelete(record)">
                <a>删除</a>
              </h-popconfirm>
              <h-divider type="vertical" />
              <h-dropdown>
                <a>
                  更多
                  <down-outlined />
                </a>
                <template #overlay>
                  <h-menu>
                    <h-menu-item>
                      <a href="javascript:;">操作 1</a>
                    </h-menu-item>
                    <h-menu-item>
                      <a href="javascript:;">操作 2</a>
                    </h-menu-item>
                    <h-menu-item>
                      <a href="javascript:;">操作 3</a>
                    </h-menu-item>
                  </h-menu>
                </template>
              </h-dropdown>
            </template>
          </template>
        </h-table>
      </h-card>
    </div>
    <h-modal
      title="Basic Modal"
      :getContainer="() => elRef && elRef.$el"
      v-model:visible="modalVisible"
      @ok="handleModalOk"
    >
      <p>Some contents...</p>
      <p>Some contents...</p>
      <p>Some contents...</p>
    </h-modal>
  </page-container>
</template>

<script lang="ts">
import { computed, defineComponent, reactive, ref, watch } from 'vue';
import {
  PlusOutlined,
  ReloadOutlined,
  ColumnHeightOutlined,
  SettingOutlined,
  FullscreenOutlined,
  FullscreenExitOutlined,
  DownOutlined,
} from '@ant-design/icons-vue';
import { Container as DragContainer, Draggable } from '@/components/draggable';
import { queryRule } from '@/api/list/table-list';
import type { Pagination, TableFilters, TableColumn } from '@/typing';
import { useFetchData } from '@/utils/hooks/useFetchData';
import { useFullscreen } from '@/utils/hooks/useFullscreen';
import { useTableDynamicColumns } from '@/utils/hooks/useTableColumn';
import DragIcon from '@/components/table/drag-icon.vue';

export default defineComponent({
  name: 'TableList',
  setup() {
    const tableRef = ref();

    const statusMap = {
      0: { text: '关闭', status: 'default' },
      1: { text: '运行中', status: 'processing' },
      2: { text: '已上线', status: 'success' },
      3: { text: '异常', status: 'error' },
    };
    const status = ['关闭', '运行中', '已上线', '异常'];
    const filteredInfoMap = ref();
    const queryParam = reactive({
      ruleName: undefined,
      desc: undefined,
      callNo: undefined,
      status: undefined,
    });
    const fetchDataContext = reactive({
      current: 1,
      pageSize: 10,
      tableSize: 'middle', // 'default' | 'middle' | 'small'
      stripe: false,
      requestParams: { ...queryParam },
    });
    watch(
      filteredInfoMap,
      () => {
        queryParam.status = filteredInfoMap.value?.status;
        fetchDataContext.requestParams = { ...queryParam };
      },
      { immediate: true },
    );
    const baseColumns = computed<TableColumn[]>(() => {
      const filtered = filteredInfoMap.value || {};
      return [
        {
          title: '规则名称',
          dataIndex: 'name',
        },
        {
          title: '描述',
          dataIndex: 'desc',
        },
        {
          title: '服务调用次数',
          dataIndex: 'callNo',
          sorter: true,
          align: 'right',
          customRender: ({ text }) => `${text} 万`,
        },
        {
          title: '状态',
          dataIndex: 'status',
          filteredValue: filtered.status || null,
          filters: [
            {
              text: status[0],
              value: '0',
            },
            {
              text: status[1],
              value: '1',
            },
            {
              text: status[2],
              value: '2',
            },
            {
              text: status[3],
              value: '3',
            },
          ],
        },
        {
          title: '上次调度时间',
          dataIndex: 'updatedAt',
          sorter: true,
        },
        {
          title: '操作',
          dataIndex: 'action',
        },
      ];
    });
    const needRowIndex = ref(true);
    const {
      state: columnState,
      dynamicColumns,
      dynamicColumnItems,
      handleColumnAllClick,
      handleColumnChange,
      reset,
      move,
    } = useTableDynamicColumns(baseColumns, { needRowIndex });

    const [elRef, screenState, { setFull, exitFull }] = useFullscreen();

    const { stripe, context: state, reload } = useFetchData(queryRule, fetchDataContext);
    const handleTableChange = ({ current, pageSize }: Pagination, filters?: TableFilters) => {
      filteredInfoMap.value = filters;
      fetchDataContext.current = current;
      fetchDataContext.pageSize = pageSize;
    };

    const handleSearch = () => {
      fetchDataContext.requestParams = { ...queryParam };
    };

    // modal
    const modalVisible = ref(false);
    const handleModalOk = () => {};

    const onDelete = (record: any) => {
      console.log('detele', record);
    };
    return {
      reload,
      onDelete,
      statusMap,
      state,
      stripe,
      columnState,
      dynamicColumns,
      dynamicColumnItems,

      queryParam,
      handleSearch,
      // fullscreen
      elRef,
      screenState,
      setFull,
      exitFull,

      handleTableChange,

      handleColumnChange,
      handleColumnAllClick,
      reset,
      move,

      // modal controls
      modalVisible,
      handleModalOk,

      tableRef,
      fetchDataContext,
    };
  },
  components: {
    DragIcon,
    PlusOutlined,
    ReloadOutlined,
    ColumnHeightOutlined,
    SettingOutlined,
    FullscreenOutlined,
    FullscreenExitOutlined,
    DownOutlined,
    Draggable,
    DragContainer,
  },
});
</script>
