<script lang="ts" setup>
/**
 * @Name: DataTable.vue
 * @Description:审批查看(供货)数据表格
 * @Author: xinyan
 */

import { Download, Plus, Refresh, Upload } from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';
import { usePagination } from '/@/utils/usePagination';
import { useTableData } from '/@/utils/useTableData';
import DataTableSlot from './DataTableSlot.vue';
import { uesDownloadFile } from '/@/utils/useDownload';
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 * as api from '../api';
import { useResponse } from '/@/utils/useResponse';
import {
	SupplyCheckColumns_Regular,
	SupplyCheckColumns_Special,
} from '/@/views/price-approval/Columns';
import EditDrawer from '/@/views/price-approval/approval-review-supply/components/EditDrawer.vue';
import { hasPermission } from '/@/utils/hasPermission';
import { getDept } from '/@/views/price-approval/api';

const router = useRouter();

interface Parameter {
	sku: string;
	platform: string;
	country_code: string;
	sales_mode: string;
}

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

const gridRef = ref();
const gridOptions: any = reactive({
  size: 'mini',
  border: false,
  round: true,
  stripe: true,
  currentRowHighLight: true,
  height: '100%',
  toolbarConfig: {
    size: 'large',
    slots: {
      buttons: 'toolbar_buttons',
      tools: 'toolbar_tools'
    }
  },
  rowConfig: {
		height: 50,
    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 checkedList = ref<Set<number>>(new Set());
const btnLoading = ref(false);

const editOpen = ref(false);
const rowData = ref({});

const templateType = ref('cost');

const is_superuser = ref(false);
const roleKey = ref('');

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

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

async function fetchDept() {
	const resp = (await useResponse(getDept)).data;
	is_superuser.value = resp.is_superuser;
	roleKey.value = resp.role_info.length > 0?resp.role_info.map(role => role.key):'';
}

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

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

  const query = {
		sku: queryParameter?.sku,
		platform: queryParameter?.platform,
		country_code: queryParameter?.country_code,
		sales_mode: queryParameter?.sales_mode,
	};
  await useTableData(api.getTableData, query, gridOptions);
	if (gridOptions && gridOptions.data?.length) {
		if (is_superuser.value) {
			await gridRef.value.loadColumn(SupplyCheckColumns_Special);
		} else if (roleKey.value.includes('price.manage')) {
			await gridRef.value.loadColumn(SupplyCheckColumns_Special);
		}else {
			await gridRef.value.loadColumn(SupplyCheckColumns_Regular);
		}
	}
  gridOptions.showHeader = Boolean(gridOptions.data?.length);
}

function handleRefresh() {
  fetchList();
}

async function handleDownload() {
	gridOptions.loading = true;
	try {
		await uesDownloadFile({
			apiMethod: api.exportData,
			queryParams: {
				sku: queryParameter?.sku,
				platform: queryParameter?.platform,
				country_code:queryParameter?.country_code,
				sales_mode: queryParameter?.sales_mode,
			},
			fileName: '审批查看（供货）数据.xlsx',
			successMessage: () => ElMessage.success('数据导出成功！'),
			errorMessage: () => ElMessage.error('数据导出失败，请重试！'),
		});
	} finally {
		gridOptions.loading = false;
	}
}


function handleCreate() {
  router.push({ path: '/addPage', query: { type: 'supply' } });
}

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 downloadTemplate() {
  const url = '/api/pricing/price_product_supply/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 cellStyle() {
  return {
    fontWeight: 600,
  };
}

defineExpose({ fetchList });
</script>

<template>
  <vxe-grid ref="gridRef" :cell-style="cellStyle" v-bind="gridOptions" v-on="gridEvents">
    <!-- 工具栏左侧 -->
    <template #toolbar_buttons>
      <div class="flex gap-2">
        <div>
          <PermissionButton v-if="hasPermission('PRICE_SUPPLY_CREATE')" :icon="Plus" plain round type="primary" @click="handleCreate">新 增</PermissionButton>
        </div>
        <div class="custom-el-input">
          <el-select v-model="templateType" style="width: 200px">
            <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="cost" />
          </el-select>
        </div>
        <VerticalDivider class="px-1" style="margin-left: 7px" />
        <ImportButton v-if="hasPermission('SUPPLY_IMPORT_DATA')" :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">
        <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 SupplyCheckColumns_Special" #[`${col.field}`]="{ row }">
      <DataTableSlot :field="col.field" :row="row" @edit-row="handleEdit" @handle-delete="singleDelete" />
    </template>
  </vxe-grid>
  <EditDrawer v-if="editOpen" v-model="editOpen" :row-data="rowData" @refresh="handleRefresh" />
</template>

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

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