<script lang="ts" setup>
/**
 * @Name: Table.vue
 * @Description: 产品属性表格
 * @Author: Cheney
 */

import { ElMessage } from 'element-plus';
import { Plus, Refresh } from '@element-plus/icons-vue';
import { usePagination } from '/@/utils/usePagination';
import { useTableData } from '/@/utils/useTableData';
import { useResponse } from '/@/utils/useResponse';
import { AttributeColumns } from '/@/views/sku-manage/Columns';
import PermissionButton from '/@/components/PermissionButton/index.vue';
import DataTableSlot from './DataTableSlot.vue';
import EditDrawer from './EditDrawer.vue';
import NoticeDialog from '/src/views/product-manage/product-list/component/NoticeDialog.vue';
import * as api from '../api';
import CreateDialog from '/src/views/sku-manage/product-attribute/component/CreateDialog.vue';
import ManageEnumDrawer from '/src/views/sku-manage/product-attribute/component/manage-enum/index.vue';
import ShowDetailDrawer from '/@/views/sku-manage/product-attribute/component/ShowDetailDrawer.vue';
import { hasPermission } from '/@/utils/hasPermission';


interface Parameter {
  name: string,
  key: string,
}

const queryParameter: Parameter | undefined = inject('query-parameter');
const { tableOptions, handlePageChange } = usePagination(fetchList);

const gridRef = ref();
const gridOptions: any = reactive({
  id: 'product-attribute-table',
  keepSource: true,
  size: 'small',
  border: false,
  round: true,
  stripe: true,
  currentRowHighLight: true,
  height: '100%',
  customConfig: {
    // mode: 'drawer',
    // immediate: true,
    storage: true
  },
  toolbarConfig: {
    size: 'large',
    // custom: true,
    slots: {
      tools: 'toolbar_tools',
      buttons: 'toolbar_buttons'
    }
  },
  rowConfig: {
    isHover: true
  },
  columnConfig: {
    // resizable: true
  },
  pagerConfig: {
    total: tableOptions.value.total,
    page: tableOptions.value.page,
    limit: tableOptions.value.limit
  },
  loading: false,
  loadingConfig: {
    icon: 'vxe-icon-indicator roll',
    text: '正在拼命加载中...'
  },
  columns: '',
  data: ''
});

const editOpen = ref(false);
const createOpen = ref(false);
const manageOpen = ref(false);
const viewOpen = ref(false);
const rowData = ref({});

const dialogVisible = ref(false);

onBeforeMount(() => {
  gridOptions.pagerConfig.limit = 20;
});

onMounted(() => {
  fetchList();
});

async function fetchList(isQuery = false) {
  if (isQuery) {
    gridOptions.pagerConfig.page = 1;
  }

  gridOptions.data = [];
  gridOptions.columns = [];

  const query = {
    name: queryParameter?.name,
    key: queryParameter?.key
  };

  await useTableData(api.getTableData, query, gridOptions);
  if (gridOptions && gridOptions.data?.length) await gridRef.value.loadColumn(AttributeColumns);
  gridOptions.showHeader = Boolean(gridOptions.data?.length);
}

function handleRefresh() {
  fetchList();
}

function handleEdit(row: any) {
  editOpen.value = true;
  rowData.value = row;
}

function handleManage(row: any) {
  manageOpen.value = true;
  rowData.value = row;
}

function handleCreate() {
  createOpen.value = true;
}

function handleView(row: any) {
  viewOpen.value = true;
  rowData.value = row;
}

async function singleDelete(row: any) {
  const res = await useResponse(api.deleteRow, row);
  if (res.code === 2000) {
    ElMessage.error({ message: '已删除!', plain: true, icon: 'Delete' });
    handleRefresh();
  }
}

const gridEvents = {
  custom({ type }: any) {
    // console.log(`点击 ${type}`)
    if (type == 'confirm') {
      fetchList();
    }
  }
};

defineExpose({ fetchList });
</script>

<template>
  <vxe-grid ref="gridRef" v-bind="gridOptions" v-on="gridEvents">
    <template #toolbar_buttons>
      <PermissionButton :icon="Plus" v-if="hasPermission('SkuAttrCreate')" plain round type="primary" @click="handleCreate">新 增</PermissionButton>
    </template>
    <!-- 工具栏右侧 -->
    <template #toolbar_tools>
      <el-button circle class="toolbar-btn" @click="handleRefresh">
        <el-icon>
          <Refresh />
        </el-icon>
      </el-button>
    </template>
    <template #pager>
      <vxe-pager
          v-model:currentPage="gridOptions.pagerConfig.page"
          v-model:pageSize="gridOptions.pagerConfig.limit"
          :total="gridOptions.pagerConfig.total"
          class="mt-1.5"
          @page-change="handlePageChange"
      />
    </template>
    <template #empty>
      <el-empty description="暂无数据" />
    </template>
    <!-- 自定义列插槽 -->
    <template v-for="col in AttributeColumns" #[`${col.field}`]="{ row }">
      <DataTableSlot :key="row.id" :field="col.field" :row="row" @edit-row="handleEdit" @handle-delete="singleDelete"
                     @handle-manage="handleManage" @show-detail="handleView" />
    </template>
  </vxe-grid>
  <EditDrawer v-if="editOpen" v-model="editOpen" :row-data="rowData" @refresh="handleRefresh" />
  <NoticeDialog v-if="dialogVisible" v-model="dialogVisible" :row-data="rowData" />
  <CreateDialog v-if="createOpen" v-model="createOpen" @refresh="fetchList" />
  <ManageEnumDrawer v-if="manageOpen" v-model="manageOpen" :row-data="rowData" />
  <ShowDetailDrawer v-if="viewOpen" v-model="viewOpen" :row-data="rowData" />
</template>

<style scoped>
.toolbar-btn {
  width: 34px;
  height: 34px;
  font-size: 18px
}

:deep(.custom-el-input .el-select__wrapper) {
  border-radius: 20px;
}
</style>
