Form.vue 33.9 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141
<template>
	<el-dialog :title="!dataForm.id ? '新建' : isDetail ? '详情' : '编辑'" :close-on-click-modal="false"
		:visible.sync="visible" class="NCC-dialog NCC-dialog_center" lock-scroll width="720px">
		<el-row :gutter="15">
			<el-form ref="elForm" :model="dataForm" size="small" label-width="100px" label-position="right"
				:disabled="!!isDetail" :rules="rules">
				<!-- 基础信息字段 -->
				<el-col :span="24" v-if="false">
					<el-form-item label="主键" prop="id">
						<el-input v-model="dataForm.id" />
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item label="门店编码" prop="mdbm">
						<el-input v-model="dataForm.mdbm" placeholder="请输入" clearable />
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item label="店名" prop="dm">
						<el-input v-model="dataForm.dm" placeholder="请输入" clearable />
					</el-form-item>
				</el-col>
				<el-col :span="24">
					<el-form-item label="地址" prop="dz">
						<el-input v-model="dataForm.dz" placeholder="请输入完整地址" clearable>
							<el-button slot="append" icon="el-icon-location-outline"
								@click="handleOpenLocation">地图定位</el-button>
						</el-input>
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item label="经度" prop="longitude">
						<el-input v-model="dataForm.longitude" readonly placeholder="请通过地图定位选择" />
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item label="纬度" prop="latitude">
						<el-input v-model="dataForm.latitude" readonly placeholder="请通过地图定位选择" />
					</el-form-item>
				</el-col>
				<el-col :span="24">
					<el-form-item label="电子围栏">
						<div class="fence-status-bar">
							<el-tag :type="dataForm.fencePolygons && dataForm.fencePolygons.length ? 'success' : 'info'"
								size="medium">
								{{ (dataForm.fencePolygons && dataForm.fencePolygons.length) ? '已设置围栏 (1块)' : '未设置围栏' }}
							</el-tag>
							<el-button type="primary" size="mini" icon="el-icon-edit" class="fence-action-btn"
								:disabled="!dataForm.longitude || !dataForm.latitude" @click="handleOpenFence">
								设置围栏
							</el-button>
							<span v-if="!dataForm.longitude" class="hint-text">(请先完成地图定位)</span>
						</div>
					</el-form-item>
				</el-col>

				<!-- 其他业务字段 -->
				<el-col :span="12">
					<el-form-item label="城市" prop="cs">
						<el-input v-model="dataForm.cs" placeholder="请输入" clearable />
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item label="最新状态" prop="zxzt">
						<el-select v-model="dataForm.zxzt" placeholder="请选择" clearable :style='{ "width": "100%" }'>
							<el-option v-for="(item, index) in zxztOptions" :key="index" :label="item.fullName"
								:value="item.id"></el-option>
						</el-select>
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item label="门店类别" prop="storeCategory">
						<el-select v-model="dataForm.storeCategory" placeholder="请选择" clearable
							:style='{ "width": "100%" }'>
							<el-option v-for="(item, index) in storeCategoryOptions" :key="index" :label="item.Name"
								:value="item.Value"></el-option>
						</el-select>
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item label="门店类型" prop="storeType">
						<el-select v-model="dataForm.storeType" placeholder="请选择" clearable
							:style='{ "width": "100%" }'>
							<el-option v-for="(item, index) in storeTypeOptions" :key="index" :label="item.Name"
								:value="item.Value"></el-option>
						</el-select>
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item label="姓名" prop="xm">
						<el-input v-model="dataForm.xm" placeholder="请输入" clearable />
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item label="电话号码" prop="dhhm">
						<el-input v-model="dataForm.dhhm" placeholder="请输入" clearable />
					</el-form-item>
				</el-col>
				<el-col :span="24">
					<el-form-item label="门店图片" prop="storeImages">
						<NCC-UploadImg v-model="dataForm.storeImages" :fileSize="5" sizeUnit="MB" :limit="9" :disabled="!!isDetail" />
					</el-form-item>
				</el-col>
				<el-col :span="24">
					<el-form-item label="门店介绍" prop="storeDescription">
						<el-input v-model="dataForm.storeDescription" type="textarea" :rows="4" maxlength="1000" show-word-limit
							placeholder="请输入门店介绍" />
					</el-form-item>
				</el-col>
				<el-col :span="24">
					<el-form-item label="营业时间设置" prop="businessHours">
						<el-input
							v-model="dataForm.businessHours"
							type="textarea"
							:rows="3"
							maxlength="500"
							show-word-limit
							placeholder="请输入营业时间设置"
						/>
					</el-form-item>
				</el-col>
				<el-col :span="24">
					<el-form-item label="交通提示" prop="trafficTips">
						<el-input
							v-model="dataForm.trafficTips"
							type="textarea"
							:rows="3"
							maxlength="500"
							show-word-limit
							placeholder="请输入交通提示"
						/>
					</el-form-item>
				</el-col>
				<el-col :span="24">
					<el-form-item label="门店标签" prop="storeTags">
						<div class="store-tags-editor">
							<div class="store-tags-list">
								<el-tag
									v-for="(tag, index) in dataForm.storeTags"
									:key="`${tag}-${index}`"
									:disable-transitions="false"
									:closable="!isDetail"
									@close="handleRemoveTag(index)">
									{{ tag }}
								</el-tag>
								<span v-if="!dataForm.storeTags.length" class="store-tags-empty">暂无标签</span>
							</div>
							<div class="store-tags-action-row" v-if="!isDetail">
								<el-input
									v-if="inputTagVisible"
									ref="tagInput"
									v-model="inputTagValue"
									class="input-new-tag"
									size="small"
									maxlength="20"
									placeholder="请输入标签内容"
									@keyup.enter.native="handleInputTagConfirm"
									@blur="handleInputTagConfirm"
								/>
								<el-button
									v-else
									class="button-new-tag tag-action-btn"
									size="small"
									icon="el-icon-plus"
									@click="showTagInput">
									新增标签
								</el-button>
							</div>
						</div>
					</el-form-item>
				</el-col>
			</el-form>
		</el-row>
		<span slot="footer" class="dialog-footer">
			<el-button @click="visible = false">取 消</el-button>
			<el-button type="primary" @click="dataFormSubmit()" v-if="!isDetail">确 定</el-button>
		</span>

		<!-- 定位弹窗 -->
		<el-dialog title="门店地图定位" :visible.sync="locationVisible" width="800px" append-to-body class="map-dialog">
			<div class="map-container-wrapper">
				<div class="map-header-bar">
					<span>在地图上点击以选择门店位置,或通过地址检索定位</span>
					<div class="coordinate-info" v-if="tempMarker.lng">
						当前选择:{{ tempMarker.lng.toFixed(6) }}, {{ tempMarker.lat.toFixed(6) }}
					</div>
				</div>
				<div class="location-search-bar">
					<el-input
						v-model="locationSearchKeyword"
						placeholder="输入地址或关键词检索(如:成都市武侯区紫荆北路182号)"
						clearable
						size="small"
						class="search-input"
						@keyup.enter.native="handleSearchLocation"
					>
						<el-button slot="append" icon="el-icon-search" @click="handleSearchLocation" :loading="locationSearchLoading">检索</el-button>
					</el-input>
				</div>
				<div id="location-map" class="map-canvas"></div>
			</div>
			<span slot="footer" class="dialog-footer">
				<el-button @click="locationVisible = false">取 消</el-button>
				<el-button type="primary" @click="confirmLocation" :disabled="!tempMarker.lng">确 定</el-button>
			</span>
		</el-dialog>

		<!-- 围栏设置弹窗 -->
		<el-dialog title="设置电子围栏" :visible.sync="fenceVisible" width="1000px" append-to-body class="map-dialog">
			<div class="fence-editor-layout">
				<div class="map-side-panel">
					<div class="panel-header">图形管理 ({{ fenceBuffer.length }})</div>
					<div class="shape-list">
						<div v-for="(shape, index) in fenceBuffer" :key="index" class="shape-item">
							<i :class="getShapeIcon(shape.type)"></i>
							<span class="shape-name">{{ getShapeName(shape.type) }} {{ index + 1 }}</span>
							<el-button type="text" icon="el-icon-delete" class="delete-btn"
								@click="removeBufferShape(index)"></el-button>
						</div>
						<div v-if="!fenceBuffer.length" class="empty-text">暂无图形,请在右侧绘制</div>
					</div>
					<div class="panel-footer">
						<p class="warning-text" v-if="fenceBuffer.length > 1">
							<i class="el-icon-warning"></i> 注意:最终只能保留1个围栏
						</p>
					</div>
				</div>
				<div class="map-main-area">
					<div class="map-toolbar">
						<div v-for="tool in fenceTools" :key="tool.id" class="tool-btn"
							:class="{ active: activeFenceTool === tool.id }" @click="changeFenceTool(tool.id)">
							<span class="tool-icon" :class="'tool-icon--' + tool.id"></span>
							<span class="tool-label">{{ tool.name }}</span>
						</div>
					</div>
					<div id="fence-map" class="map-canvas"></div>
				</div>
			</div>
			<span slot="footer" class="dialog-footer">
				<div class="footer-hint" v-if="fenceBuffer.length > 1">请删除多余图形,仅保留一个围栏后再保存</div>
				<el-button @click="fenceVisible = false">取 消</el-button>
				<el-button type="primary" @click="confirmFence" :disabled="fenceBuffer.length !== 1">确 定 保 存</el-button>
			</span>
		</el-dialog>
	</el-dialog>
