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

import { Download, Message, Money, Open, Refresh } from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';
import { usePagination } from '/@/utils/usePagination';
import { useTableData } from '/@/utils/useTableData';
import { ProductColumns } from '/@/views/product-manage/Columns';
import DataTableSlot from './DataTableSlot.vue';
import { downloadFile } from '/@/utils/service';
import PermissionButton from '/src/components/PermissionButton/index.vue';
import ImportButton from '/src/components/ImportButton/index.vue';
import VerticalDivider from '/src/components/VerticalDivider/index.vue';
import EditDrawer from '/src/views/product-manage/product-list/component/EditDrawer.vue';
import NoticeDialog from '/src/views/product-manage/product-list/component/NoticeDialog.vue';
import * as api from '../api';
import { useResponse } from '/@/utils/useResponse';
import DownloadError from '/@/views/product-manage/product-list/component/DownloadError.vue';
import { hasPermission } from '/@/utils/hasPermission';
import { uesDownloadFile } from '/@/utils/useDownload';


interface Parameter {
  country: string,
  brand: string,
  group: string,
  status: string,
  asin: string,
  sku: string,
  shop: string,
  isCompetitors: string
  platformNumber: string
}

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

const gridRef = ref();
const gridOptions: any = reactive({
  id: 'product-list-table',
  keepSource: true,
  size: 'mini',
  border: false,
  round: true,
  stripe: true,
  currentRowHighLight: true,
  height: '100%',
  customConfig: {
    storage: true
  },
	sortConfig: {
		remote: true,
	},
  toolbarConfig: {
    size: 'large',
    custom: true,
    slots: {
      buttons: 'toolbar_buttons',
      tools: 'toolbar_tools'
    }
  },
  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: ProductColumns,
  data: ''
});

const checkedList = ref<Set<number>>(new Set());
const btnLoading = ref(false);

const editOpen = ref(false);
const rowData = ref({});
const showError = ref(false);
const errorMsg = ref({});
const ordering = ref('');
const dialogVisible = ref(false);

const templateType = ref('product');

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

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

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

  gridOptions.data = [];

  const query = {
    country_code: queryParameter?.country,
    brand: queryParameter?.brand,
    tag: queryParameter?.group,
    status: queryParameter?.status,
    asin: queryParameter?.asin,
    sku: queryParameter?.sku,
    shop: queryParameter?.shop,
    is_competitors: queryParameter?.isCompetitors,
    platform_number: queryParameter?.platformNumber,
		ordering: ordering.value,
  };
  await useTableData(api.getTableData, query, gridOptions);
  gridOptions.showHeader = Boolean(gridOptions.data?.length);
}

function handleRefresh() {
  fetchList();
}

async function handleDownload() {
	gridOptions.loading = true;
	try {
		await uesDownloadFile({
			apiMethod: api.exportData,
			queryParams: {
				country_code: queryParameter?.country,
				brand: queryParameter?.brand,
				tag: queryParameter?.group,
				status: queryParameter?.status,
				asin: queryParameter?.asin,
				sku: queryParameter?.sku,
				shop: queryParameter?.shop,
				is_competitors: queryParameter?.isCompetitors,
				platform_number: queryParameter?.platformNumber,
				ordering: ordering.value,
			},
			fileName: '商品列表数据.xlsx',
			successMessage: () => ElMessage.success('数据导出成功！'),
			errorMessage: () => ElMessage.error('数据导出失败，请重试！'),
		});
	} finally {
		gridOptions.loading = false;
	}
}

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();
    }
  }
}

function handleEdit(row: any) {
  editOpen.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();
	}
}

function handleNotice(row: any) {
  dialogVisible.value = true;
  rowData.value = row;
}

async function switchMonitor(row: any) {
  const res = await useResponse(api.postMonitor, { ids: [ row.id ], status: row.is_monitor ? 1 : 0 });
  if (res && res.code === 2000) {
    // 根据 row.is_monitor 的值显示不同的提示信息
    const message = row.is_monitor ? '已开启' : '已关闭';
    if (row.is_monitor) {
      ElMessage.success({ message, plain: true, icon: 'Open' });
    } else {
      ElMessage.warning({ message, plain: true, icon: 'TurnOff' });
    }
  } else {
    // 如果操作失败，恢复原始状态
    row.is_monitor = !row.is_monitor;
    ElMessage.error({ message: '操作失败!', plain: true });
  }
}

