﻿<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="5">
						<el-form-item label="门店编码">
							<el-input 
								v-model="query.mdbm" 
								placeholder="请输入门店编码" 
								clearable 
								prefix-icon="el-icon-search"
								style="border-radius: 6px;" 
							/>	
						</el-form-item>
					</el-col>
					<el-col :span="5">
						<el-form-item label="门店名称">
							<el-input 
								v-model="query.dm" 
								placeholder="请输入门店名称" 
								clearable 
								prefix-icon="el-icon-search"
								style="border-radius: 6px;" 
							/>	
						</el-form-item>
					</el-col>
					<el-col :span="5">
						<el-form-item label="单据门店">
							<el-input 
								v-model="query.djmd" 
								placeholder="请输入单据门店" 
								clearable 
								prefix-icon="el-icon-search"
								style="border-radius: 6px;" 
							/>	
						</el-form-item>
					</el-col>
					<el-col :span="5">
						<el-form-item label="新店状态">
							<el-select 
								v-model="query.isNewStore" 
								placeholder="请选择新店状态" 
								clearable 
								style="width: 100%; border-radius: 6px;"
							>
								<el-option label="新店" :value="true" />
								<el-option label="老店" :value="false" />
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="4">
						<el-form-item>
							<div class="search-buttons" style="height: 32px;">
								<el-button type="primary" icon="el-icon-search" @click="search()">查询</el-button>
								<el-button icon="el-icon-refresh-right" @click="reset()">重置</el-button>
							</div>
						</el-form-item>
					</el-col>
				</el-form>
			</el-row>
			<div class="NCC-common-layout-main NCC-flex-main">
				<div class="NCC-common-head">
					<div class="NCC-common-head-left">
						<h3 class="NCC-common-head-title">
							<i class="el-icon-office-building"></i>
							门店归属管理
						</h3>
					</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"
				>
					<el-table-column prop="mdbm" label="门店编码" align="left" width="120" show-overflow-tooltip>
						<template slot-scope="scope">
							<el-tag size="small" type="primary">{{ scope.row.mdbm }}</el-tag>
						</template>
					</el-table-column>
					<el-table-column prop="dm" label="门店名称" align="left" min-width="150" show-overflow-tooltip>
						<template slot-scope="scope">
							<span class="store-name">{{ scope.row.dm }}</span>
						</template>
					</el-table-column>
					<el-table-column prop="djmd" label="单据门店" align="left" width="150" show-overflow-tooltip />
					<el-table-column label="事业部" prop="syb" align="left" width="120">
						<template slot-scope="scope">
							<el-tag v-if="scope.row.syb" size="small" type="success">
								{{ getDepartmentName(scope.row.syb, sybOptions) }}
							</el-tag>
							<span v-else class="empty-text">无</span>
						</template>
					</el-table-column>
					<el-table-column label="教育部" prop="jyb" align="left" width="120">
						<template slot-scope="scope">
							<el-tag v-if="scope.row.jyb" size="small" type="warning">
								{{ getDepartmentName(scope.row.jyb, jybOptions) }}
							</el-tag>
							<span v-else class="empty-text">无</span>
						</template>
					</el-table-column>
					<el-table-column label="科技部" prop="kjb" align="left" width="120">
						<template slot-scope="scope">
							<el-tag v-if="scope.row.kjb" size="small" type="info">
								{{ getDepartmentName(scope.row.kjb, kjbOptions) }}
							</el-tag>
							<span v-else class="empty-text">无</span>
						</template>
					</el-table-column>
					<el-table-column label="大项目部" prop="dxmb" align="left" width="120">
						<template slot-scope="scope">
							<el-tag v-if="scope.row.dxmb" size="small" type="danger">
								{{ getDepartmentName(scope.row.dxmb, dxmbOptions) }}
							</el-tag>
							<span v-else class="empty-text">无</span>
						</template>
					</el-table-column>
					<el-table-column label="新店状态" align="center" width="100">
						<template slot-scope="scope">
							<el-tag v-if="scope.row.isNewStore" type="success" size="small">
								<i class="el-icon-star-on"></i> 新店
							</el-tag>
							<el-tag v-else type="info" size="small">
								<i class="el-icon-star-off"></i> 老店
							</el-tag>
						</template>
					</el-table-column>
					<el-table-column label="操作" fixed="right" width="200" align="center">
						<template slot-scope="scope">
							<el-button 
								type="text" 
								icon="el-icon-edit" 
								@click="editHandle(scope.row)"
								class="action-btn"
							>
								编辑
							</el-button>
							<el-button 
								type="text" 
								icon="el-icon-view" 
								@click="viewHandle(scope.row)"
								class="action-btn"
							>
								查看
							</el-button>
						</template>
					</el-table-column>
				</NCC-table>
                <pagination :total="total" :page.sync="listQuery.currentPage" :limit.sync="listQuery.pageSize" @pagination="initData" />
            </div>
        </div>
		<!-- 编辑弹窗 -->
		<el-dialog 
			:title="dialogTitle" 
			:visible.sync="dialogVisible" 
			width="700px" 
			:close-on-click-modal="false"
			:before-close="handleClose"
			class="store-dialog"
		>
			<div class="dialog-header">
				<div class="store-info">
					<i class="el-icon-office-building"></i>
					<span class="store-name">{{ editForm.dm }}</span>
					<el-tag size="small" type="primary">{{ editForm.mdbm }}</el-tag>
				</div>
			</div>
			<el-form :model="editForm" :rules="editRules" ref="editForm" label-width="120px" class="edit-form">
				<el-row :gutter="20">
					<el-col :span="12">
						<el-form-item label="事业部" prop="syb">
							<el-select 
								v-model="editForm.syb" 
								placeholder="请选择事业部" 
								clearable 
								style="width: 100%;"
								filterable
							>
								<el-option 
									v-for="item in sybOptions" 
									:key="item.Id" 
									:label="item.FullName" 
									:value="item.Id"
								>
									<span style="float: left">{{ item.FullName }}</span>
									<span style="float: right; color: #8492a6; font-size: 13px">{{ item.EnCode }}</span>
								</el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="教育部" prop="jyb">
							<el-select 
								v-model="editForm.jyb" 
								placeholder="请选择教育部" 
								clearable 
								style="width: 100%;"
								filterable
							>
								<el-option 
									v-for="item in jybOptions" 
									:key="item.Id" 
									:label="item.FullName" 
									:value="item.Id"
								>
									<span style="float: left">{{ item.FullName }}</span>
									<span style="float: right; color: #8492a6; font-size: 13px">{{ item.EnCode }}</span>
								</el-option>
							</el-select>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row :gutter="20">
					<el-col :span="12">
						<el-form-item label="科技部" prop="kjb">
							<el-select 
								v-model="editForm.kjb" 
								placeholder="请选择科技部" 
								clearable 
								style="width: 100%;"
								filterable
							>
								<el-option 
									v-for="item in kjbOptions" 
									:key="item.Id" 
									:label="item.FullName" 
									:value="item.Id"
								>
									<span style="float: left">{{ item.FullName }}</span>
									<span style="float: right; color: #8492a6; font-size: 13px">{{ item.EnCode }}</span>
								</el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="大项目部" prop="dxmb">
							<el-select 
								v-model="editForm.dxmb" 
								placeholder="请选择大项目部" 
								clearable 
								style="width: 100%;"
								filterable
							>
								<el-option 
									v-for="item in dxmbOptions" 
									:key="item.Id" 
									:label="item.FullName" 
									:value="item.Id"
								>
									<span style="float: left">{{ item.FullName }}</span>
									<span style="float: right; color: #8492a6; font-size: 13px">{{ item.EnCode }}</span>
								</el-option>
							</el-select>
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click="handleClose" :disabled="saveLoading">取消</el-button>
				<el-button type="primary" @click="saveEdit" :loading="saveLoading">
					<i class="el-icon-check"></i> 保存
				</el-button>
			</div>
		</el-dialog>

	</div>