</template>

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

// 腾讯地图 WebService API Key(与地图脚本共用,需在腾讯控制台开启 WebServiceAPI)
const TMAP_WS_KEY = 'YRXBZ-NEV6T-K7SXH-VJPMF-G5IQF-F3FCJ'

// JSONP 调用(绕过 CORS,腾讯 WebService API 前端需用 JSONP)
function jsonp(url) {
  return new Promise((resolve, reject) => {
    const cbName = '_tmap_jsonp_' + Date.now() + '_' + Math.random().toString(36).slice(2);
    const script = document.createElement('script');
    script.src = url + (url.indexOf('?') >= 0 ? '&' : '?') + 'output=jsonp&callback=' + cbName;
    window[cbName] = function(res) {
      if (script.parentNode) script.parentNode.removeChild(script);
      delete window[cbName];
      resolve(res);
    };
    script.onerror = function() {
      if (script.parentNode) script.parentNode.removeChild(script);
      delete window[cbName];
      reject(new Error('JSONP request failed'));
    };
    document.body.appendChild(script);
  });
}

export default {
	data() {
		return {
			loading: false,
			visible: false,
			isDetail: false,
			dataForm: {
				id: undefined,
				mdbm: undefined,
				dm: undefined,
				dz: undefined,
				cs: undefined,
				xm: undefined,
				dhhm: undefined,
				zxzt: undefined,
				storeCategory: undefined,
				storeType: undefined,
				longitude: null,
				latitude: null,
				fencePolygons: [],
				storeImages: [],
				storeDescription: '',
				storeTags: [],
				businessHours: '',
				trafficTips: '',
			},
			rules: {
				mdbm: [{ required: true, message: '请输入门店编码', trigger: 'blur' }],
				dm: [{ required: true, message: '请输入店名', trigger: 'blur' }],
				dz: [{ required: true, message: '请输入地址', trigger: 'blur' }],
			},
			zxztOptions: [{ fullName: '开店', id: '开店' }, { fullName: '闭店', id: '闭店' }],
			storeCategoryOptions: [],
			storeTypeOptions: [],

			// 定位弹窗相关
			locationVisible: false,
			locationMap: null,
			locationMarkerLayer: null,
			tempMarker: { lng: null, lat: null },
			locationSearchKeyword: '',
			locationSearchLoading: false,

			// 围栏弹窗相关
			fenceVisible: false,
			fenceMap: null,
			fenceEditor: null,
			fenceDrawLayers: {},     // 绘图图层(只保留多边形 / 圆形)
			fenceDisplayLayer: null, // 展示层(显示 buffer 中的图形)
			activeFenceTool: 'polygon',
			fenceBuffer: [], // 临时存放绘制的多个图形:[{ id, type, points, geometry }]
			// 目前仅支持多边形 / 圆形两个工具,矩形与椭圆功能取消
			fenceTools: [
				{ id: 'polygon', name: '多边形' },
				{ id: 'circle', name: '圆形' }
			],
			inputTagVisible: false,
			inputTagValue: ''
		}
	},
	created() {
		this.loadStoreCategoryOptions();
		this.loadStoreTypeOptions();
	},
	methods: {
		loadStoreCategoryOptions() {
			request({ url: '/api/Extend/lqmdxx/Selector/StoreCategory', method: 'get' })
				.then(res => { this.storeCategoryOptions = res.data || []; });
		},
		loadStoreTypeOptions() {
			request({ url: '/api/Extend/lqmdxx/Selector/StoreType', method: 'get' })
				.then(res => { this.storeTypeOptions = res.data || []; });
		},

		init(id, isDetail) {
			this.dataForm.id = id || 0;
			this.visible = true;
			this.isDetail = isDetail || false;
			this.inputTagVisible = false;
			this.inputTagValue = '';
			this.$nextTick(() => {
				this.$refs['elForm'].resetFields();
				if (this.dataForm.id) {
					request({ url: '/api/Extend/LqMdxx/' + this.dataForm.id, method: 'get' })
						.then(res => {
							const raw = res.data || {};
							// 合并接口数据,保留 dataForm 默认结构
							this.dataForm = {
								...this.dataForm,
								...raw,
								// 经纬度:兼容后端 camelCase / PascalCase(避免 ?? 语法,兼容旧 Babel)
								longitude: raw.longitude != null ? raw.longitude : (raw.Longitude != null ? raw.Longitude : this.dataForm.longitude),
								latitude: raw.latitude != null ? raw.latitude : (raw.Latitude != null ? raw.Latitude : this.dataForm.latitude)
							};
							// fencePolygons:后端返回 JSON 字符串需解析为数组,兼容 fence_polygons 字段名
							const fpRaw = raw.fencePolygons != null ? raw.fencePolygons : (raw.fence_polygons != null ? raw.fence_polygons : raw.FencePolygons);
							if (typeof fpRaw === 'string') {
								try {
									this.dataForm.fencePolygons = JSON.parse(fpRaw) || [];
								} catch (e) {
									this.dataForm.fencePolygons = [];
								}
							} else if (Array.isArray(fpRaw)) {
								this.dataForm.fencePolygons = fpRaw;
							} else {
								this.dataForm.fencePolygons = Array.isArray(this.dataForm.fencePolygons) ? this.dataForm.fencePolygons : [];
							}
							this.dataForm.storeImages = this.parseJsonArray(raw.storeImages);
							this.dataForm.storeTags = this.parseJsonStringArray(raw.storeTags);
							this.dataForm.storeDescription = raw.storeDescription || '';
							this.dataForm.businessHours = raw.businessHours || '';
							this.dataForm.trafficTips = raw.trafficTips || '';
						});
				} else {
					// 新建时重置经纬度与围栏
					this.dataForm.longitude = null;
					this.dataForm.latitude = null;
					this.dataForm.fencePolygons = [];
					this.dataForm.storeImages = [];
					this.dataForm.storeDescription = '';
					this.dataForm.storeTags = [];
					this.dataForm.businessHours = '';
					this.dataForm.trafficTips = '';
				}
			})
		},

		parseJsonArray(value) {
			if (!value) return [];
			if (Array.isArray(value)) return value;
			if (typeof value === 'string') {
				try {
					const parsed = JSON.parse(value);
					return Array.isArray(parsed) ? parsed : [];
				} catch (e) {
					return [];
				}
			}
			return [];
		},

		parseJsonStringArray(value) {
			const parsed = this.parseJsonArray(value);
			return parsed.map(item => (item || '').toString().trim()).filter(Boolean);
		},

		showTagInput() {
			this.inputTagVisible = true;
			this.$nextTick(() => {
				if (this.$refs.tagInput && this.$refs.tagInput.$refs && this.$refs.tagInput.$refs.input) {
					this.$refs.tagInput.$refs.input.focus();
				}
			});
		},

		handleInputTagConfirm() {
			const value = (this.inputTagValue || '').trim();
			if (value && !this.dataForm.storeTags.includes(value)) {
				this.dataForm.storeTags.push(value);
			}
			this.inputTagVisible = false;
			this.inputTagValue = '';
		},

		handleRemoveTag(index) {
			if (this.isDetail) return;
			this.dataForm.storeTags.splice(index, 1);
		},

		loadTMapScript() {
			return new Promise((resolve, reject) => {
				if (window.TMap) return resolve();
				const script = document.createElement('script');
				script.src = 'https://map.qq.com/api/gljs?v=1.exp&key=YRXBZ-NEV6T-K7SXH-VJPMF-G5IQF-F3FCJ&libraries=tools,geometry';
				script.onload = resolve;
				script.onerror = reject;
				document.body.appendChild(script);
			});
		},

		// --- 门店定位逻辑 ---
		handleOpenLocation() {
			this.locationVisible = true;
			// 若已有经纬度,则以门店经纬度为中心;否则先不设置,等 IP 定位
			this.tempMarker = {
				lng: this.dataForm.longitude,
				lat: this.dataForm.latitude
			};
			// 仅作为默认检索关键字,不自动发起检索
			this.locationSearchKeyword = this.dataForm.dz || '';

			this.$nextTick(() => {
				// 如果已有经纬度,直接按门店坐标初始化地图
				if (this.dataForm.longitude && this.dataForm.latitude) {
					this.initLocationMap();
				} else {
					// 无经纬度时,优先用 IP 做一个大概定位,再初始化地图
					this.initLocationWithIp();
				}
			});
		},

		// 使用腾讯地图 IP 定位作为初始中心(仅在没有门店经纬度时调用)
		initLocationWithIp() {
			const ipUrl = 'https://apis.map.qq.com/ws/location/v1/ip?key=' + TMAP_WS_KEY;
			// 先尝试 IP 定位(JSONP),成功后设置 tempMarker 再初始化地图;失败则走默认中心
			jsonp(ipUrl)
				.then((res) => {
					if (res.status === 0 && res.result && res.result.location) {
						const loc = res.result.location;
						this.tempMarker = { lng: loc.lng, lat: loc.lat };
						// 同步一下城市,便于后续检索时 region 使用
						if (res.result.ad_info && res.result.ad_info.city && !this.dataForm.cs) {
							this.dataForm.cs = res.result.ad_info.city;
						}
					}
					this.initLocationMap();
				})
				.catch(() => {
					this.initLocationMap();
				});
		},

		// 地址检索:使用腾讯地图 WebService API(地址解析 + 地点搜索)
		handleSearchLocation() {
			const keyword = (this.locationSearchKeyword || '').trim();
			if (!keyword) {
				this.$message.warning('请输入地址或关键词');
				return;
			}
			this.locationSearchLoading = true;
			const region = this.dataForm.cs || '';

			// 1. 先调用地址解析 API(适合完整地址),使用 JSONP 绕过 CORS
			const geocoderUrl = 'https://apis.map.qq.com/ws/geocoder/v1/?address=' + encodeURIComponent(keyword) + '&key=' + TMAP_WS_KEY + (region ? '&region=' + encodeURIComponent(region) : '');
			jsonp(geocoderUrl)
				.then((res) => {
					if (res.status === 0 && res.result && res.result.location) {
						const loc = res.result.location;
						this.applySearchResult(loc.lat, loc.lng);
						this.locationSearchLoading = false;
						this.$message.success('检索成功');
					} else {
						this.searchByKeyword(keyword, region);
					}
				})
				.catch(() => {
					this.searchByKeyword(keyword, region);
				});
		},

		// 关键词搜索:使用腾讯地图地点搜索 WebService API
		searchByKeyword(keyword, region) {
			const cityName = region || '全国';
			const boundary = 'region(' + cityName + ',1)';
			const searchUrl = 'https://apis.map.qq.com/ws/place/v1/search?keyword=' + encodeURIComponent(keyword) + '&boundary=' + encodeURIComponent(boundary) + '&page_size=10&key=' + TMAP_WS_KEY;
			jsonp(searchUrl)
				.then((res) => {
					this.locationSearchLoading = false;
					if (res.status === 0 && res.data && res.data.length > 0) {
						const first = res.data[0];
						const loc = first.location;
						this.applySearchResult(loc.lat, loc.lng);
						this.$message.success('检索成功');
					} else {
						this.$message.warning('未找到匹配结果,请尝试其他关键词或在地图上直接点击选择');
					}
				})
				.catch(() => {
					this.locationSearchLoading = false;
					this.$message.error('检索失败,请稍后再试');
				});
		},

		// 将检索结果应用到地图(移动中心、设置标记)
		applySearchResult(lat, lng) {
			this.tempMarker = { lng: lng, lat: lat };
			if (window.TMap && this.locationMarkerLayer) {
				const TMap = window.TMap;
				this.locationMarkerLayer.setGeometries([{ id: 'm', position: new TMap.LatLng(lat, lng) }]);
			}
			if (window.TMap && this.locationMap) {
				const TMap = window.TMap;
				this.locationMap.setCenter(new TMap.LatLng(lat, lng));
				this.locationMap.setZoom(16);
			}
		},

		initLocationMap() {
			this.loadTMapScript().then(() => {
				const TMap = window.TMap;
				const centerLat = this.tempMarker.lat || 30.656149; // 成都
				const centerLng = this.tempMarker.lng || 104.065735;
				const center = new TMap.LatLng(centerLat, centerLng);

				this.locationMap = new TMap.Map('location-map', { center, zoom: 14 });
				this.locationMarkerLayer = new TMap.MultiMarker({ map: this.locationMap, geometries: [] });

				if (this.tempMarker.lng) {
					this.locationMarkerLayer.setGeometries([{ id: 'm', position: new TMap.LatLng(this.tempMarker.lat, this.tempMarker.lng) }]);
				}

				this.locationMap.on('click', (evt) => {
					if (!evt.latLng) return;
					const lat = evt.latLng.getLat();
					const lng = evt.latLng.getLng();
					this.tempMarker = { lng, lat };
					this.locationMarkerLayer.setGeometries([{ id: 'm', position: evt.latLng }]);
				});
			});
		},

		confirmLocation() {
			this.dataForm.longitude = this.tempMarker.lng;
			this.dataForm.latitude = this.tempMarker.lat;
			this.locationVisible = false;
		},

		// --- 围栏设置逻辑 ---
		handleOpenFence() {
			if (!this.dataForm.longitude) return;
			this.fenceVisible = true;
			// 初始化 Buffer:历史上如果有多块,只保留第一块,保证始终至多一个围栏
			const polygons = Array.isArray(this.dataForm.fencePolygons) ? this.dataForm.fencePolygons : [];
			if (polygons.length > 0 && Array.isArray(polygons[0])) {
				this.fenceBuffer = [{
					id: `old-${Date.now()}`,
					type: 'polygon',
					points: polygons[0]
				}];
			} else {
				this.fenceBuffer = [];
			}
			this.$nextTick(() => {
				this.initFenceMap();
			});
		},

		initFenceMap() {
			this.loadTMapScript().then(() => {
				const TMap = window.TMap;
				const center = new TMap.LatLng(this.dataForm.latitude, this.dataForm.longitude);
				this.fenceMap = new TMap.Map('fence-map', { center, zoom: 16 });

				// 1. 门店位置固定标点
				this.fenceStoreMarkerLayer = new TMap.MultiMarker({
					map: this.fenceMap,
					geometries: [{ id: 'store', position: center }]
				});

				// 2. 初始化展示层
				this.fenceDisplayLayer = new TMap.MultiPolygon({
					map: this.fenceMap,
					geometries: [],
					styles: {
						default: new TMap.PolygonStyle({
							color: 'rgba(41,182,246,0.2)',
							borderColor: 'rgba(41,182,246,0.9)',
							borderWidth: 2
						})
					}
				});

				// 3. 构建临时绘制图层:
				//    - 一个多边形图层 polygonLayer
				//    - 一个圆形图层 circleLayer
				const polygonLayer = new TMap.MultiPolygon({
					map: this.fenceMap,
					geometries: [],
					styles: {
						default: new TMap.PolygonStyle({
							color: 'rgba(255,152,0,0.2)',
							borderColor: '#FF9800',
							borderWidth: 2
						})
					}
				});
				const circleLayer = new TMap.MultiCircle({
					map: this.fenceMap,
					geometries: [],
					styles: {
						default: new TMap.CircleStyle({
							color: 'rgba(255,152,0,0.2)',
							borderColor: '#FF9800',
							borderWidth: 2
						})
					}
				});
				this.fenceDrawLayers = {
					polygon: polygonLayer,
					circle: circleLayer
				};

				// 4. 初始化唯一编辑器(后续不再整体销毁,只清空内容)
				this.fenceEditor = new TMap.tools.GeometryEditor({
					map: this.fenceMap,
					overlayList: [
						{ overlay: polygonLayer, id: 'polygon' },
						{ overlay: circleLayer, id: 'circle' }
					],
					actionMode: TMap.tools.constants.EDITOR_ACTION.DRAW,
					activeOverlayId: 'polygon',
					snappable: true
				});

				// 5. 监听绘制完毕事件:每次只保留当前绘制结果为唯一围栏
				this.fenceEditor.on('draw_complete', (geometry) => {
					const toolId = this.activeFenceTool;
					const points = this._extractPoints(toolId, geometry);

					if (points && points.length >= 3) {
						// 业务约束:无论之前画了什么,本次绘制即为“唯一围栏”
						this.fenceBuffer = [{
							id: `shape-${Date.now()}`,
							type: toolId,
							points: points
						}];
						this.refreshFenceDisplay();
					}

					// 绘制完毕后:不销毁 Editor,只清空对应图层的临时几何
					const drawLayer = this.fenceDrawLayers[toolId];
					if (drawLayer && typeof drawLayer.setGeometries === 'function') {
						drawLayer.setGeometries([]);
					}

					// 延迟一帧重置绘制状态,避免与内部事件冲突
					setTimeout(() => {
						if (this.fenceEditor && window.TMap && window.TMap.tools && window.TMap.tools.constants) {
							this.fenceEditor.setActiveOverlay(toolId);
							this.fenceEditor.setActionMode(window.TMap.tools.constants.EDITOR_ACTION.DRAW);
						}
					}, 20);
				});

				this.refreshFenceDisplay();
			});
		},

		changeFenceTool(id) {
			this.activeFenceTool = id;
			if (this.fenceEditor) {
				// 清除可能画了一半的所有绘制层(去重后防止同一图层重复清理)
				const uniqueLayers = Object.values(this.fenceDrawLayers).filter((layer, index, arr) => arr.indexOf(layer) === index);
				uniqueLayers.forEach(layer => {
					if (layer && typeof layer.setGeometries === 'function') {
						layer.setGeometries([]);
					}
				});

				this.fenceEditor.setActiveOverlay(id);
				this.fenceEditor.setActionMode(window.TMap.tools.constants.EDITOR_ACTION.DRAW);
			}
		},

		refreshFenceDisplay() {
			if (!this.fenceDisplayLayer) return;
			const TMap = window.TMap;
			const geometries = this.fenceBuffer.map(item => {
				const path = item.points.map(p => new TMap.LatLng(p.lat, p.lng));
				// 闭合
				if (path[0].getLat() !== path[path.length - 1].getLat() || path[0].getLng() !== path[path.length - 1].getLng()) {
					path.push(path[0]);
				}
				return { id: item.id, paths: [path] };
			});
			this.fenceDisplayLayer.setGeometries(geometries);
		},

		removeBufferShape(index) {
			this.fenceBuffer.splice(index, 1);
			this.refreshFenceDisplay();
		},

		confirmFence() {
			if (this.fenceBuffer.length !== 1) {
				this.$message.warning('请确保最终只保留一个围栏');
				return;
			}
			this.dataForm.fencePolygons = [this.fenceBuffer[0].points];
			this.fenceVisible = false;
		},

		// 将 GeometryEditor 返回的几何统一转换为点数组
		_extractPoints(toolId, geometry) {
			if (!geometry) return []

			// 通用:从 geometry 中尝试解析点数组(paths 或 path,一维或二维)
			let pointsArray = []
			if (Array.isArray(geometry.paths) && geometry.paths.length) {
				const first = geometry.paths[0]
				pointsArray = Array.isArray(first) ? first : geometry.paths
			} else if (Array.isArray(geometry.path) && geometry.path.length) {
				const first = geometry.path[0]
				pointsArray = Array.isArray(first) ? first : geometry.path
			}

			// 多边形 / 矩形 / 椭圆:统一按点数组处理
			if (['polygon', 'rectangle', 'ellipse'].includes(toolId)) {
				if (!Array.isArray(pointsArray) || !pointsArray.length) return []
				return pointsArray.map(p => ({
					lng: typeof p.getLng === 'function' ? p.getLng() : p.lng,
					lat: typeof p.getLat === 'function' ? p.getLat() : p.lat
				}))
			}

			// 圆形:用中心 + 半径近似成 36 边多边形
			if (toolId === 'circle' && geometry.center && geometry.radius) {
				const center = geometry.center
				const r = geometry.radius
				const cLat = typeof center.getLat === 'function' ? center.getLat() : center.lat
				const cLng = typeof center.getLng === 'function' ? center.getLng() : center.lng
				const R = 6378137
				const latRad = (cLat * Math.PI) / 180
				return Array.from({ length: 36 }, (_, i) => {
					const angle = (2 * Math.PI * i) / 36
					return {
						lat: cLat + (r * Math.cos(angle)) / R * (180 / Math.PI),
						lng: cLng + (r * Math.sin(angle)) / (R * Math.cos(latRad)) * (180 / Math.PI)
					}
				})
			}

			return []
		},

		getShapeIcon(type) {
			const icons = { polygon: 'el-icon-picture', circle: 'el-icon-loading', rectangle: 'el-icon-full-screen', ellipse: 'el-icon-help' };
			return icons[type] || 'el-icon-info';
		},

		getShapeName(type) {
			const names = { polygon: '多边形', circle: '圆形', rectangle: '矩形', ellipse: '椭圆' };
			return names[type] || '图形';
		},

		dataFormSubmit() {
			this.$refs['elForm'].validate((valid) => {
				if (!valid) return;
				const isNew = !this.dataForm.id;
				// 提交前:fencePolygons 若为数组则序列化为 JSON 字符串,与后端约定一致
				const submitData = { ...this.dataForm };
				if (Array.isArray(submitData.fencePolygons)) {
					submitData.fencePolygons = JSON.stringify(submitData.fencePolygons);
				}
				if (Array.isArray(submitData.storeImages)) {
					submitData.storeImages = JSON.stringify(submitData.storeImages);
				}
				if (Array.isArray(submitData.storeTags)) {
					submitData.storeTags = JSON.stringify(submitData.storeTags);
				}
				request({
					url: isNew ? '/api/Extend/LqMdxx' : `/api/Extend/LqMdxx/${this.dataForm.id}`,
					method: isNew ? 'POST' : 'PUT',
					data: submitData
				}).then((res) => {
					this.$message({
						message: res.msg,
						type: 'success',
						duration: 1000,
						onClose: () => {
							this.visible = false;
							this.$emit('refresh', true);
						}
					})
				})
			})
		}
	}
}
</script>

