<template>
  <PageWrapper>
    <n-grid x-gap="12" cols="1 s:1 m:1 l:24 xl:24 2xl:24" responsive="screen">
      <n-grid-item span="8">
        <n-card shadow="hover" class="border-0" size="small">
          <n-space :size="4">
            <n-input
              type="text"
              v-model:value="params.name"
              placeholder="请输入字典名称"
              clearable
            />
            <n-button type="primary" @click="reloadTable">
              <template #icon>
                <n-icon>
                  <SearchOutlined />
                </n-icon> </template
              >查询
            </n-button>
          </n-space>
          <div style="margin-top: 15px">
            <n-space>
              <n-button type="primary" @click="dictRefresh" v-perm="['sys:dict:cache']">
                <template #icon> <RedoOutlined /> </template>刷新缓存</n-button
              >
              <n-button type="primary" @click="handleAdd" v-perm="['sys:dict:add']">
                <template #icon>
                  <n-icon>
                    <PlusOutlined />
                  </n-icon>
                </template>
                新建
              </n-button>
              <n-button
                type="error"
                @click="handleDelete()"
                v-perm="['sys:dict:delete']"
                :disabled="!selectionData.length"
              >
                <template #icon>
                  <n-icon>
                    <DeleteOutlined />
                  </n-icon> </template
                >删除
              </n-button>
            </n-space>
          </div>
          <BasicTable
            :columns="columns"
            :actionColumn="actionColumn"
            :request="loadDataTable"
            :row-key="(row) => row.id"
            ref="tableRef"
            :showTableSetting="false"
            @update:checked-row-keys="onSelectionChange"
            :pagination="{ showQuickJumper: false, showSizePicker: false }"
            :row-props="rowProps"
            :row-class-name="getRowClassName"
            :autoScrollX="true"
          >
          </BasicTable>
        </n-card>
      </n-grid-item>
      <n-grid-item span="16">
        <n-card shadow="hover" class="border-0 proCard" size="small">
          <dictItem :dictId="dictId" v-if="dictItemShow" />
        </n-card>
      </n-grid-item>
    </n-grid>
    <editDialog
      v-if="editVisible"
      :dictId="dictId"
      v-model:visible="editVisible"
      ref="createModalRef"
      @success="reloadTable('noRefresh')"
    />
  </PageWrapper>
</template>

<script lang="ts" setup>
  import { ref, nextTick, defineAsyncComponent, onMounted, reactive, h } from 'vue';
  import { getDictList, refreshCache, dictDelete } from '@/api/data/dictionary';
  import {
    PlusOutlined,
    FormOutlined,
    DeleteOutlined,
    SearchOutlined,
    RedoOutlined,
  } from '@vicons/antd';
  import { TableAction } from '@/components/Table';
  import { columns } from './columns';
  import editDialog from './edit.vue';
  import dictItem from './dictItem.vue';
  import { renderIcon } from '@/utils';
  import { useMessage, useDialog } from 'naive-ui';

  /**
   * 定义参数变量
   */
  const dictId = ref(0);
  const tableRef = ref();
  const createModalRef = ref();
  const dictItemShow = ref(false);
  const editVisible = ref(false);
  const selectionData = ref([]);
  const message = useMessage();
  const dialog = useDialog();

  const actionColumn = reactive({
    width: 200,
    title: '操作',
    align: 'center',
    key: 'action',
    fixed: 'right',
    render(record) {
      return h(TableAction as any, {
        style: 'button',
        actions: [
          {
            label: '编辑',
            icon: renderIcon(FormOutlined),
            type: 'warning',
            auth: ['sys:dict:update'],
            onClick: handleEdit.bind(null, record),
          },
          {
            label: '删除',
            icon: renderIcon(DeleteOutlined),
            type: 'error',
            auth: ['sys:dict:delete'],
            onClick: handleDelete.bind(null, record),
          },
        ],
        select: (key) => {
          message.info(`您点击了，${key} 按钮`);
        },
      });
    },
  });

  /**
   * 定义查询参数
   */
  const params = ref({
    name: '',
  });

  /**
   * 刷新配置项值列表
   * @param noRefresh 参数
   */
  function reloadTable(noRefresh = '') {
    tableRef.value.reload(noRefresh ? {} : { pageNo: 1 });
  }

  /**
   * 执行添加
   */
  const handleAdd = async () => {
    dictId.value = 0;
    editVisible.value = true;
    await nextTick();
    createModalRef.value.openModal();
  };

  /**
   * 执行编辑
   */
  const handleEdit = async (row) => {
    dictId.value = row.id;
    editVisible.value = true;
    await nextTick();
    createModalRef.value.openModal();
  };
  /**
   * 刷新缓存
   */
  async function dictRefresh() {
    await refreshCache();
    message.success('刷新成功');
  }

  /**
   * 选项发生变化
   * @param value 参数
   */
  function onSelectionChange(value) {
    selectionData.value = value;
  }

  /**
   * 加载数据列表
   */
  const loadDataTable = async (res) => {
    const result = await getDictList({ ...params.value, ...res });
    dictId.value = result?.records[0]?.id;
    dictItemShow.value = true;
    return result;
  };

  /**
   * 执行删除
   */
  async function handleDelete(row) {
    dialog.warning({
      title: '提示',
      content: '确定要删除？',
      positiveText: '确定',
      negativeText: '取消',
      onPositiveClick: async () => {
        row ? await dictDelete(row.id) : await dictBatchDelete(selectionData.value);
        message.success('删除成功');
        reloadTable();
      },
    });
  }
  const getRowClassName = (row) => {
    return dictId.value === row.id ? 'clickRowStyle' : '';
  };
  const rowProps = (row) => {
    return {
      style: 'cursor: pointer;',
      onClick: () => {
        dictId.value = row.id;
      },
    };
  };
  /**
   * 钩子函数
   */
  onMounted(() => {
    loadDataTable();
  });
</script>
<style lang="less" scoped>
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .dict-list-box {
    overflow: auto;

    .dict-item {
      height: 40px;
      line-height: 40px;
      padding: 0 6px;
      cursor: pointer;
      display: flex;
      justify-content: space-between;

      .t1 {
        font-size: 14px;
        display: block;
        font-weight: 700;

        .t2 {
          font-size: 12px;
          font-weight: normal;
        }
      }

      &.active {
        background-color: #e8f1ff;
        border-radius: 3px;

        .t1 {
          color: #1677ff;
        }

        .t2 {
          color: rgb(22, 119, 255, 0.8);
        }
      }

      .ant-badge__content.is-fixed {
        top: 20px;
        right: calc(-10px + var(--ant-badge-size) / 2);
      }
    }
  }
</style>
<style lang="less">
  .n-data-table-tbody {
    .n-data-table-tr.clickRowStyle,
    .n-data-table-tr.clickRowStyle {
      td {
        background-color: #e7eeff !important;
      }
      &:hover {
        td {
          background-color: #e7eeff !important;
        }
      }
    }
  }
</style>