async function batchOpen() {
  const ids = Array.from(checkedList.value);
  const res = await useResponse(api.postMonitor, { ids, status: 1 }, btnLoading);
  if (res && res.code === 2000) {
    ElMessage.success({ message: '选中项已开启', plain: true, icon: 'Open' });
  }
  checkedList.value.clear();
  await fetchList();
}

function downloadTemplate() {
  const urlMap: { [key: string]: string } = {
    notice: '/api/choice/goods/alarm/import_data/',
    product: '/api/choice/goods/import_data/',
    price: '/api/choice/goods/GuidancePrice/import_data/'
  };

  const fileNameMap: { [key: string]: string } = {
    notice: '商品通知模板.xlsx',
    product: '商品模板.xlsx',
    price: '指导价格模板.xlsx'
  };

  const url = urlMap[templateType.value];
  const fileName = fileNameMap[templateType.value];

  if (url) {
    downloadFile({
      url,
      method: 'GET',
      filename: fileName
    });
  } else {
    console.error('未知的模板类型:', templateType.value);
  }
}

function handleError(error: any) {
  errorMsg.value = error;
  showError.value = true;
}

const gridEvents = {
  custom({ type }: any) {
    if (type == 'confirm') {
      fetchList();
    }
  }
};

function handleSortChange({ field, order }) {
	const prefix = order === 'desc' ? '-' : '';
	ordering.value = `${prefix}${field}`;
	fetchList(field, order);
}

defineExpose({ fetchList });
</script>

<template>
  <vxe-grid ref="gridRef"
            v-bind="gridOptions"
            v-on="gridEvents"
						@sort-change="handleSortChange"
            @checkbox-change="selectChangeEvent"
            @checkbox-all="selectAllChangeEvent">
    <!-- 工具栏左侧 -->
    <template #toolbar_buttons>
      <div class="flex gap-2">
        <PermissionButton :disabled="!checkedList.size" :icon="Open" :loading="btnLoading" plain round type="primary"
                          @click="batchOpen">
          批量开启
        </PermissionButton>
        <div class="custom-el-input">
          <el-select v-model="templateType" style="width: 190px">
            <template #prefix>
              <div class="flex items-center">
                <el-button size="small" style="margin-left: -7px; font-size: 14px; border-radius: 29px;" text
                           type="success"
                           @click.stop="downloadTemplate">下载
                </el-button>
                <VerticalDivider style="margin-left: 7px" />
              </div>
            </template>
						<el-option label="商品模板" value="product" />
            <el-option label="商品通知模板" value="notice" />
<!--            <el-option v-if="hasPermission('GuidancePriceTemplate')" label="指导价格模板" value="price" />-->
          </el-select>
        </div>
        <VerticalDivider class="px-1" style="margin-left: 7px;" />

        <ImportButton :icon="Message" :uploadFunction="api.uploadChangeNotice" bg text>变更通知导入</ImportButton>
        <ImportButton :uploadFunction="api.uploadProducts" bg text>
          <i class="bi bi-box-seam mr-3"></i>
          商品导入
        </ImportButton>
        <!--<ImportButton :icon="Money" :show="'GuidancePriceImport'" :uploadFunction="api.uploadPrice" bg text-->
        <!--              @handelError="handleError">指导价格导入-->
        <!--</ImportButton>-->
      </div>
    </template>
    <!-- 工具栏右侧 -->
    <template #toolbar_tools>
      <el-button circle class="toolbar-btn" @click="handleRefresh">
        <el-icon>
          <Refresh />
        </el-icon>
      </el-button>
      <el-button circle class="toolbar-btn" @click="handleDownload" style="margin-right: 12px">
        <el-icon>
          <Download />
        </el-icon>
      </el-button>
    </template>
    <template #top>
      <div class="mb-2"></div>
    </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 ProductColumns" #[`${col.field}`]="{ row }">
      <DataTableSlot :key="row.id" :field="col.field" :row="row" @edit-row="handleEdit" @handle-notice="handleNotice"
                     @handle-monitor="switchMonitor" @handle-delete="singleDelete"/>
    </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" />
  <DownloadError v-if="showError" v-model="showError" :errorMsg="errorMsg" />
</template>

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

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