<style lang="scss" scoped>
.fence-status-bar {
	display: flex;
	align-items: center;
	flex-wrap: wrap;
	column-gap: 10px;
	row-gap: 8px;
	padding: 5px 0;

	.fence-action-btn {
		margin-left: 0;
		min-height: 30px;
		padding: 0 14px;
		font-weight: 500;
		transition: background-color 0.2s, border-color 0.2s, box-shadow 0.2s, color 0.2s;

		&:hover,
		&:focus {
			background-color: #66b1ff;
			border-color: #66b1ff;
		}

		&:active {
			background-color: #3a8ee6;
			border-color: #3a8ee6;
			box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.12);
		}

		&.is-disabled {
			opacity: 0.75;
		}
	}

	.hint-text {
		font-size: 12px;
		color: #f56c6c;
		margin-left: 0;
	}
}

.store-tags-editor {
	display: flex;
	flex-direction: column;
	align-items: stretch;
	gap: 10px;

	.store-tags-list {
		display: flex;
		flex-wrap: wrap;
		align-items: center;
		gap: 8px;
		min-height: 32px;
	}

	.store-tags-empty {
		font-size: 12px;
		color: #909399;
	}

	.store-tags-action-row {
		display: flex;
		align-items: center;
		gap: 8px;
	}

	.input-new-tag {
		width: 220px;
		max-width: 100%;
	}

	.button-new-tag {
		padding: 0 12px;
	}

	.tag-action-btn {
		min-height: 32px;
		padding: 0 14px;
		font-weight: 500;
		color: #409eff;
		border-color: #b3d8ff;
		background-color: #f3f9ff;
		transition: color 0.2s, border-color 0.2s, background-color 0.2s, box-shadow 0.2s;

		&:hover,
		&:focus {
			color: #409eff;
			border-color: #409eff;
			background-color: #eaf3ff;
			box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.12);
		}

		&:active {
			color: #fff;
			border-color: #3a8ee6;
			background-color: #3a8ee6;
			box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.12);
		}
	}
}

