<template>
	<div class="NCC-common-layout">
		<div class="NCC-common-layout-center">
			<!-- 查询条件 -->
			<el-row class="NCC-common-search-box" :gutter="16">
				<el-form @submit.native.prevent>
					<el-col :span="6">
						<el-form-item label="申请门店">
							<el-select v-model="query.applicationStoreId" placeholder="请选择申请门店" clearable filterable>
								<el-option v-for="store in storeOptions" :key="store.id" :label="store.dm" :value="store.id" />
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="6">
						<el-form-item label="审批状态">
							<el-select v-model="query.approvalStatus" placeholder="请选择审批状态" clearable>
								<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-col>
					<el-col :span="6">
						<el-form-item label="是否已领取">
							<el-select v-model="query.isReceived" placeholder="请选择" clearable>
								<el-option label="未领取" :value="0" />
								<el-option label="已领取" :value="1" />
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="6">
						<el-form-item>
							<el-button type="primary" icon="el-icon-search" @click="search()">查询</el-button>
							<el-button icon="el-icon-refresh-right" @click="reset()">重置</el-button>
						</el-form-item>
					</el-col>
				</el-form>
			</el-row>
			<!-- 申请列表 -->
			<div class="NCC-common-layout-main NCC-flex-main">
				<div class="NCC-common-head">
					<div>
						<el-button type="primary" icon="el-icon-plus" @click="addUsage()">添加使用记录</el-button>
					</div>
					<div class="NCC-common-head-right">
						<el-tooltip effect="dark" content="刷新" placement="top">
							<el-link icon="icon-ym icon-ym-Refresh NCC-common-head-icon" :underline="false"
								@click="initData()" />
						</el-tooltip>
						<screenfull isContainer />
					</div>
				</div>
				<NCC-table v-loading="loading" :data="list"
					:header-cell-style="{ background: '#f5f7fa', color: '#606266' }">
					<el-table-column label="申请编号" align="center" prop="id" width="180">
						<template slot-scope="scope">
							<div class="id-info">
								<i class="el-icon-postcard id-icon"></i>
								<span class="text-nowrap">{{ scope.row.id || '无' }}</span>
							</div>
						</template>
					</el-table-column>
					<el-table-column label="批次ID" align="center" prop="usageBatchId" width="180">
						<template slot-scope="scope">
							<span class="text-nowrap">{{ scope.row.usageBatchId || '无' }}</span>
						</template>
					</el-table-column>
					<el-table-column label="申请人" align="center" prop="applicationUserName" width="120" />
					<el-table-column label="申请门店" align="center" prop="applicationStoreName" width="150" />
					<el-table-column label="申请时间" align="center" prop="applicationTime" width="180">
						<template slot-scope="scope">
							<span>{{ formatDateTime(scope.row.applicationTime) }}</span>
						</template>
					</el-table-column>
					<el-table-column label="审批状态" align="center" prop="approvalStatus" width="120">
						<template slot-scope="scope">
							<el-tag :type="getStatusType(scope.row.approvalStatus)" size="small">
								{{ scope.row.approvalStatus || '无' }}
							</el-tag>
						</template>
					</el-table-column>
					<el-table-column label="是否已领取" align="center" prop="isReceived" width="120">
						<template slot-scope="scope">
							<el-tag :type="scope.row.isReceived === 1 ? 'success' : 'info'" size="small">
								{{ scope.row.isReceived === 1 ? '已领取' : '未领取' }}
							</el-tag>
						</template>
					</el-table-column>
					<el-table-column label="领取时间" align="center" prop="receiveTime" width="180">
						<template slot-scope="scope">
							<span>{{ scope.row.receiveTime ? formatDateTime(scope.row.receiveTime) : '无' }}</span>
						</template>
					</el-table-column>
					<el-table-column label="备注" align="center" prop="remarks" min-width="150">
						<template slot-scope="scope">
							<span>{{ scope.row.remarks || '无' }}</span>
						</template>
					</el-table-column>
					<el-table-column label="操作" width="280" align="left" fixed="right">
						<template slot-scope="scope">
							<div class="action-buttons">
								<el-button type="text" icon="el-icon-view" @click="viewBatchDetail(scope.row)"
									class="view-btn">
									查看批次详情
								</el-button>
								<el-button v-if="scope.row.approvalStatus === '审批中'" type="text" icon="el-icon-check"
									@click="approve(scope.row)" class="approve-btn">
									审批
								</el-button>
								<el-button v-if="scope.row.approvalStatus === '已通过' && scope.row.isReceived === 0"
									type="text" icon="el-icon-finished" @click="markReceived(scope.row)"
									class="receive-btn">
									标记已领取
								</el-button>
							</div>
						</template>
					</el-table-column>
				</NCC-table>
				<pagination :total="total" :page.sync="query.currentPage" :limit.sync="query.pageSize"
					@pagination="initData" />
			</div>
		</div>
		<!-- 审批弹窗 -->
		<ApprovalDialog v-if="approvalDialogVisible" ref="ApprovalDialog" @refresh="initData" />
		<!-- 批次详情弹窗 -->
		<BatchDetailDialog v-if="batchDetailDialogVisible" ref="BatchDetailDialog" />
		<!-- 添加使用记录弹窗 -->
		<UsageMultiForm v-if="usageMultiFormVisible" ref="UsageMultiForm" @refresh="initData" />
	</div>
