index.vue 36 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076
  1. <template>
  2. <div class="p-2">
  3. <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
  4. <div v-show="showSearch" class="mb-[10px]">
  5. <el-card shadow="hover">
  6. <el-form ref="queryFormRef" :model="queryParams" :inline="true">
  7. <el-form-item label="门店名称" prop="name">
  8. <el-input v-model="queryParams.name" placeholder="请输入门店名称" clearable @keyup.enter="handleQuery" />
  9. </el-form-item>
  10. <el-form-item label="详细地址" prop="address">
  11. <el-input v-model="queryParams.address" placeholder="请输入详细地址" clearable @keyup.enter="handleQuery" />
  12. </el-form-item>
  13. <el-form-item>
  14. <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
  15. <el-button icon="Refresh" @click="resetQuery">重置</el-button>
  16. </el-form-item>
  17. </el-form>
  18. </el-card>
  19. </div>
  20. </transition>
  21. <el-card shadow="never">
  22. <template #header>
  23. <el-row :gutter="10" class="mb8">
  24. <el-col :span="1.5">
  25. <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['physical:store:add']">新增</el-button>
  26. </el-col>
  27. <el-col :span="1.5">
  28. <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['physical:store:edit']"
  29. >修改</el-button
  30. >
  31. </el-col>
  32. <el-col :span="1.5">
  33. <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['physical:store:remove']"
  34. >删除</el-button
  35. >
  36. </el-col>
  37. <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
  38. </el-row>
  39. </template>
  40. <el-table v-loading="loading" border :data="storeList" @selection-change="handleSelectionChange">
  41. <el-table-column type="selection" width="55" align="center" />
  42. <el-table-column label="门店 ID" align="center" prop="id" v-if="true" />
  43. <el-table-column label="主页图标" align="center" prop="iconUrl" width="120">
  44. <template #default="scope">
  45. <img v-if="scope.row.iconUrl" :src="scope.row.iconUrl" alt="" style="width: 40px; height: 40px; object-fit: cover; border-radius: 4px" />
  46. <span v-else>无</span>
  47. </template>
  48. </el-table-column>
  49. <el-table-column label="昵称" align="center" prop="name" />
  50. <el-table-column label="服务类型" align="center" prop="storeTypeName" />
  51. <el-table-column label="详细地址" align="center" prop="address" />
  52. <el-table-column label="是否授权" align="center" prop="isAuthorization">
  53. <template #default="scope">
  54. <el-tag :type="scope.row.isAuthorization ? 'success' : 'info'">
  55. {{ scope.row.isAuthorization ? '已授权' : '未授权' }}
  56. </el-tag>
  57. </template>
  58. </el-table-column>
  59. <el-table-column label="兑换开始时间" align="center" prop="businessStartTime" width="180">
  60. <template #default="scope">
  61. <span>{{ parseTime(scope.row.businessStartTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
  62. </template>
  63. </el-table-column>
  64. <el-table-column label="兑换结束时间" align="center" prop="businessEndTime" width="180">
  65. <template #default="scope">
  66. <span>{{ parseTime(scope.row.businessEndTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
  67. </template>
  68. </el-table-column>
  69. <el-table-column label="状态" align="center" prop="status">
  70. <template #default="scope">
  71. <el-tag :type="scope.row.status === 1 ? 'success' : 'info'">
  72. {{ scope.row.status === 1 ? '开业中' : '闭店中' }}
  73. </el-tag>
  74. </template>
  75. </el-table-column>
  76. <el-table-column label="创建时间" align="center" prop="createdAt" width="180"></el-table-column>
  77. <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
  78. <template #default="scope">
  79. <el-tooltip content="修改" placement="top">
  80. <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['physical:store:edit']"></el-button>
  81. </el-tooltip>
  82. <el-tooltip content="删除" placement="top">
  83. <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['physical:store:remove']"></el-button>
  84. </el-tooltip>
  85. <el-tooltip :content="scope.row.isAuthorization ? '关闭授权' : '点击授权'" placement="top">
  86. <el-button
  87. link
  88. :type="scope.row.isAuthorization ? 'warning' : 'success'"
  89. @click="handleAuthorization(scope.row)"
  90. style="text-decoration: underline"
  91. >
  92. {{ scope.row.isAuthorization ? '关闭授权' : '点击授权' }}
  93. </el-button>
  94. </el-tooltip>
  95. </template>
  96. </el-table-column>
  97. </el-table>
  98. <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
  99. </el-card>
  100. <!-- 添加或修改门店信息对话框 -->
  101. <el-dialog :title="dialog.title" v-model="dialog.visible" width="600px" append-to-body>
  102. <el-form ref="storeFormRef" :model="form" :rules="rules" label-width="120px">
  103. <el-form-item label="昵称" prop="name">
  104. <el-input v-model="form.name" placeholder="请输入昵称" />
  105. </el-form-item>
  106. <el-form-item label="详细地址" prop="address">
  107. <el-input v-model="form.address" type="textarea" placeholder="请输入内容" />
  108. <el-button type="primary" @click="openMapSelector" style="margin-top: 8px">选择地图位置</el-button>
  109. </el-form-item>
  110. <el-form-item label="联系方式" prop="phone">
  111. <el-input v-model="form.phone" type="textarea" placeholder="请输入内容" />
  112. </el-form-item>
  113. <el-form-item label="服务类型" prop="storeTypeId">
  114. <el-select v-model="form.storeTypeId" placeholder="请选择服务类型" style="width: 100%">
  115. <el-option v-for="item in tagOptions" :key="item.id" :label="item.serviceName" :value="item.id" />
  116. </el-select>
  117. </el-form-item>
  118. <el-form-item label="主页图标" prop="iconUrl">
  119. <div class="upload-container">
  120. <el-upload
  121. class="upload-icon"
  122. action="#"
  123. :on-change="handleIconChange"
  124. :on-remove="handleIconRemove"
  125. :file-list="fileList"
  126. :auto-upload="false"
  127. :limit="1"
  128. accept="image/*"
  129. >
  130. <template #trigger>
  131. <el-button type="primary">点击选择图标</el-button>
  132. </template>
  133. <template #default>
  134. <div class="preview-area" @click="handlePreviewClick">
  135. <img
  136. v-if="iconPreviewUrl || form.iconUrl"
  137. :src="iconPreviewUrl || form.iconUrl"
  138. alt="预览图"
  139. style="max-width: 100px; max-height: 100px; margin-top: 10px; cursor: pointer"
  140. />
  141. <div v-else style="margin-top: 10px; color: #999">无</div>
  142. </div>
  143. </template>
  144. <template #tip>
  145. <div class="el-upload__tip">
  146. <span v-if="fileList.length > 0">当前已选文件:{{ fileList[0].name }}</span>
  147. </div>
  148. </template>
  149. </el-upload>
  150. </div>
  151. </el-form-item>
  152. <el-form-item label="主标题" prop="mainTitle">
  153. <el-input v-model="form.mainTitle" type="textarea" placeholder="请输入内容" />
  154. </el-form-item>
  155. <el-form-item label="门店简介" prop="storeDescription">
  156. <el-input v-model="form.storeDescription" type="textarea" placeholder="请输入内容" />
  157. </el-form-item>
  158. <el-form-item label="门店appId" prop="previewDurationSeconds">
  159. <div>
  160. <el-input v-model="form.storeAppIds" placeholder="请输入内容" style="width: 100%" />
  161. <div style="margin-top: 4px; font-size: 12px; color: #999">
  162. <el-icon style="vertical-align: middle"><InfoFilled /></el-icon>
  163. 温馨提示:多个 appId 请用英文逗号分隔,appId为用户ID
  164. </div>
  165. </div>
  166. </el-form-item>
  167. <el-form-item label="门店宣传图" prop="storePromotionImageOsId">
  168. <imageUpload v-model="form.storePromotionImageOsId" :limit="5" />
  169. </el-form-item>
  170. <el-form-item label="开始兑换时间" prop="businessStartTime">
  171. <el-date-picker
  172. clearable
  173. v-model="form.businessStartTime"
  174. type="datetime"
  175. value-format="YYYY-MM-DD HH:mm:ss"
  176. placeholder="请选择开始兑换时间"
  177. >
  178. </el-date-picker>
  179. </el-form-item>
  180. <el-form-item label="结束兑换时间" prop="businessEndTime">
  181. <el-date-picker
  182. clearable
  183. v-model="form.businessEndTime"
  184. type="datetime"
  185. value-format="YYYY-MM-DD HH:mm:ss"
  186. placeholder="请选择结束兑换时间"
  187. >
  188. </el-date-picker>
  189. </el-form-item>
  190. <el-form-item label="状态" prop="status">
  191. <el-radio-group v-model="form.status">
  192. <el-radio :label="1">开业中</el-radio>
  193. <el-radio :label="2">闭店中</el-radio>
  194. </el-radio-group>
  195. </el-form-item>
  196. </el-form>
  197. <template #footer>
  198. <div class="dialog-footer">
  199. <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
  200. <el-button @click="cancel">取 消</el-button>
  201. </div>
  202. </template>
  203. </el-dialog>
  204. <!-- 地图选择对话框 -->
  205. <el-dialog title="选择地理位置" v-model="mapDialogVisible" width="800px" append-to-body @close="handleMapClose">
  206. <div style="height: 500px; display: flex; flex-direction: column">
  207. <div style="margin-bottom: 10px; padding: 10px; background: #f5f7fa; border-radius: 4px; font-size: 12px">
  208. <el-icon style="vertical-align: middle; margin-right: 5px"><InfoFilled /></el-icon>
  209. 操作提示:拖动地图找到目标位置 → 点击地图标记位置 → 点击确认选择保存坐标
  210. </div>
  211. <div style="flex: 1">
  212. <div id="amapContainer" style="width: 100%; height: 100%"></div>
  213. </div>
  214. <div style="margin-top: 10px; display: flex; gap: 10px">
  215. <el-input v-model="selectedCoordinate" placeholder="选中的坐标" readonly style="flex: 1">
  216. <template #prepend>坐标:</template>
  217. </el-input>
  218. <el-button type="primary" @click="confirmMapSelection">确认选择</el-button>
  219. </div>
  220. </div>
  221. <template #footer>
  222. <div class="dialog-footer">
  223. <el-button @click="cancelMapSelection">取 消</el-button>
  224. </div>
  225. </template>
  226. </el-dialog>
  227. <!-- 图片预览弹窗 -->
  228. <el-dialog v-model="dialogVisible" title="图片预览" width="50%">
  229. <img :src="previewSrc || iconPreviewUrl || form.iconUrl" alt="预览图片" style="max-width: 100%; max-height: 80vh" />
  230. </el-dialog>
  231. </div>
  232. </template>
  233. <script setup name="Store" lang="ts">
  234. import { listStore, getStore, delStore, addStore, updateStore } from '@/api/system/physical/store';
  235. import { StoreVO, StoreQuery, StoreForm } from '@/api/system/physical/store/types';
  236. import { uploadTournament } from '@/api/system/business/tournaments';
  237. import { selectAllPhysicalTagsSelList } from '@/api/system/physical/tag';
  238. import { TagVO } from '@/api/system/physical/tag/types';
  239. import { ElMessage } from 'element-plus';
  240. import { InfoFilled } from '@element-plus/icons-vue';
  241. import { listByIds } from '@/api/system/oss';
  242. const { proxy } = getCurrentInstance() as ComponentInternalInstance;
  243. let mapInstance: any = null;
  244. let markerInstance: any = null;
  245. let mapApiLoaded = false;
  246. const storeList = ref<StoreVO[]>([]);
  247. const buttonLoading = ref(false);
  248. const loading = ref(true);
  249. const showSearch = ref(true);
  250. const ids = ref<Array<string | number>>([]);
  251. const single = ref(true);
  252. const multiple = ref(true);
  253. const total = ref(0);
  254. const queryFormRef = ref<ElFormInstance>();
  255. const storeFormRef = ref<ElFormInstance>();
  256. const dialog = reactive<DialogOption>({
  257. visible: false,
  258. title: ''
  259. });
  260. const initFormData: StoreForm = {
  261. id: undefined,
  262. storeCode: undefined,
  263. name: undefined,
  264. storeTypeId: undefined,
  265. zoneId: undefined,
  266. address: undefined,
  267. iconUrl: undefined,
  268. backgroundUrl: undefined,
  269. businessStartTime: undefined,
  270. businessEndTime: undefined,
  271. status: 1,
  272. phone: '',
  273. customTags: [],
  274. createdAt: undefined,
  275. updatedAt: undefined,
  276. deletedAt: undefined,
  277. latitude: undefined,
  278. longitude: undefined,
  279. storePromotionImageOsId: []
  280. };
  281. const data = reactive<PageData<StoreForm, StoreQuery>>({
  282. form: { ...initFormData },
  283. queryParams: {
  284. pageNum: 1,
  285. pageSize: 10,
  286. storeCode: undefined,
  287. name: undefined,
  288. storeTypeId: undefined,
  289. zoneId: undefined,
  290. address: undefined,
  291. iconUrl: undefined,
  292. backgroundUrl: undefined,
  293. businessStartTime: undefined,
  294. businessEndTime: undefined,
  295. status: undefined,
  296. createdAt: undefined,
  297. updatedAt: undefined,
  298. deletedAt: undefined,
  299. params: {}
  300. },
  301. rules: {
  302. id: [{ required: true, message: '主键 ID 不能为空', trigger: 'blur' }],
  303. name: [{ required: true, message: '门店名称,最多 20 字不能为空', trigger: 'blur' }],
  304. storeTypeId: [{ required: true, message: '门店类型 ID 不能为空', trigger: 'blur' }],
  305. address: [{ required: true, message: '详细地址不能为空', trigger: 'blur' }],
  306. status: [{ required: true, message: '状态不能为空', trigger: 'change' }],
  307. mainTitle: [{ required: true, message: '主标题不能为空', trigger: 'change' }],
  308. storeDescription: [{ required: true, message: '门店简介不能为空', trigger: 'change' }],
  309. phone: [
  310. { required: true, message: '联系方式不能为空', trigger: 'blur' },
  311. { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  312. ],
  313. businessStartTime: [
  314. { required: true, message: '营业开始时间不能为空', trigger: 'blur' },
  315. {
  316. validator: (rule, value, callback) => {
  317. if (value && form.value.businessEndTime && value > form.value.businessEndTime) {
  318. callback(new Error('开始时间不能大于结束时间'));
  319. } else {
  320. callback();
  321. }
  322. },
  323. trigger: 'change'
  324. }
  325. ],
  326. businessEndTime: [
  327. { required: true, message: '营业结束时间不能为空', trigger: 'blur' },
  328. {
  329. validator: (rule, value, callback) => {
  330. if (value && form.value.businessStartTime && value < form.value.businessStartTime) {
  331. callback(new Error('结束时间不能小于开始时间'));
  332. } else {
  333. callback();
  334. }
  335. },
  336. trigger: 'change'
  337. }
  338. ],
  339. storePromotionImageOsId: [
  340. {
  341. validator: (rule, value, callback) => {
  342. if (!value || value.length === 0) {
  343. callback(new Error('请至少上传一张门店宣传图'));
  344. } else {
  345. callback();
  346. }
  347. },
  348. trigger: 'change'
  349. }
  350. ]
  351. }
  352. });
  353. const { queryParams, form, rules } = toRefs(data);
  354. const getList = async () => {
  355. loading.value = true;
  356. const res = await listStore(queryParams.value);
  357. storeList.value = res.rows;
  358. total.value = res.total;
  359. loading.value = false;
  360. };
  361. const cancel = () => {
  362. reset();
  363. dialog.visible = false;
  364. };
  365. const reset = () => {
  366. form.value = { ...initFormData };
  367. storeFormRef.value?.resetFields();
  368. customTags.value = [];
  369. fileList.value = [];
  370. fileList2.value = [];
  371. iconPreviewUrl.value = '';
  372. iconPreviewUrl2.value = '';
  373. form.value.iconUrl = '';
  374. form.value.backgroundUrl = '';
  375. };
  376. const handleQuery = () => {
  377. queryParams.value.pageNum = 1;
  378. getList();
  379. };
  380. const resetQuery = () => {
  381. queryFormRef.value?.resetFields();
  382. handleQuery();
  383. };
  384. const handleSelectionChange = (selection: StoreVO[]) => {
  385. ids.value = selection.map((item) => item.id);
  386. single.value = selection.length != 1;
  387. multiple.value = !selection.length;
  388. };
  389. const handleAdd = () => {
  390. reset();
  391. dialog.visible = true;
  392. dialog.title = '添加门店信息';
  393. fileList.value = [];
  394. fileList2.value = [];
  395. iconPreviewUrl.value = '';
  396. iconPreviewUrl2.value = '';
  397. form.value.iconUrl = '';
  398. form.value.backgroundUrl = '';
  399. customTags.value = [];
  400. };
  401. const handleUpdate = async (row?: StoreVO) => {
  402. reset();
  403. const _id = row?.id || ids.value[0];
  404. const res = await getStore(_id);
  405. Object.assign(form.value, res.data);
  406. if (form.value.iconUrl) {
  407. iconPreviewUrl.value = form.value.iconUrl;
  408. }
  409. if (form.value.backgroundUrl) {
  410. iconPreviewUrl2.value = form.value.backgroundUrl;
  411. }
  412. if (res.data.customTags && Array.isArray(res.data.customTags)) {
  413. customTags.value = [...res.data.customTags];
  414. } else {
  415. customTags.value = [];
  416. }
  417. const processImages = async (images: any[]) => {
  418. const imageUrls = await Promise.all(
  419. images.map(async (image) => {
  420. try {
  421. const res = await getIds(image.osId);
  422. const firstItem = Array.isArray(res) ? res[0] : res.data?.[0] || res[0];
  423. return {
  424. url: firstItem?.url || firstItem?.picUrl,
  425. ossId: image.osId,
  426. name: image.osId
  427. };
  428. } catch (error) {
  429. console.error('获取图片URL失败:', error);
  430. return { url: '', ossId: '' };
  431. }
  432. })
  433. );
  434. return imageUrls
  435. .filter((item) => item.url !== '')
  436. .map((item) => item.ossId)
  437. .join(',');
  438. };
  439. if (res.data.storePromotionImage && Array.isArray(res.data.storePromotionImage)) {
  440. form.value.storePromotionImageOsId = await processImages(res.data.storePromotionImage);
  441. } else {
  442. form.value.storePromotionImageOsId = [];
  443. }
  444. dialog.visible = true;
  445. dialog.title = '修改门店信息';
  446. };
  447. const getIds = async (ids: string | number) => {
  448. return await listByIds(ids);
  449. };
  450. const submitForm = () => {
  451. storeFormRef.value?.validate(async (valid: boolean) => {
  452. if (valid) {
  453. buttonLoading.value = true;
  454. const processOsIds = async (osIdString: any, imageType: string) => {
  455. if (!osIdString) return [];
  456. const osIds = osIdString
  457. .toString()
  458. .split(',')
  459. .map((id: string) => id.trim());
  460. const imageList = [];
  461. for (const osId of osIds) {
  462. const res = await listByIds(osId);
  463. const firstItem = Array.isArray(res) ? res[0] : res.data?.[0] || res[0];
  464. const picUrl = firstItem?.url || firstItem?.picUrl;
  465. imageList.push({ osId, imageUrl: picUrl, imageType });
  466. }
  467. return imageList;
  468. };
  469. form.value.storePromotionImage = await processOsIds(form.value.storePromotionImageOsId, 'STORE');
  470. if (form.value.id) {
  471. await updateStore(form.value).finally(() => (buttonLoading.value = false));
  472. } else {
  473. await addStore(form.value).finally(() => (buttonLoading.value = false));
  474. }
  475. proxy?.$modal.msgSuccess('操作成功');
  476. dialog.visible = false;
  477. await getList();
  478. }
  479. });
  480. };
  481. const handleDelete = async (row?: StoreVO) => {
  482. const _ids = row?.id || ids.value;
  483. await proxy?.$modal.confirm('是否确认删除门店信息编号为"' + _ids + '"的数据项?');
  484. await delStore(_ids);
  485. proxy?.$modal.msgSuccess('删除成功');
  486. await getList();
  487. };
  488. onMounted(() => {
  489. getList();
  490. loadTagOptions();
  491. });
  492. const iconPreviewUrl = ref('');
  493. const iconPreviewUrl2 = ref('');
  494. const fileList = ref([]);
  495. const fileList2 = ref([]);
  496. const dialogVisible = ref(false);
  497. const dialogVisible2 = ref(false);
  498. const previewSrc = ref('');
  499. const previewSrc2 = ref('');
  500. const handleIconChange = async (file) => {
  501. const index = fileList.value.findIndex((f) => f.uid === file.uid);
  502. fileList.value = [];
  503. if (file.raw) {
  504. iconPreviewUrl.value = URL.createObjectURL(file.raw);
  505. }
  506. if (index === -1) {
  507. fileList.value.push(file);
  508. }
  509. try {
  510. const rawFile = file.raw;
  511. const res = await uploadTournament(rawFile);
  512. if (res.code === 200) {
  513. fileList.value[index] = {
  514. ...file,
  515. status: 'success',
  516. response: res.data.url
  517. };
  518. form.value.iconUrl = fileList.value[index].response;
  519. iconPreviewUrl.value = fileList.value[index].response;
  520. ElMessage.success('上传成功');
  521. } else {
  522. throw new Error(res.msg);
  523. }
  524. } catch (error) {
  525. fileList.value[index] = {
  526. ...file,
  527. status: 'fail',
  528. error: '上传失败'
  529. };
  530. ElMessage.error('上传失败,请重试');
  531. }
  532. };
  533. const handleIconRemove = (file, updatedFileList) => {
  534. fileList.value = updatedFileList;
  535. iconPreviewUrl.value = '';
  536. form.value.iconUrl = '';
  537. };
  538. const handlePreviewClick = () => {
  539. const currentSrc = iconPreviewUrl.value || form.value.iconUrl;
  540. if (currentSrc) {
  541. dialogVisible.value = true;
  542. }
  543. };
  544. const handleIconChange2 = async (file) => {
  545. const index = fileList2.value.findIndex((f) => f.uid === file.uid);
  546. fileList2.value = [];
  547. if (file.raw) {
  548. iconPreviewUrl2.value = URL.createObjectURL(file.raw);
  549. }
  550. if (index === -1) {
  551. fileList2.value.push(file);
  552. }
  553. try {
  554. const rawFile = file.raw;
  555. const res = await uploadTournament(rawFile);
  556. if (res.code === 200) {
  557. fileList2.value[index] = {
  558. ...file,
  559. status: 'success',
  560. response: res.data.url
  561. };
  562. form.value.backgroundUrl = fileList2.value[index].response;
  563. iconPreviewUrl2.value = fileList2.value[index].response;
  564. ElMessage.success('上传成功');
  565. } else {
  566. throw new Error(res.msg);
  567. }
  568. } catch (error) {
  569. fileList2.value[index] = {
  570. ...file,
  571. status: 'fail',
  572. error: '上传失败'
  573. };
  574. ElMessage.error('上传失败,请重试');
  575. }
  576. };
  577. const handleIconRemove2 = (file, updatedFileList) => {
  578. fileList2.value = updatedFileList;
  579. iconPreviewUrl2.value = '';
  580. form.value.backgroundUrl = '';
  581. };
  582. const handlePreviewClick2 = () => {
  583. const currentSrc = iconPreviewUrl2.value || form.value.backgroundUrl;
  584. if (currentSrc) {
  585. dialogVisible2.value = true;
  586. }
  587. };
  588. const tagOptions = ref<TagVO[]>([]);
  589. const loadTagOptions = async () => {
  590. try {
  591. const res = await selectAllPhysicalTagsSelList();
  592. if (res.code === 200) {
  593. tagOptions.value = res.data;
  594. } else {
  595. ElMessage.error('加载门店类型失败:' + res.msg);
  596. }
  597. } catch (error) {
  598. console.error('请求出错:', error);
  599. ElMessage.error('请求失败,请检查网络');
  600. }
  601. };
  602. const customTags = ref<string[]>([]);
  603. const addTagDialogVisible = ref(false);
  604. const newTagName = ref('');
  605. const confirmAddTag = () => {
  606. if (!newTagName.value.trim()) {
  607. ElMessage.warning('标签名称不能为空');
  608. return;
  609. }
  610. if (customTags.value.length >= 3) {
  611. ElMessage.warning('最多只能添加 3 个标签');
  612. return;
  613. }
  614. if (customTags.value.includes(newTagName.value)) {
  615. ElMessage.warning('该标签已存在');
  616. return;
  617. }
  618. customTags.value.push(newTagName.value);
  619. newTagName.value = '';
  620. addTagDialogVisible.value = false;
  621. };
  622. const handleTagClose = (index: number) => {
  623. customTags.value.splice(index, 1);
  624. };
  625. watch(
  626. customTags,
  627. () => {
  628. if (Array.isArray(customTags.value)) {
  629. form.value.customTags = customTags.value;
  630. }
  631. },
  632. { deep: true }
  633. );
  634. const openAddTagDialog = () => {
  635. newTagName.value = '';
  636. addTagDialogVisible.value = true;
  637. };
  638. // 地图相关变量
  639. const mapDialogVisible = ref(false);
  640. const selectedCoordinate = ref('');
  641. // 动态加载高德地图API
  642. const loadAmapApi = (): Promise<void> => {
  643. return new Promise((resolve, reject) => {
  644. if (mapApiLoaded || (window as any).AMap) {
  645. mapApiLoaded = true;
  646. resolve();
  647. return;
  648. }
  649. const script = document.createElement('script');
  650. script.type = 'text/javascript';
  651. script.src = 'https://webapi.amap.com/maps?v=1.4.15&key=7ffb6b303bfa384026e2124df21248c0a';
  652. script.onload = () => {
  653. mapApiLoaded = true;
  654. resolve();
  655. };
  656. script.onerror = () => {
  657. reject(new Error('高德地图API加载失败'));
  658. };
  659. document.head.appendChild(script);
  660. });
  661. };
  662. // 初始化高德地图
  663. const initMap = async () => {
  664. try {
  665. await loadAmapApi();
  666. const AMap = (window as any).AMap;
  667. if (mapInstance) {
  668. mapInstance.destroy();
  669. }
  670. // 优先使用表单中已有的坐标
  671. let initCenter: number[] = [];
  672. let markerPos: number[] = [];
  673. let hasCoordinates = false;
  674. if (form.value.longitude !== undefined && form.value.latitude !== undefined) {
  675. const lng = Number(form.value.longitude);
  676. const lat = Number(form.value.latitude);
  677. if (!isNaN(lng) && !isNaN(lat)) {
  678. initCenter = [lng, lat];
  679. markerPos = [lng, lat];
  680. hasCoordinates = true;
  681. }
  682. }
  683. // 如果没有已有坐标,尝试获取浏览器定位
  684. if (!hasCoordinates) {
  685. try {
  686. const position = await getCurrentBrowserLocation();
  687. // 注意:浏览器原生定位返回的是WGS-84,需要转换为GCJ-02
  688. const gcj02Pos = convertWgs84ToGcj02(position.latitude, position.longitude);
  689. initCenter = [gcj02Pos.lng, gcj02Pos.lat];
  690. markerPos = [gcj02Pos.lng, gcj02Pos.lat];
  691. hasCoordinates = true;
  692. proxy?.$modal.msgSuccess('已自动定位到您当前的位置');
  693. } catch (error) {
  694. console.log('浏览器定位失败,使用默认中心点', error);
  695. // 使用中国中心点作为备选(GCJ-02坐标系)
  696. initCenter = [104.1954, 35.8617];
  697. markerPos = [104.1954, 35.8617];
  698. }
  699. }
  700. mapInstance = new AMap.Map('amapContainer', {
  701. center: initCenter,
  702. zoom: hasCoordinates ? 16 : 5,
  703. resizeEnable: true,
  704. dragEnable: true,
  705. zoomEnable: true
  706. });
  707. markerInstance = new AMap.Marker({
  708. position: markerPos,
  709. title: '门店位置',
  710. icon: new AMap.Icon({
  711. size: new AMap.Size(25, 34),
  712. image: '//webapi.amap.com/theme/v1.3/markers/n/mark_b.png',
  713. imageSize: new AMap.Size(25, 34)
  714. }),
  715. offset: new AMap.Pixel(-12, -34)
  716. });
  717. mapInstance.add(markerInstance);
  718. // 点击地图事件 - 更新坐标并获取地址
  719. mapInstance.on('click', async (e: any) => {
  720. const lng = e.lnglat.getLng();
  721. const lat = e.lnglat.getLat();
  722. markerInstance.setPosition([lng, lat]);
  723. selectedCoordinate.value = `纬度: ${lat.toFixed(6)}, 经度: ${lng.toFixed(6)} (GCJ-02)`;
  724. form.value.latitude = lat;
  725. form.value.longitude = lng;
  726. // 使用 OpenCageData API 获取中文地址(需要将 GCJ-02 转换为 WGS-84)
  727. await setSelectedLocationWithConversion(lat, lng);
  728. });
  729. if (hasCoordinates) {
  730. const lat = Number(form.value.latitude || markerPos[1]);
  731. const lng = Number(form.value.longitude || markerPos[0]);
  732. selectedCoordinate.value = `纬度: ${lat.toFixed(6)}, 经度: ${lng.toFixed(6)} (GCJ-02)`;
  733. // 如果编辑模式且已有地址,不需要重新获取
  734. if (!form.value.address) {
  735. // 如果是新增模式或地址为空,尝试获取地址
  736. await setSelectedLocationWithConversion(lat, lng);
  737. }
  738. }
  739. } catch (error) {
  740. console.error('地图初始化失败:', error);
  741. proxy?.$modal.msgError('地图加载失败');
  742. }
  743. };
  744. /**
  745. * 使用 OpenCageData API 获取地址(GCJ-02 → WGS-84 转换)
  746. */
  747. const setSelectedLocationWithConversion = async (gcjLat: number, gcjLon: number) => {
  748. const coordsText = `纬度:${gcjLat.toFixed(6)}, 经度:${gcjLon.toFixed(6)}`;
  749. try {
  750. // 关键步骤:将 GCJ-02 转换为 WGS-84
  751. const wgs84Coords = convertGcj02ToWgs84(gcjLat, gcjLon);
  752. console.log('坐标转换:', {
  753. '原始GCJ-02': `${gcjLat}, ${gcjLon}`,
  754. '转换WGS-84': `${wgs84Coords.lat}, ${wgs84Coords.lng}`
  755. });
  756. // 使用 WGS-84 坐标调用 OpenCageData API
  757. const response = await fetch(
  758. `https://api.opencagedata.com/geocode/v1/json?q=${wgs84Coords.lat}+${wgs84Coords.lng}&key=82827937f9614a6eb17c772efa63d75d&language=zh&no_annotations=1`
  759. );
  760. if (response.ok) {
  761. const data = await response.json();
  762. if (data && data.results && data.results.length > 0) {
  763. const address = data.results[0].formatted;
  764. // 清理地址格式:移除开头的邮编和逗号
  765. const cleanedAddress = cleanChineseAddress(address);
  766. // 将地址填充到表单中(注意:数据库中仍然存储 GCJ-02 坐标)
  767. form.value.address = cleanedAddress;
  768. console.log('详细地址:', cleanedAddress);
  769. proxy?.$modal.msgSuccess(`已获取地址:${cleanedAddress}`);
  770. } else {
  771. form.value.address = coordsText;
  772. proxy?.$modal.msgWarning('未能获取详细地址,请手动输入');
  773. }
  774. } else {
  775. form.value.address = coordsText;
  776. proxy?.$modal.msgWarning('地址解析服务异常,请手动输入');
  777. }
  778. } catch (error) {
  779. console.error('地址解析失败:', error);
  780. form.value.address = coordsText;
  781. proxy?.$modal.msgWarning('地址解析失败,请手动输入');
  782. }
  783. };
  784. /**
  785. * GCJ-02 → WGS-84(前端简易版)
  786. */
  787. const convertGcj02ToWgs84 = (gcjLat: number, gcjLon: number): { lat: number; lng: number } => {
  788. const PI = 3.1415926535897932384626;
  789. const A = 6378245.0;
  790. const EE = 0.00669342162296594323;
  791. const outOfChina = (lat: number, lon: number): boolean => {
  792. return lon < 72.004 || lon > 137.8347 || lat < 0.8293 || lat > 55.8271;
  793. };
  794. const transformLat = (x: number, y: number): number => {
  795. let ret = -100.0 + 2.0 * x + 3.0 * y + 0.2 * y * y + 0.1 * x * y + 0.2 * Math.sqrt(Math.abs(x));
  796. ret += ((20.0 * Math.sin(6.0 * x * PI) + 20.0 * Math.sin(2.0 * x * PI)) * 2.0) / 3.0;
  797. ret += ((20.0 * Math.sin(y * PI) + 40.0 * Math.sin((y / 3.0) * PI)) * 2.0) / 3.0;
  798. ret += ((160.0 * Math.sin((y / 12.0) * PI) + 320.0 * Math.sin((y * PI) / 30.0)) * 2.0) / 3.0;
  799. return ret;
  800. };
  801. const transformLon = (x: number, y: number): number => {
  802. let ret = 300.0 + x + 2.0 * y + 0.1 * x * x + 0.1 * x * y + 0.1 * Math.sqrt(Math.abs(x));
  803. ret += ((20.0 * Math.sin(6.0 * x * PI) + 20.0 * Math.sin(2.0 * x * PI)) * 2.0) / 3.0;
  804. ret += ((20.0 * Math.sin(x * PI) + 40.0 * Math.sin((x / 3.0) * PI)) * 2.0) / 3.0;
  805. ret += ((150.0 * Math.sin((x / 12.0) * PI) + 300.0 * Math.sin((x / 30.0) * PI)) * 2.0) / 3.0;
  806. return ret;
  807. };
  808. if (outOfChina(gcjLat, gcjLon)) {
  809. return { lat: gcjLat, lng: gcjLon };
  810. }
  811. let dLat = transformLat(gcjLon - 105.0, gcjLat - 35.0);
  812. let dLon = transformLon(gcjLon - 105.0, gcjLat - 35.0);
  813. const radLat = (gcjLat / 180.0) * PI;
  814. let magic = Math.sin(radLat);
  815. magic = 1 - EE * magic * magic;
  816. const sqrtMagic = Math.sqrt(magic);
  817. dLat = (dLat * 180.0) / (((A * (1 - EE)) / (magic * sqrtMagic)) * PI);
  818. dLon = (dLon * 180.0) / ((A / sqrtMagic) * Math.cos(radLat) * PI);
  819. return {
  820. lat: gcjLat - dLat, // 注意:这里是减法,与 WGS→GCJ 相反
  821. lng: gcjLon - dLon
  822. };
  823. };
  824. /**
  825. * 清理中文地址格式
  826. */
  827. const cleanChineseAddress = (address: string): string => {
  828. if (!address) return address;
  829. // 移除开头的邮编(如 "410000 湖南省..." → "湖南省...")
  830. let cleaned = address.replace(/^\d{5,}\s*/, '');
  831. // 处理重复的省市名称(如:湖南省长沙市长沙市 → 湖南省长沙市)
  832. cleaned = cleaned.replace(/([\u4e00-\u9fa5]+市)\1/g, '$1');
  833. // 移除多余的逗号、空格
  834. cleaned = cleaned.replace(/[,,\s]+/g, '').replace(/\s+/g, '');
  835. // 移除 "中国" 前缀(OpenCageData 通常会包含)
  836. cleaned = cleaned.replace(/^中国/, '');
  837. return cleaned;
  838. };
  839. // ... existing code ...
  840. // WGS-84转GCJ-02(前端简易版)
  841. const convertWgs84ToGcj02 = (wgsLat: number, wgsLon: number): { lat: number; lng: number } => {
  842. const PI = 3.1415926535897932384626;
  843. const A = 6378245.0;
  844. const EE = 0.00669342162296594323;
  845. const outOfChina = (lat: number, lon: number): boolean => {
  846. return lon < 72.004 || lon > 137.8347 || lat < 0.8293 || lat > 55.8271;
  847. };
  848. const transformLat = (x: number, y: number): number => {
  849. let ret = -100.0 + 2.0 * x + 3.0 * y + 0.2 * y * y + 0.1 * x * y + 0.2 * Math.sqrt(Math.abs(x));
  850. ret += ((20.0 * Math.sin(6.0 * x * PI) + 20.0 * Math.sin(2.0 * x * PI)) * 2.0) / 3.0;
  851. ret += ((20.0 * Math.sin(y * PI) + 40.0 * Math.sin((y / 3.0) * PI)) * 2.0) / 3.0;
  852. ret += ((160.0 * Math.sin((y / 12.0) * PI) + 320.0 * Math.sin((y * PI) / 30.0)) * 2.0) / 3.0;
  853. return ret;
  854. };
  855. const transformLon = (x: number, y: number): number => {
  856. let ret = 300.0 + x + 2.0 * y + 0.1 * x * x + 0.1 * x * y + 0.1 * Math.sqrt(Math.abs(x));
  857. ret += ((20.0 * Math.sin(6.0 * x * PI) + 20.0 * Math.sin(2.0 * x * PI)) * 2.0) / 3.0;
  858. ret += ((20.0 * Math.sin(x * PI) + 40.0 * Math.sin((x / 3.0) * PI)) * 2.0) / 3.0;
  859. ret += ((150.0 * Math.sin((x / 12.0) * PI) + 300.0 * Math.sin((x / 30.0) * PI)) * 2.0) / 3.0;
  860. return ret;
  861. };
  862. if (outOfChina(wgsLat, wgsLon)) {
  863. return { lat: wgsLat, lng: wgsLon };
  864. }
  865. let dLat = transformLat(wgsLon - 105.0, wgsLat - 35.0);
  866. let dLon = transformLon(wgsLon - 105.0, wgsLat - 35.0);
  867. const radLat = (wgsLat / 180.0) * PI;
  868. let magic = Math.sin(radLat);
  869. magic = 1 - EE * magic * magic;
  870. const sqrtMagic = Math.sqrt(magic);
  871. dLat = (dLat * 180.0) / (((A * (1 - EE)) / (magic * sqrtMagic)) * PI);
  872. dLon = (dLon * 180.0) / ((A / sqrtMagic) * Math.cos(radLat) * PI);
  873. return {
  874. lat: wgsLat + dLat,
  875. lng: wgsLon + dLon
  876. };
  877. };
  878. // 获取浏览器定位(Promise封装)
  879. const getCurrentBrowserLocation = (): Promise<{ latitude: number; longitude: number }> => {
  880. return new Promise((resolve, reject) => {
  881. if (!navigator.geolocation) {
  882. reject(new Error('浏览器不支持地理位置'));
  883. return;
  884. }
  885. navigator.geolocation.getCurrentPosition(
  886. (position) => {
  887. resolve({
  888. latitude: position.coords.latitude,
  889. longitude: position.coords.longitude
  890. });
  891. },
  892. (error) => {
  893. reject(error);
  894. },
  895. {
  896. enableHighAccuracy: true,
  897. timeout: 10000,
  898. maximumAge: 0
  899. }
  900. );
  901. });
  902. };
  903. // 打开地图选择器
  904. const openMapSelector = () => {
  905. mapDialogVisible.value = true;
  906. nextTick(() => {
  907. setTimeout(() => {
  908. initMap();
  909. }, 200);
  910. });
  911. };
  912. // 确认地图选择
  913. const confirmMapSelection = () => {
  914. if (form.value.latitude === undefined || form.value.longitude === undefined) {
  915. proxy?.$modal.msgWarning('请先在地图上点击选择位置');
  916. return;
  917. }
  918. proxy?.$modal.msgSuccess('位置选择成功');
  919. mapDialogVisible.value = false;
  920. };
  921. // 取消地图选择
  922. const cancelMapSelection = () => {
  923. mapDialogVisible.value = false;
  924. };
  925. // 关闭地图对话框
  926. const handleMapClose = () => {
  927. if (mapInstance) {
  928. mapInstance.destroy();
  929. mapInstance = null;
  930. markerInstance = null;
  931. }
  932. };
  933. const handleAuthorization = async (row: StoreVO) => {
  934. const action = row.isAuthorization ? '关闭' : '授权';
  935. await proxy?.$modal.confirm(`确认要${action}门店"${row.name}"吗?`);
  936. const updateData: StoreForm = {
  937. ...row,
  938. isAuthorization: !row.isAuthorization,
  939. storePromotionImage: row.storePromotionImage || []
  940. };
  941. await updateStore(updateData);
  942. proxy?.$modal.msgSuccess('授权成功');
  943. await getList();
  944. };
  945. </script>
  946. <style scoped>
  947. .upload-container {
  948. display: flex;
  949. flex-direction: column;
  950. align-items: flex-start;
  951. }
  952. .upload-icon {
  953. margin-bottom: 10px;
  954. }
  955. .preview-area {
  956. display: flex;
  957. flex-direction: column;
  958. align-items: center;
  959. }
  960. .tag-container {
  961. flex-wrap: wrap;
  962. }
  963. </style>