</template>
<script>
    import request from '@/utils/request'
	export default {
        data() {
            return {
				query: {
                    mdbm: undefined,
                    dm: undefined,
                    djmd: undefined,
                    isNewStore: undefined
				},
                list: [],
                listLoading: true,
                total: 0,
                listQuery: {
                    currentPage: 1,
                    pageSize: 20,
					sort: "desc",
                    sidx: "",
                },
                dialogVisible: false,
                saveLoading: false,
                dialogTitle: '编辑门店归属',
                editForm: {
                    id: '',
                    mdbm: '',
                    dm: '',
                    syb: '',
                    jyb: '',
                    kjb: '',
                    dxmb: ''
                },
                editRules: {
                    syb: [{ required: false, message: '请选择事业部', trigger: 'change' }],
                    jyb: [{ required: false, message: '请选择教育部', trigger: 'change' }],
                    kjb: [{ required: false, message: '请选择科技部', trigger: 'change' }],
                    dxmb: [{ required: false, message: '请选择大项目部', trigger: 'change' }]
                },
                columnList: [
                    { prop: 'mdbm', label: '门店编码' },
                    { prop: 'dm', label: '门店名称' },
                    { prop: 'djmd', label: '单据门店' },
                    { prop: 'syb', label: '事业部' },
                    { prop: 'jyb', label: '教育部' },
                    { prop: 'kjb', label: '科技部' },
                    { prop: 'dxmb', label: '大项目部' },
                    { prop: 'isNewStore', label: '是否新店' }
				],
				sybOptions: [],
				jybOptions: [],
				kjbOptions: [],
				dxmbOptions: [],
			}
        },
		computed: {},
		created() {
			this.initData()
			this.loadDepartmentOptions()
		},
		methods: {
			// 加载部门选项
			loadDepartmentOptions() {
				// 加载事业部
				request({
					url: '/api/Extend/Organize/GetByName',
					method: 'GET',
					data: { organizeName: '事业部' }
				}).then(res => {
					this.sybOptions = res.data || []
				}).catch(() => {
					this.sybOptions = []
				})

				// 加载教育部
				request({
					url: '/api/Extend/Organize/GetByName',
					method: 'GET',
					data: { organizeName: '教育部' }
				}).then(res => {
					this.jybOptions = res.data || []
				}).catch(() => {
					this.jybOptions = []
				})

				// 加载科技部
				request({
					url: '/api/Extend/Organize/GetByName',
					method: 'GET',
					data: { organizeName: '科技部' }
				}).then(res => {
					this.kjbOptions = res.data || []
				}).catch(() => {
					this.kjbOptions = []
				})

				// 加载大项目部
				request({
					url: '/api/Extend/Organize/GetByName',
					method: 'GET',
					data: { organizeName: '大项目部' }
				}).then(res => {
					this.dxmbOptions = res.data || []
				}).catch(() => {
					this.dxmbOptions = []
				})
			},

			// 获取部门名称
			getDepartmentName(id, options) {
				const option = options.find(item => item.Id === id)
				return option ? option.FullName : '未知'
			},

			// 加载所有门店的新店保护状态
			async loadNewStoreStatus() {
				if (!this.list || this.list.length === 0) return
				
				// 并行查询所有门店的保护状态
				const promises = this.list.map(async (row) => {
					if (!row.id) {
						this.$set(row, 'isNewStore', false)
						return
					}
					
					try {
						const res = await request({
							url: `/api/Extend/LqMdXdbhsj/GetByStoreId/${row.id}`,
							method: 'GET'
						})
						
						this.$set(row, 'isNewStore', res.data && res.data.hasProtection === true)
						
					} catch (error) {
						console.error(`查询门店 ${row.dm} 保护时间失败:`, error)
						this.$set(row, 'isNewStore', false)
					}
				})
				
				await Promise.all(promises)
			},

			// 判断是否为新店（通过门店新店保护时间表查询）
			async isNewStore(row) {
				if (!row.id) return false
				
				try {
					const res = await request({
						url: `/api/Extend/LqMdXdbhsj/GetByStoreId/${row.id}`,
						method: 'GET'
					})
					
					const isNew = res.data && res.data.hasProtection === true
					this.$set(row, 'isNewStore', isNew)
					return isNew
				} catch (error) {
					console.error(`查询门店 ${row.dm} 保护时间失败:`, error)
					this.$set(row, 'isNewStore', false)
					return false
				}
			},

			// 编辑处理
			editHandle(row) {
				this.dialogTitle = '编辑门店归属'
				this.editForm = {
					id: row.id,
					mdbm: row.mdbm,
					dm: row.dm,
					syb: row.syb || '',
					jyb: row.jyb || '',
					kjb: row.kjb || '',
					dxmb: row.dxmb || ''
				}
				this.dialogVisible = true
			},

			// 查看处理
			viewHandle(row) {
				this.dialogTitle = '查看门店归属'
				this.editForm = {
					id: row.id,
					mdbm: row.mdbm,
					dm: row.dm,
					syb: row.syb || '',
					jyb: row.jyb || '',
					kjb: row.kjb || '',
					dxmb: row.dxmb || ''
				}
				this.dialogVisible = true
			},


			// 弹窗关闭处理
			handleClose() {
				if (this.saveLoading) {
					this.$message.warning('正在保存中，请稍候...')
					return
				}
				this.dialogVisible = false
				this.$refs.editForm && this.$refs.editForm.resetFields()
			},

			// 保存编辑
			saveEdit() {
				this.$refs.editForm.validate((valid) => {
					if (valid) {
						this.saveLoading = true
						request({
							url: `/api/Extend/LqMdxx/${this.editForm.id}`,
							method: 'PUT',
							data: {
								syb: this.editForm.syb,
								jyb: this.editForm.jyb,
								kjb: this.editForm.kjb,
								dxmb: this.editForm.dxmb
							}
						}).then(res => {
							this.$message.success('保存成功')
							this.dialogVisible = false
							this.initData()
						}).catch(() => {
							this.$message.error('保存失败')
						}).finally(() => {
							this.saveLoading = false
						})
					}
				})
			},


			async initData() {
                this.listLoading = true;
                let _query = {
                    ...this.listQuery,
                    ...this.query
                };
                let query = {}
                for (let key in _query) {
                    if (Array.isArray(_query[key])) {
                        query[key] = _query[key].join()
                    } else {
                        query[key] = _query[key]
                    }
                }
                
                try {
                    const res = await request({
                        url: `/api/Extend/LqMdxx`,
                        method: 'GET',
                        data: query
                    })
                    
                    this.list = res.data.list
                    this.total = res.data.pagination.total
                    
                    // 为每个门店查询新店保护状态
                    await this.loadNewStoreStatus()
                    
                } catch (error) {
                    console.error('加载门店数据失败:', error)
                } finally {
                    this.listLoading = false
                }
            },

			search() {
                this.listQuery = {
                    currentPage: 1,
                    pageSize: 20,
                    sort: "desc",
                    sidx: "",
                }
                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>
	// 页面头部样式
	.NCC-common-head-left {
		display: flex;
		align-items: center;
		gap: 12px;
	}

	.NCC-common-head-title {
		margin: 0;
		font-size: 18px;
		font-weight: 600;
		color: #303133;
		display: flex;
		align-items: center;
		gap: 8px;

		i {
			color: #409EFF;
			font-size: 20px;
		}
	}


	// 表格样式
	.store-name {
		font-weight: 500;
		color: #303133;
	}

	.empty-text {
		color: #C0C4CC;
		font-style: italic;
	}

	.action-btn {
		padding: 4px 8px;
		margin: 0 2px;
		
		&:hover {
			background-color: #f5f7fa;
		}
	}

	// 弹窗样式
	.store-dialog {
		.dialog-header {
			padding: 16px 0;
			border-bottom: 1px solid #EBEEF5;
			margin-bottom: 20px;

			.store-info {
				display: flex;
				align-items: center;
				gap: 12px;

				i {
					font-size: 20px;
					color: #409EFF;
				}

				.store-name {
					font-size: 16px;
					font-weight: 600;
					color: #303133;
				}
			}
		}

		.edit-form {
			.el-form-item {
				margin-bottom: 20px;
			}
		}
	}


	// 搜索区域样式
	.search-buttons {
		display: flex;
		align-items: center;
		gap: 8px;
	}

	// 响应式设计
	@media (max-width: 768px) {
		.NCC-common-head {
			flex-direction: column;
			align-items: flex-start;
			gap: 12px;

			.NCC-common-head-right {
				width: 100%;
				justify-content: flex-start;
			}
		}

		.el-col {
			margin-bottom: 16px;
		}

		.store-dialog {
			.el-dialog {
				width: 95% !important;
				margin: 0 auto;
			}
		}
	}

	// 表格响应式
	@media (max-width: 1200px) {
		.NCC-table {
			.el-table {
				font-size: 12px;
			}
		}
	}
</style>