</template>

<script>
import request from '@/utils/request'
import { getApplicationByBatchId, approveApplication, markReceived, getBatchInfo } from '@/api/extend/lqInventory'
import ApprovalDialog from './approval-dialog.vue'
import BatchDetailDialog from './batch-detail-dialog.vue'
import UsageMultiForm from './usage-multi-form.vue'

export default {
	components: { ApprovalDialog, BatchDetailDialog, UsageMultiForm },
	data() {
		return {
			loading: false,
			list: [],
			total: 0,
			query: {
				currentPage: 1,
				pageSize: 20,
				applicationStoreId: undefined,
				approvalStatus: undefined,
				isReceived: undefined
			},
			storeOptions: [],
			approvalDialogVisible: false,
			batchDetailDialogVisible: false,
			usageMultiFormVisible: false
		}
	},
	created() {
		this.initStoreOptions()
		this.initData()
	},
	methods: {
		initData() {
			this.loading = true
			let query = { ...this.query }
			// 移除空值
			Object.keys(query).forEach(key => {
				if (query[key] === undefined || query[key] === null || query[key] === '') {
					delete query[key]
				}
			})
			request({
				url: '/api/Extend/LqInventoryUsage/GetApplicationList',
				method: 'GET',
				data: query
			}).then(res => {
				if (res.code == 200 && res.data) {
					this.list = res.data.list || []
					this.total = res.data.pagination ? res.data.pagination.total : 0
				} else {
					this.list = []
					this.total = 0
				}
				this.loading = false
			}).catch(() => {
				this.loading = false
				this.list = []
				this.total = 0
			})
		},
		initStoreOptions() {
			request({
				url: '/api/Extend/LqMdxx',
				method: 'GET',
				data: {
					currentPage: 1,
					pageSize: 1000
				}
			}).then(res => {
				if (res.data && res.data.list) {
					this.storeOptions = res.data.list
				}
			}).catch(() => {
				this.storeOptions = []
			})
		},
		search() {
			this.query.currentPage = 1
			this.initData()
		},
		reset() {
			this.query = {
				currentPage: 1,
				pageSize: 20,
				applicationStoreId: undefined,
				approvalStatus: undefined,
				isReceived: undefined
			}
			this.initData()
		},
		viewBatchDetail(row) {
			this.batchDetailDialogVisible = true
			this.$nextTick(() => {
				this.$refs.BatchDetailDialog.init(row.usageBatchId)
			})
		},
		approve(row) {
			this.approvalDialogVisible = true
			this.$nextTick(() => {
				this.$refs.ApprovalDialog.init(row)
			})
		},
		markReceived(row) {
			this.$confirm('确定要标记该申请为已领取吗？', '提示', {
				type: 'warning'
			}).then(() => {
				markReceived(row.id).then(res => {
					this.$message({
						type: 'success',
						message: res.msg || '标记成功',
						onClose: () => {
							this.initData()
						}
					})
				}).catch(() => { })
			}).catch(() => { })
		},
		addUsage() {
			this.usageMultiFormVisible = true
			this.$nextTick(() => {
				this.$refs.UsageMultiForm.init()
			})
		},
		getStatusType(status) {
			const statusMap = {
				'待审批': 'info',
				'审批中': 'warning',
				'已通过': 'success',
				'未通过': 'danger',
				'已退回': 'info'
			}
			return statusMap[status] || 'info'
		},
		formatDateTime(timestamp) {
			if (!timestamp) return '无'
			const date = new Date(timestamp)
			const year = date.getFullYear()
			const month = String(date.getMonth() + 1).padStart(2, '0')
			const day = String(date.getDate()).padStart(2, '0')
			const hours = String(date.getHours()).padStart(2, '0')
			const minutes = String(date.getMinutes()).padStart(2, '0')
			const seconds = String(date.getSeconds()).padStart(2, '0')
			return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
		}
	}
}
</script>

<style lang="scss" scoped>
.text-nowrap {
	white-space: nowrap;
	overflow: hidden;
	text-overflow: ellipsis;
	max-width: 100%;
}

.id-info {
	display: flex;
	align-items: center;
	justify-content: center;
	gap: 6px;
}

.id-icon {
	color: #409EFF;
	font-size: 16px;
}

.action-buttons {
	display: flex;
	align-items: center;
	gap: 8px;
	flex-wrap: wrap;
}

.view-btn {
	color: #409EFF;

	&:hover {
		color: #66b1ff;
	}
}

.approve-btn {
	color: #67C23A;

	&:hover {
		color: #85ce61;
	}
}

.receive-btn {
	color: #E6A23C;

	&:hover {
		color: #ebb563;
	}
}

::v-deep .el-table__row:hover {
	background-color: #f5f7fa;
}

::v-deep .el-table__header-wrapper {
	.el-table__header {
		th {
			background-color: #f5f7fa;
			color: #606266;
			font-weight: 600;
		}
	}
}
</style>

