<template>
	<div class="NCC-common-layout">
		<div class="NCC-common-layout-center" style="width: 100%;">
			<el-row class="NCC-common-search-box" :gutter="16">
				<el-form @submit.native.prevent="search">
					<el-col :span="6">
						<el-form-item label="关联产品">
							<el-select v-model="query.fl" placeholder="关联产品" clearable filterable @clear="search" @change="search">
								<el-option
									v-for="item in cpglOptions"
									:key="item.id"
									:label="item.cpmc + ' (' + (item.cpid || item.id) + ')'"
									:value="item.id"
								/>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="6">
						<el-form-item label="备件名称">
							<el-input v-model="query.mc" placeholder="备件名称" clearable @clear="search" @keyup.enter.native="search" />	
						</el-form-item>
					</el-col>
					<el-col :span="6">
						<el-form-item label="物料编码">
							<el-input v-model="query.bh" placeholder="物料编码" clearable @clear="search" @keyup.enter.native="search" />	
						</el-form-item>
					</el-col>
					<el-col v-if="false" :span="6">
						<el-form-item label="规格型号">
							<el-input v-model="query.gg" placeholder="规格型号" clearable @clear="search" @keyup.enter.native="search" />	
						</el-form-item>
					</el-col>
					<template v-if="showAll">
					<el-col :span="6">
						<el-form-item label="备件位置">
							<el-input v-model="query.bjwz" placeholder="备件位置" clearable @clear="search" />	
						</el-form-item>
					</el-col>
					<el-col :span="6">
						<el-form-item label="更换指引">
							<el-input v-model="query.ghzy" placeholder="更换指引" />	
						</el-form-item>
					</el-col>
					<el-col v-if="false" :span="6">
						<el-form-item label="发布时间">
							<el-date-picker v-model="query.fbsj" type="daterange" value-format="timestamp" format="yyyy-MM-dd" start-placeholder="开始日期" end-placeholder="结束日期" @change="search">
							</el-date-picker>
						</el-form-item>
					</el-col>
					<el-col v-if="false" :span="6">
						<el-form-item label="设备出厂编号">
							<el-input v-model="query.sbccbh" placeholder="设备出厂编号" clearable @clear="search" />	
						</el-form-item>
					</el-col>
					<el-col v-if="false" :span="6">
						<el-form-item label="设备出厂日期">
							<el-date-picker v-model="query.sbccrq" type="daterange" value-format="timestamp" format="yyyy-MM-dd" start-placeholder="开始日期" end-placeholder="结束日期" @change="search">
							</el-date-picker>
						</el-form-item>
					</el-col>
					<el-col :span="6">
						<el-form-item label="备件分类">
							<el-select v-model="query.bjfl" placeholder="备件分类" clearable @clear="search">
								<el-option v-for="(item, index) in bjflOptions" :key="index" :label="item.fullName" :value="item.id"  />
							</el-select>
						</el-form-item>
					</el-col>
					</template>
					<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-button type="text" icon="el-icon-arrow-down" @click="showAll=true" v-if="!showAll">展开</el-button>
							<el-button type="text" icon="el-icon-arrow-up" @click="showAll=false" v-else>收起</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="addOrUpdateHandle()">新增</el-button>
						<el-button type="primary" plain icon="el-icon-download" @click="exportData()">导出</el-button>
						<el-button type="primary" plain icon="el-icon-upload2" @click="uploadForm()">导入</el-button>
						<el-button type="text" icon="el-icon-delete" @click="handleBatchRemoveDel()">批量删除</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="reset()" />
						</el-tooltip>
						<screenfull isContainer />
					</div>
				</div>
                <NCC-table v-loading="listLoading" :data="list" has-c @selection-change="handleSelectionChange">
					<el-table-column prop="mc" label="备件名称" align="left" />
					<el-table-column prop="glcpmc" label="关联产品" align="left" min-width="120">
						<template slot-scope="scope">
							{{ scope.row.glcpmc || getProductName(scope.row.sssb) || '--' }}
						</template>
					</el-table-column>
					<el-table-column prop="bh" label="物料编码" align="left" />
					<el-table-column v-if="false" prop="gg" label="规格型号" align="left" />
					<el-table-column prop="bjwz" label="备件位置" align="left" />
					<el-table-column prop="bjjj" label="备件介绍" align="left" />
					<el-table-column prop="ghzy" label="更换指引" align="left" />
					<el-table-column prop="dhzq" label="订货周期" align="left" />
					<el-table-column prop="sjbj" label="随机备件" align="left" min-width="140" show-overflow-tooltip>
						<template slot-scope="scope">
							<div class="bjxx-file-cell">
								<template v-for="(file, idx) in parseFileList(scope.row.sjbj)">
									<a :key="'sjbj-'+idx" href="javascript:;" class="file-link" @click.prevent="openFile(file)">{{ file.name || file.url || '附件' }}</a>
									<span v-if="idx < parseFileList(scope.row.sjbj).length - 1" class="file-sep">、</span>
								</template>
								<span v-if="!parseFileList(scope.row.sjbj).length" class="text-muted">—</span>
							</div>
						</template>
					</el-table-column>
					<el-table-column prop="ynbj" label="一年备件" align="left" min-width="140" show-overflow-tooltip>
						<template slot-scope="scope">
							<div class="bjxx-file-cell">
								<template v-for="(file, idx) in parseFileList(scope.row.ynbj)">
									<a :key="'ynbj-'+idx" href="javascript:;" class="file-link" @click.prevent="openFile(file)">{{ file.name || file.url || '附件' }}</a>
									<span v-if="idx < parseFileList(scope.row.ynbj).length - 1" class="file-sep">、</span>
								</template>
								<span v-if="!parseFileList(scope.row.ynbj).length" class="text-muted">—</span>
							</div>
						</template>
					</el-table-column>
					<el-table-column prop="lnbj" label="两年备件" align="left" min-width="140" show-overflow-tooltip>
						<template slot-scope="scope">
							<div class="bjxx-file-cell">
								<template v-for="(file, idx) in parseFileList(scope.row.lnbj)">
									<a :key="'lnbj-'+idx" href="javascript:;" class="file-link" @click.prevent="openFile(file)">{{ file.name || file.url || '附件' }}</a>
									<span v-if="idx < parseFileList(scope.row.lnbj).length - 1" class="file-sep">、</span>
								</template>
								<span v-if="!parseFileList(scope.row.lnbj).length" class="text-muted">—</span>
							</div>
						</template>
					</el-table-column>
					<el-table-column label="操作" fixed="right" width="100">
							<template slot-scope="scope">
							<el-button type="text" @click="addOrUpdateHandle(scope.row.id)" >编辑</el-button>
							<el-button type="text" @click="handleDel(scope.row.id)" class="NCC-table-delBtn" >删除</el-button>
						</template>
					</el-table-column>
				</NCC-table>
                <pagination :total="total" :page.sync="listQuery.currentPage" :limit.sync="listQuery.pageSize" @pagination="initData" />
            </div>
        </div>
		<NCC-Form v-if="formVisible" ref="NCCForm" @refresh="refresh" />
		<ImportForm v-if="importFormVisible" ref="importForm" @refresh="refresh" />
	</div>
