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

import { Delete, Download, InfoFilled, Plus, Refresh, Upload } from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';
import { usePagination } from '/@/utils/usePagination';
import { useTableData } from '/@/utils/useTableData';
import { useResponse } from '/@/utils/useResponse';
import { CompetitorMonitorColumns } from '/@/views/product-manage/Columns';
import DataTableSlot from './DataTableSlot.vue';
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 './EditDrawer.vue';
import CreateDialog from '/src/views/product-manage/competitor-monitor/component/CreateDialog.vue';
import * as api from '../api';
import { downloadFile } from '/@/utils/service';
import HistoricalDetail from '/@/views/product-manage/historical-detail/index.vue';
import { uesDownloadFile } from '/@/utils/useDownload';


interface Parameter {
  country: string,
  brand: string,
  group: string,
  status: string,
  shop: string
  asin: string,
  sku: string,
  platformId: string,
	minScore:number,
	maxScore:number,
	minScoreNumber:number,
	maxScoreNumber:number,
	minCommentNumber:number,
	maxCommentNumber:number,
	minAsinScore:number,
	maxAsinScore:number,
	minAsinCommentNumber:number,
	maxAsinCommentNumber:number,
}

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

const gridRef = ref();
const gridOptions: any = reactive({
  id: 'competitor-monitor-table',
  keepSource: true,
  size: 'mini',
  border: false,
  round: true,
  stripe: true,
  showHeader: 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: CompetitorMonitorColumns,
  data: ''
});

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

const editOpen = ref(false);
const createOpen = ref(false);
const rowData = ref<any>({});
const ordering = ref('');
const templateType = ref('monitor');

const isShowComment = ref(false);
const isShowHistory = ref(false);

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,
    goods__brand: queryParameter?.brand,
    goods__tag: queryParameter?.group,
    status: queryParameter?.status,
    shop: queryParameter?.shop,
    asin: queryParameter?.asin,
    goods__sku: queryParameter?.sku,
    platform_number: queryParameter?.platformId,

		minScoreNumber: queryParameter?.minScoreNumber,
		maxScoreNumber: queryParameter?.maxScoreNumber,
		minCommentNumber: queryParameter?.minCommentNumber,
		maxCommentNumber: queryParameter?.maxCommentNumber,
		minScore: queryParameter?.minScore,
		maxScore: queryParameter?.maxScore,
		minAsinScore: queryParameter?.minAsinScore,
		maxAsinScore: queryParameter?.maxAsinScore,
		minAsinCommentNumber: queryParameter?.minAsinCommentNumber,
		maxAsinCommentNumber: queryParameter?.maxAsinCommentNumber,

		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,
				goods__brand: queryParameter?.brand,
				goods__tag: queryParameter?.group,
				status: queryParameter?.status,
				shop: queryParameter?.shop,
				asin: queryParameter?.asin,
				goods__sku: queryParameter?.sku,
				platform_number: queryParameter?.platformId,

				minScoreNumber: queryParameter?.minScoreNumber,
				maxScoreNumber: queryParameter?.maxScoreNumber,
				minCommentNumber: queryParameter?.minCommentNumber,
				maxCommentNumber: queryParameter?.maxCommentNumber,
				minScore: queryParameter?.minScore,
				maxScore: queryParameter?.maxScore,
				minAsinScore: queryParameter?.minAsinScore,
				maxAsinScore: queryParameter?.maxAsinScore,
				minAsinCommentNumber: queryParameter?.minAsinCommentNumber,
				maxAsinCommentNumber: queryParameter?.maxAsinCommentNumber,

				ordering: ordering.value,
			},
			fileName: '竞品监控数据.xlsx',
			successMessage: () => ElMessage.success('数据导出成功！'),
			errorMessage: () => ElMessage.error('数据导出失败，请重试！'),
		});
	} finally {
		gridOptions.loading = false;
	}
}

async function batchDelete() {
  const ids = Array.from(checkedList.value);
  const res = await useResponse(api.batchDeleteRow, { keys: ids });
  checkedList.value.clear();
  if (res.code === 2000) {
    ElMessage.error({ message: '选中项已删除!', plain: true, icon: 'Delete' });
    handleRefresh();
  }
}

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 handleCreate() {
  createOpen.value = true;
}

function showComment(row: any) {
  isShowComment.value = true;
  rowData.value = row;
}

function showHistory(row: any) {
  isShowHistory.value = true;
  rowData.value = row;
}

function downloadTemplate() {
  const url = '/api/choice/competitor_monitor/import_data/';
  const fileName = '竞品监控模板.xlsx';

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

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

function handleSortChange({ field, order }) {
	const prefix = order === 'desc' ? '-' : '';
	ordering.value = ['reviews', 'ratings', 'score'].includes(field) ? `${prefix}${field}` : `${prefix}goods__${field}`;
	fetchList(field, order);
}

defineExpose({ fetchList });

</script>

<template>
  <vxe-grid ref="gridRef" v-bind="gridOptions" v-on="gridEvents"
            @checkbox-change="selectChangeEvent"
						@sort-change="handleSortChange"
            @checkbox-all="selectAllChangeEvent">
    <template #toolbar_buttons>
      <div class="flex gap-2">
        <div>
          <el-popconfirm
              :icon="InfoFilled"
              icon-color="#626AEF"
              title="你确定要删除此项吗?"
              width="220"
              @confirm="batchDelete"
          >
            <template #reference>
              <PermissionButton :disabled="!checkedList.size" :icon="Delete" plain round type="danger">
                批量删除
              </PermissionButton>
            </template>
            <template #actions="{ confirm, cancel }">
              <el-button size="small" @click="cancel">No!</el-button>
              <el-button size="small" type="danger" @click="confirm">
                Yes?
              </el-button>
            </template>
          </el-popconfirm>
        </div>
        <div>
          <PermissionButton :icon="Plus" plain round type="primary" @click="handleCreate">新 增</PermissionButton>
        </div>
        <div class="custom-el-input">
          <el-select v-model="templateType" placeholder="Select" 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="monitor" />
          </el-select>
        </div>
        <VerticalDivider class="px-1" style="margin-left: 7px;" />
        <ImportButton :icon="Upload" :uploadFunction="api.upload" bg text>导 入</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 CompetitorMonitorColumns" #[`${col.field}`]="{ row }">
      <DataTableSlot :key="row.id" :field="col.field" :row="row" @edit-row="handleEdit" @handle-delete="singleDelete"
                     @show-comment="showComment" @show-history="showHistory" />
    </template>
  </vxe-grid>
  <EditDrawer v-if="editOpen" v-model="editOpen" :row-data="rowData" @refresh="handleRefresh" />
  <CreateDialog v-if="createOpen" v-model="createOpen" @refresh="fetchList" />
  <HistoricalDetail v-if="isShowHistory" v-model="isShowHistory" :row-data="rowData.goods" title="竞品监控" />
</template>

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

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