<template>
	<el-dialog title="导出仓库使用记录" :close-on-click-modal="false" :visible.sync="visible"
		class="NCC-dialog NCC-dialog_center" lock-scroll width="700px">
		<el-form label-position="right" label-width="120px">
			<el-form-item label="门店">
				<el-select v-model="exportQuery.storeId" placeholder="请选择门店（可选）" clearable filterable style="width: 100%">
					<el-option v-for="store in storeOptions" :key="store.id" :label="store.dm" :value="store.id" />
				</el-select>
			</el-form-item>
			<el-form-item label="产品">
				<el-select v-model="exportQuery.productId" placeholder="请选择产品（可选）" clearable filterable style="width: 100%">
					<el-option v-for="product in productOptions" :key="product.id" :label="product.productName" :value="product.id" />
				</el-select>
			</el-form-item>
			<el-form-item label="批次号">
				<el-input v-model="exportQuery.usageBatchId" placeholder="请输入批次号（可选）" clearable />
			</el-form-item>
			<el-form-item label="使用时间">
				<el-date-picker v-model="usageTimeRange" type="datetimerange" range-separator="至"
					start-placeholder="开始时间" end-placeholder="结束时间" value-format="yyyy-MM-dd HH:mm:ss"
					format="yyyy-MM-dd HH:mm:ss" style="width: 100%" />
			</el-form-item>
			<el-form-item label="审批状态">
				<el-select v-model="exportQuery.approvalStatus" placeholder="请选择审批状态（可选）" clearable style="width: 100%">
					<el-option label="全部" value="" />
					<el-option label="待审批" value="待审批" />
					<el-option label="审批中" value="审批中" />
					<el-option label="已通过" value="已通过" />
					<el-option label="未通过" value="未通过" />
					<el-option label="已退回" value="已退回" />
				</el-select>
			</el-form-item>
			<el-form-item label="是否已领取">
				<el-select v-model="exportQuery.isReceived" placeholder="请选择（可选）" clearable style="width: 100%">
					<el-option label="全部" :value="null" />
					<el-option label="已领取" :value="true" />
					<el-option label="未领取" :value="false" />
				</el-select>
			</el-form-item>
			<el-form-item label="是否有效">
				<el-select v-model="exportQuery.isEffective" placeholder="请选择（可选）" clearable style="width: 100%">
					<el-option label="全部" :value="null" />
					<el-option label="有效" :value="true" />
					<el-option label="无效" :value="false" />
				</el-select>
			</el-form-item>
			<el-form-item label="导出说明">
				<div class="export-info">
					<p>• 导出包含11个字段：批次号、产品名称、门店名称、使用数量、单价、总金额、使用时间、归属仓库、审批状态、是否已领取、是否有效</p>
					<p>• 所有字段都会显示中文名称，无需手动选择</p>
					<p>• 支持按门店、产品、批次号、使用时间、审批状态、是否已领取、是否有效进行筛选</p>
				</div>
			</el-form-item>
		</el-form>
		<span slot="footer" class="dialog-footer">
			<el-button @click="visible = false">取 消</el-button>
			<el-button type="primary" @click="handleExport" :loading="btnLoading">导 出</el-button>
		</span>
	</el-dialog>
</template>

<script>
import request from '@/utils/request'

export default {
	name: 'ExportUsageDialog',
	props: {
		storeOptions: {
			type: Array,
			default: () => []
		}
	},
	data() {
		return {
			visible: false,
			btnLoading: false,
			exportQuery: {
				storeId: undefined,
				productId: undefined,
				usageBatchId: undefined,
				usageStartTime: undefined,
				usageEndTime: undefined,
				approvalStatus: undefined,
				isReceived: undefined,
				isEffective: undefined
			},
			usageTimeRange: null,
			productOptions: [] // 产品选项
		}
	},
	methods: {
		init() {
			this.visible = true
			// 重置表单
			this.exportQuery = {
				storeId: undefined,
				productId: undefined,
				usageBatchId: undefined,
				usageStartTime: undefined,
				usageEndTime: undefined,
				approvalStatus: undefined,
				isReceived: undefined,
				isEffective: undefined
			}
			this.usageTimeRange = null
			// 加载产品选项
			this.initProductOptions()
		},
		// 加载产品选项
		initProductOptions() {
			request({
				url: '/api/Extend/LqProduct/GetList',
				method: 'GET',
				data: {
					currentPage: 1,
					pageSize: 1000,
					onShelfStatus: 1  // 只获取上架的产品
				}
			}).then(res => {
				if (res.code == 200 && res.data && res.data.list) {
					this.productOptions = res.data.list.filter(product => product.onShelfStatus === 1)
				} else {
					this.productOptions = []
				}
			}).catch(() => {
				this.productOptions = []
			})
		},
		handleExport() {
			this.btnLoading = true
			// 构建导出查询参数
			let exportParams = { ...this.exportQuery }
			
			// 处理时间范围
			if (this.usageTimeRange && this.usageTimeRange.length === 2) {
				exportParams.usageStartTime = this.usageTimeRange[0]
				exportParams.usageEndTime = this.usageTimeRange[1]
			}
			
			// 处理布尔值参数（转换为字符串true/false）
			if (exportParams.isReceived !== undefined && exportParams.isReceived !== null) {
				exportParams.isReceived = exportParams.isReceived === true || exportParams.isReceived === 'true'
			}
			if (exportParams.isEffective !== undefined && exportParams.isEffective !== null) {
				exportParams.isEffective = exportParams.isEffective === true || exportParams.isEffective === 'true'
			}
			
			// 移除空值
			Object.keys(exportParams).forEach(key => {
				if (exportParams[key] === undefined || exportParams[key] === null || exportParams[key] === '') {
					delete exportParams[key]
				}
			})
			
			// 构建查询字符串
			const queryString = Object.keys(exportParams)
				.map(key => {
					const value = exportParams[key]
					// 布尔值转换为字符串
					if (typeof value === 'boolean') {
						return `${key}=${value}`
					}
					return `${key}=${encodeURIComponent(value)}`
				})
				.join('&')
			
			// 调用导出接口
			const url = `/api/Extend/LqInventoryUsage/ExportExcel${queryString ? '?' + queryString : ''}`
			
			request({
				url: url,
				method: 'GET'
			}).then(res => {
				this.btnLoading = false
				if (res.code === 200 && res.data) {
					// 如果返回的是下载链接
					if (res.data.url) {
						// 构建完整URL
						const baseUrl = window.location.origin
						const downloadUrl = baseUrl + res.data.url
						window.open(downloadUrl, '_blank')
						this.$message.success('导出成功')
						this.visible = false
					} else {
						this.$message.error('导出失败：未返回下载链接')
					}
				} else {
					this.$message.error(res.msg || '导出失败')
				}
			}).catch(err => {
				this.btnLoading = false
				console.error('导出失败:', err)
				this.$message.error('导出失败，请稍后重试')
			})
		}
	}
}
</script>

<style lang="scss" scoped>
.export-info {
	padding: 10px;
	background-color: #f5f7fa;
	border-radius: 4px;
	
	p {
		margin: 5px 0;
		font-size: 13px;
		color: #606266;
		line-height: 1.6;
	}
}
</style>