</template>
<script>
    import request from '@/utils/request'
    import { getDictionaryDataSelector } from '@/api/systemData/dictionary'
    import { getDownloadUrl } from '@/api/common'
    import NCCForm from './Form'
    import ImportForm from './ImportForm'
    import { previewDataInterface } from '@/api/systemData/dataInterface'
	export default {
        components: { NCCForm, ImportForm },
        data() {
            return {
                showAll: false,
				query: {
                    fl:undefined,
                    mc:undefined,
                    bh:undefined,
                    gg:undefined,
                    bjwz:undefined,
                    ghzy:undefined,
                    fbsj:undefined,
                    sbccbh:undefined,
                    sbccrq:undefined,
                    bjfl:undefined,
				},
                list: [],
                listLoading: true,
                multipleSelection: [], total: 0,
                listQuery: {
                    currentPage: 1,
                    pageSize: 20,
					sort: "desc",
                    sidx: "",
                },
                formVisible: false,
                importFormVisible: false,
				bjflOptions : [],
				cpglOptions: [], // 产品管理选项
			}
        },
		computed: {},
		created() {
			this.getbjflOptions();
			this.getCpglOptions().then(() => this.initData());
		},
		methods: {
			getCpglOptions() {
				return request({
					url: '/api/Extend/Cpgl',
					method: 'GET',
					data: { currentPage: 1, pageSize: 1000 }
				}).then(res => {
					this.cpglOptions = res.data.list || []
					return Promise.resolve()
				}).catch(err => {
					console.error('获取产品管理列表失败:', err)
					this.cpglOptions = []
					return Promise.reject(err)
				})
			},
			getProductName(productId) {
				if (!productId) return '--';
				const product = this.cpglOptions.find(item => item.id === productId);
				return product ? (product.cpmc || '--') : '--';
			},
			// 解析备件文件 JSON 为数组，用于列表展示
			parseFileList(fileStr) {
				if (!fileStr) return [];
				try {
					const files = typeof fileStr === 'string' ? JSON.parse(fileStr) : fileStr;
					return Array.isArray(files) ? files : [];
				} catch (e) {
					return [];
				}
			},
			// 文件完整地址（用于直接有 url 时打开）
			fileUrl(file) {
				if (!file) return '#';
				const url = file.url || file.path || file.name || '';
				if (!url) return '#';
				if (url.startsWith('http://') || url.startsWith('https://')) return url;
				const base = (this.define && this.define.comUrl) ? this.define.comUrl : (process.env.VUE_APP_BASE_API || '');
				return base + (url.startsWith('/') ? url : '/' + url);
			},
			// 点击打开文件：有 url 直接打开，否则走下载接口
			openFile(file) {
				if (!file) return;
				if (file.url || file.path) {
					window.open(this.fileUrl(file), '_blank');
					return;
				}
				const id = file.fileId || file.name;
				if (!id) return;
				getDownloadUrl('annex', id).then(res => {
					if (res.data && res.data.url) {
						window.open(this.define.comUrl + res.data.url, '_blank');
					}
				}).catch(() => {});
			},
			getbjflOptions(){
				getDictionaryDataSelector('625969064434468101').then(res => {
					this.bjflOptions = res.data.list
				});
			},
			initData() {
                this.listLoading = true;
                let _query = {
                    ...this.listQuery,
                    ...this.query
                };
                const query = {};
                for (const key in _query) {
                    const val = _query[key];
                    if (val === undefined || val === null || val === '') continue;
                    if (Array.isArray(val)) {
                        query[key] = val.join();
                    } else {
                        // 关联产品(fl) 后端期望字符串，避免类型不一致导致检索失败
                        query[key] = key === 'fl' ? String(val) : val;
                    }
                }
                request({
                    url: `/api/Extend/Bjxx`,
                    method: 'GET',
                    data: query
                }).then(res => {
                    this.list = res.data.list
                    this.total = res.data.pagination.total
                    this.listLoading = false
                })
            },
			uploadForm() {
				this.importFormVisible = true
				this.$nextTick(() => {
					this.$refs.importForm.init()
				})
			},
			handleDel(id) {
                this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
                    type: 'warning'
                }).then(() => {
                    request({
                        url: `/api/Extend/Bjxx/${id}`,
                        method: 'DELETE'
                    }).then(res => {
                        this.$message({
                            type: 'success',
                            message: res.msg,
                            onClose: () => {
                                this.initData()
                            }
                        });
                    })
                }).catch(() => {
                });
            },
			handleSelectionChange(val) {
                const res = val.map(item => item.id)
                this.multipleSelection = res
            },
            handleBatchRemoveDel() {
                if (!this.multipleSelection.length) {
                    this.$message({
                        type: 'error',
                        message: '请选择一条数据',
                        duration: 1500,
                    })
                    return
                }
                const ids = this.multipleSelection
                this.$confirm('您确定要删除这些数据吗, 是否继续？', '提示', {
                    type: 'warning'
                }).then(() => {
                    request({
                        url: `/api/Extend/Bjxx/batchRemove`,
                        method: 'POST',
                        data: ids ,
                    }).then(res => {
                        this.$message({
                            type: 'success',
                            message: res.msg,
                            onClose: () => {
                                this.initData()
                            }
                        });
                    })
                }).catch(() => { })
            },
			addOrUpdateHandle(id, isDetail) {
                this.formVisible = true
                this.$nextTick(() => {
                    this.$refs.NCCForm.init(id, isDetail)
                })
            },
			exportData() {
				const ids = this.multipleSelection && this.multipleSelection.length > 0 ? this.multipleSelection : null
				const query = { ...this.listQuery, ...this.query }
				if (ids && ids.length) query.ids = ids.join(',')
				request({
					url: '/api/Extend/Bjxx/Actions/Export',
					method: 'GET',
					data: query
				}).then(res => {
					if (!res.data || !res.data.url) return
					window.location.href = this.define.comUrl + res.data.url
					this.$message.success('导出成功')
				}).catch(() => {})
			},
			search() {
                this.listQuery = {
                    currentPage: 1,
                    pageSize: 20,
                    sort: "desc",
                    sidx: "",
                }
                this.initData()
            },
            refresh(isrRefresh) {
                this.formVisible = false
                if (isrRefresh) {
                    // 保持当前页码，只刷新数据
                    this.initData()
                }
            },
            reset() {
                for (let key in this.query) {
                    this.query[key] = undefined
                }
                this.listQuery = {
                    currentPage: 1,
                    pageSize: 20,
                    sort: "desc",
                    sidx: "",
                }
                this.initData()
            }
		}
    }
</script>
<style lang="scss" scoped>
.bjxx-file-cell {
	display: flex;
	flex-wrap: wrap;
	align-items: center;
	gap: 2px;
	font-size: 12px;
	.file-link {
		color: #409eff;
		text-decoration: none;
		&:hover { text-decoration: underline; }
	}
	.file-sep { color: #c0c4cc; margin: 0 2px; }
	.text-muted { color: #909399; }
}
</style>