@media (max-width: 768px) {
	.fence-status-bar {
		align-items: flex-start;

		.fence-action-btn {
			width: 100%;
		}
	}

	.store-tags-editor {
		.input-new-tag,
		.tag-action-btn {
			width: 100%;
		}

		.store-tags-action-row {
			align-items: stretch;
		}
	}
}

.map-dialog {
	::v-deep .el-dialog__body {
		padding: 10px 20px;
	}
}

.map-container-wrapper {
	.map-header-bar {
		display: flex;
		justify-content: space-between;
		font-size: 13px;
		color: #606266;
		margin-bottom: 8px;

		.coordinate-info {
			color: #409eff;
			font-weight: bold;
		}
	}

	.location-search-bar {
		margin-bottom: 10px;

		.search-input {
			width: 100%;
		}
	}
}

.map-canvas {
	width: 100%;
	height: 450px;
	border-radius: 4px;
	border: 1px solid #dcdfe6;
}

.fence-editor-layout {
	display: flex;
	height: 500px;
	gap: 15px;

	.map-side-panel {
		width: 220px;
		border: 1px solid #ebeef5;
		border-radius: 4px;
		display: flex;
		flex-direction: column;

		.panel-header {
			padding: 10px;
			background: #f5f7fa;
			border-bottom: 1px solid #ebeef5;
			font-weight: bold;
			font-size: 14px;
		}

		.shape-list {
			flex: 1;
			overflow-y: auto;
			padding: 10px;

			.shape-item {
				display: flex;
				align-items: center;
				padding: 8px;
				margin-bottom: 8px;
				background: #fdfdfd;
				border: 1px solid #f2f2f2;
				border-radius: 4px;

				i {
					margin-right: 8px;
					color: #409eff;
				}

				.shape-name {
					flex: 1;
					font-size: 12px;
				}

				.delete-btn {
					color: #f56c6c;
					padding: 0;
				}
			}

			.empty-text {
				text-align: center;
				color: #909399;
				font-size: 12px;
				margin-top: 50px;
			}
		}

		.panel-footer {
			padding: 10px;
			border-top: 1px solid #ebeef5;

			.warning-text {
				font-size: 11px;
				color: #e6a23c;
				margin: 0;
			}
		}
	}

	.map-main-area {
		flex: 1;
		display: flex;
		flex-direction: column;

		.map-toolbar {
			display: flex;
			padding: 0 0 10px 0;
			gap: 8px;

			.tool-btn {
				display: flex;
				align-items: center;
				padding: 5px 12px;
				border: 1px solid #dcdfe6;
				border-radius: 4px;
				cursor: pointer;
				background: #fff;
				transition: all 0.2s;

				&:hover {
					border-color: #409eff;
					color: #409eff;
				}

				&.active {
					background: #ecf5ff;
					border-color: #409eff;
					color: #409eff;
				}

				.tool-icon {
					width: 16px;
					height: 16px;
					margin-right: 6px;
					background-size: cover;
				}

				.tool-label {
					font-size: 12px;
				}
			}

			.tool-icon--polygon {
				background-image: url('https://mapapi.qq.com/web/lbs/javascriptGL/demo/img/polygon.png');
			}

			.tool-icon--circle {
				background-image: url('https://mapapi.qq.com/web/lbs/javascriptGL/demo/img/circle.png');
			}

			.tool-icon--rectangle {
				background-image: url('https://mapapi.qq.com/web/lbs/javascriptGL/demo/img/rectangle.png');
			}

			.tool-icon--ellipse {
				background-image: url('https://mapapi.qq.com/web/lbs/javascriptGL/demo/img/ellipse.png');
			}
		}
	}
}

.footer-hint {
	color: #f56c6c;
	font-size: 12px;
	margin-right: 20px;
	display: inline-block;
}
</style>