<script lang="ts" setup>
/**
 * @Name: Table.vue
 * @Description: 公司SKU表格
 * @Author: Cheney
 */

import { InfoFilled, Plus, Position, Refresh } from '@element-plus/icons-vue';
import { usePagination } from '/@/utils/usePagination';
import { useTableData } from '/@/utils/useTableData';
import { useResponse } from '/@/utils/useResponse';
import { CompanySkuColumns } from '/@/views/sku-manage/Columns';
import PermissionButton from '/@/components/PermissionButton/index.vue';
import DataTableSlot from './DataTableSlot.vue';
import * as api from '../api';
import ShowSkuDrawer from '/@/views/sku-manage/company-sku/component/ShowSkuDrawer.vue';
import SkuBuilder from '/@/views/sku-manage/company-sku/component/SkuBuilder.vue';
import { ElMessage } from 'element-plus';
import { hasPermission } from '/@/utils/hasPermission';


interface Parameter {
  brandName: string;
  status: string;
  kind: string;
  sku: 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 showSkuBuilder = ref(false);
const createOpen = ref(false);
const showOpen = ref(false);
const rowData = ref<any | undefined>(undefined);

const skuData = ref({});

const checkedList = ref<Set<number>>(new Set());
const btnLoading = 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 = {
    brand: queryParameter?.brandName,
    kind: queryParameter?.kind,
    status: queryParameter?.status,
    sku__contains: queryParameter?.sku
  };

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

function handleRefresh() {
  fetchList();
}

async function handleEdit(row: any) {
  rowData.value = row;
  await fetchSkuDetail(row);
  if (Object.keys(skuData.value).length > 0) {
    showSkuBuilder.value = true;
  }
}

function handleCreate() {
  rowData.value = undefined;
  skuData.value = {};
  showSkuBuilder.value = true;
}

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

async function handleReleaseSku(row: any) {
  const res = await useResponse(api.releaseSku, { id: row.id, status: 3, kind: row.kind.id });
  if (res.code === 2000) {
    ElMessage.success({ message: '发布成功', plain: true, icon: 'Position' });
    handleRefresh();
  }
}

async function handleShowSku(row: any) {
  rowData.value = row;
  await fetchSkuDetail(row);
  if (Object.keys(skuData.value).length > 0) {
    showOpen.value = true;
  }
}

async function fetchSkuDetail(row: any) {
  const res = await useResponse(api.getSkuDetail, { id: row.id });
  if (res.code === 2000) {
    skuData.value = res.data;
  }
}

function selectChangeEvent({ checked, row }: any) {
  if (checked) {
    checkedList.value.add(row.id); // 获取单个数据
  } else {
    checkedList.value.delete(row.id);
  }
}

function selectAllChangeEvent({ checked }: any) {
  const $grid = gridRef.value;
  if ($grid) {
    const records = $grid.getData(); // 获取所有数据
    if (checked) {
      records.forEach((item: any) => {
        checkedList.value.add(item.id);
      });
    } else {
      checkedList.value.clear();
    }
  }
}

async function batchRelease() {
  const ids = Array.from(checkedList.value);
  const res = await useResponse(api.postRelease, { ids, status: 3 }, btnLoading);
  if (res && res.code === 2000) {
    ElMessage.success({ message: '已发布!', plain: true });
  }
  checkedList.value.clear();
  await fetchList();
}

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

const isBatchReleaseDisabled = computed(() => {
  const ids = Array.from(checkedList.value);
  return ids.some(id => {
    const item = gridOptions.data.find((row: any) => row.id === id);
    return item && item.status === 3;
  });
});

defineExpose({ fetchList });
</script>

<template>
  <vxe-grid ref="gridRef" v-bind="gridOptions" v-on="gridEvents"
            @checkbox-change="selectChangeEvent"
            @checkbox-all="selectAllChangeEvent">
    <template #toolbar_buttons>
      <div class="flex gap-2">
        <div>
          <PermissionButton v-if="hasPermission('SkuCreate')" :icon="Plus"  plain round type="primary" @click="handleCreate">新 增</PermissionButton>
        </div>
        <div v-if="hasPermission('SkuBulkPublish')">
          <el-popconfirm :icon="InfoFilled" icon-color="#626AEF" title="此操作将会把所有选中的SKU全部发布, 是否继续?"
                         width="360" @confirm="batchRelease">
            <template #reference>
              <PermissionButton :color="'#6466F1'" :disabled="!checkedList.size || isBatchReleaseDisabled" :icon="Position"
                                plain round>
                批量发布
              </PermissionButton>
            </template>
            <template #actions="{ confirm, cancel }">
              <el-button size="small" @click="cancel">No!</el-button>
              <el-button :color="'#6466F1'" size="small" @click="confirm">Yes?</el-button>
            </template>
          </el-popconfirm>
        </div>

      </div>
    </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 CompanySkuColumns" #[`${col.field}`]="{ row }">
      <DataTableSlot
          :key="row.id"
          :field="col.field"
          :row="row"
          @edit-row="handleEdit"
          @handle-delete="singleDelete"
          @release-sku="handleReleaseSku"
          @show-sku="handleShowSku"
      />
    </template>
  </vxe-grid>
  <SkuBuilder v-if="showSkuBuilder" v-model="showSkuBuilder" :row-data="rowData" :skuData="skuData"
              @refresh="handleRefresh" />
  <ShowSkuDrawer v-if="showOpen" v-model="showOpen" :row-data="rowData" :skuData="skuData" />
</template>

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

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