create.vue 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943
  1. <template>
  2. <div class="admin--page-content">
  3. <div class="admin--form">
  4. <form @submit.prevent="handleSubmit">
  5. <!-- ============================
  6. 챌린지 기본 정보
  7. ============================ -->
  8. <table class="admin--form--table">
  9. <colgroup>
  10. <col style="width: 140px;">
  11. <col>
  12. </colgroup>
  13. <tbody>
  14. <tr>
  15. <th><div>챌린지명 <span class="admin--required">*</span></div></th>
  16. <td>
  17. <div class="input--wrap">
  18. <input v-model="formData.name" type="text" class="w--full admin--form-input" placeholder="예: 동해안 왕대구 선상낚시대회" required />
  19. </div>
  20. </td>
  21. </tr>
  22. <tr>
  23. <th><div>참가비 <span class="admin--required">*</span></div></th>
  24. <td>
  25. <div class="input--wrap">
  26. <input
  27. v-model="formData.fee"
  28. type="number"
  29. min="0"
  30. class="admin--form-input w--200"
  31. :placeholder="isFree ? '0 (무료)' : '예: 10000'"
  32. :disabled="isFree"
  33. required
  34. />
  35. <span>원</span>
  36. <label class="admin--checkbox-label">
  37. <input type="checkbox" v-model="isFree" @change="onFreeChange" /> 무료
  38. </label>
  39. </div>
  40. </td>
  41. </tr>
  42. <tr>
  43. <th><div>기간 <span class="admin--required">*</span></div></th>
  44. <td>
  45. <div class="input--wrap">
  46. <DatePicker v-model="startDate" placeholder="📅 YYYY-MM-DD" />
  47. <span class="admin--date-separator">-</span>
  48. <DatePicker v-model="endDate" placeholder="📅 YYYY-MM-DD" />
  49. </div>
  50. </td>
  51. </tr>
  52. <tr>
  53. <th><div>최대 참가자 <span class="admin--required">*</span></div></th>
  54. <td>
  55. <div class="input--wrap">
  56. <input v-model="formData.max_participants" type="number" min="100" max="999999" class="admin--form-input w--120" placeholder="100 ~ 999999" required />
  57. <span>명</span>
  58. </div>
  59. </td>
  60. </tr>
  61. <tr>
  62. <th><div>타이틀 이미지</div></th>
  63. <td>
  64. <div class="input--wrap">
  65. <input
  66. ref="imageInput"
  67. type="file"
  68. accept="image/*"
  69. class="admin--form-file-hidden"
  70. @change="onImageChange"
  71. />
  72. <button type="button" class="admin--btn-small admin--btn-blue" @click="triggerImageInput">
  73. 이미지 선택
  74. </button>
  75. <span v-if="image" class="ml--16">{{ image.file.name }}</span>
  76. </div>
  77. <p class="mt--10">권장 1200x800, JPG/PNG/GIF/WebP, 5MB 이하 (선택 사항)</p>
  78. <div v-if="image" class="onboard--photo-grid mt--10">
  79. <div class="onboard--photo-item">
  80. <img :src="image.preview" alt="미리보기" />
  81. <button type="button" class="onboard--photo-remove" @click="removeImage"></button>
  82. </div>
  83. </div>
  84. </td>
  85. </tr>
  86. <tr>
  87. <th><div>상태 <span class="admin--required">*</span></div></th>
  88. <td>
  89. <div class="input--wrap">
  90. <label class="admin--radio-label">
  91. <input type="radio" v-model="formData.status_YN" value="Y" /> 사용중
  92. </label>
  93. <label class="admin--radio-label ml--16">
  94. <input type="radio" v-model="formData.status_YN" value="N" /> 미사용
  95. </label>
  96. </div>
  97. </td>
  98. </tr>
  99. <tr>
  100. <th><div>상세내용</div></th>
  101. <td>
  102. <ClientOnly>
  103. <SunEditor
  104. v-model="formData.description"
  105. height="400px"
  106. placeholder="챌린지 상세 설명을 입력하세요. (참가 방법ㆍ규칙ㆍ유의사항 등)"
  107. />
  108. </ClientOnly>
  109. </td>
  110. </tr>
  111. </tbody>
  112. </table>
  113. <!-- ============================
  114. 라운드 설정
  115. ============================ -->
  116. <h3 class="admin--table--middle--title">라운드 설정</h3>
  117. <p class="admin--table--middle--desc">
  118. 라운드별로 장소 범위(전체/개별)를 선택하고, 장소마다 아이템을 배정합니다. 최대 5라운드까지 등록할 수 있습니다.
  119. </p>
  120. <div
  121. v-for="(round, rIdx) in rounds"
  122. :key="round._key"
  123. class="admin--round--box--wrap"
  124. :class="{ 'mt--16': rIdx > 0 }"
  125. >
  126. <div class="admin--round--title">
  127. 라운드 {{ round.round_no }}
  128. <span v-if="round.place_mode === 'all'">전체 장소ㆍ아이템 {{ round.items.length }}</span>
  129. <span v-else>개별 장소 {{ round.places.length }}</span>
  130. <!-- 최소 2라운드 이상. 3라운드부터 라운드 삭제 버튼 노출 -->
  131. <button
  132. v-if="rounds.length > 2"
  133. type="button"
  134. class="round--remove--btn"
  135. @click="removeRound(rIdx)"
  136. >
  137. 라운드 삭제
  138. </button>
  139. </div>
  140. <div class="admin--round--box">
  141. <div class="input--wrap mt--16">
  142. <label class="admin--round--radio">
  143. <input
  144. type="radio"
  145. :name="'place_mode_' + round._key"
  146. value="all"
  147. :checked="round.place_mode === 'all'"
  148. @change="changePlaceMode(round, 'all')"
  149. />
  150. 전체 장소에 동일 적용
  151. </label>
  152. <label class="admin--round--radio">
  153. <input
  154. type="radio"
  155. :name="'place_mode_' + round._key"
  156. value="specific"
  157. :checked="round.place_mode === 'specific'"
  158. @change="changePlaceMode(round, 'specific')"
  159. />
  160. 장소별 개별 설정
  161. </label>
  162. </div>
  163. <div class="qual--wrap">
  164. <p class="mt--16 mb--4">진출자 {{ rIdx === 0 ? '인원' : '확률' }}</p>
  165. <div class="input--wrap">
  166. <input
  167. v-model="round.qualified"
  168. type="number"
  169. min="1"
  170. class="admin--form-input w--120"
  171. :placeholder="rIdx === 0 ? '예: 30' : '예: 50'"
  172. required
  173. />
  174. <!-- 1라운드 단위 : 명, 그 외 라운드 단위 : % -->
  175. <span>{{ rIdx === 0 ? '명' : '%' }}</span>
  176. </div>
  177. </div>
  178. <!-- 전체 적용 모드 — 라운드 단위 아이템 -->
  179. <div v-if="round.place_mode === 'all'" class="item--select--wrap">
  180. <div class="item--select--btn--wrap mt--16 mb--4">
  181. <p>배정 아이템ㆍ수량 {{ round.items.length }}</p>
  182. <button type="button" @click="openItemModal(round)">+ 아이템 선택</button>
  183. </div>
  184. <div class="item--selected--wrap">
  185. <div v-for="(it, iIdx) in round.items" :key="it.item_id" class="item--selected">
  186. {{ it.name }}<button type="button" @click="round.items.splice(iIdx, 1)">✕</button>
  187. </div>
  188. </div>
  189. </div>
  190. <!-- 장소별 개별 설정 모드 -->
  191. <template v-else>
  192. <div
  193. v-for="(place, pIdx) in round.places"
  194. :key="place._key"
  195. class="round--place--wrap"
  196. >
  197. <div class="admin--round--title">
  198. 장소 {{ pIdx + 1 }}
  199. <button
  200. type="button"
  201. class="place--remove--btn"
  202. @click="removePlace(round, pIdx)"
  203. >✕</button>
  204. </div>
  205. <div class="place--select--wrap">
  206. <p class="mb--4">장소 정의</p>
  207. <!-- 분야/지역/제휴 셀렉트 — 항상 노출 -->
  208. <div class="input--wrap">
  209. <select v-model="place.field_id" class="admin--form-select">
  210. <option value="">전체 분야</option>
  211. <option v-for="f in fieldOptions" :key="f.id" :value="f.id">{{ f.name }}</option>
  212. </select>
  213. <select v-model="place.area_id" class="admin--form-select">
  214. <option value="">전체 지역</option>
  215. <option v-for="a in areaOptions" :key="a.id" :value="a.id">{{ a.name }}</option>
  216. </select>
  217. <select v-model="place.partnership_YN" class="admin--form-select">
  218. <option value="">제휴 여부</option>
  219. <option value="Y">제휴</option>
  220. <option value="N">비제휴</option>
  221. </select>
  222. <!-- 장소 미선택 시: "장소 선택" 버튼 + 드롭다운 -->
  223. <div v-if="place.onboards.length === 0" class="place--select--btn--wrap">
  224. <button
  225. type="button"
  226. class="admin--form-select"
  227. @click.stop="openDropdown(place)"
  228. >
  229. 장소 선택
  230. </button>
  231. <div
  232. v-if="place.dropdownOpen"
  233. class="all--place--wrap"
  234. @click.stop
  235. >
  236. <div class="place--top">
  237. <div class="search--wrap">
  238. <input v-model="place.searchKeyword" type="text" placeholder="선상ㆍ낚시터명 검색">
  239. </div>
  240. <div class="check--wrap">
  241. <label>
  242. <input
  243. type="checkbox"
  244. :checked="isAllFilteredSelected(place)"
  245. @change="toggleAll(place)"
  246. >
  247. 전체
  248. <span>조건의 모든 장소에 적용</span>
  249. </label>
  250. </div>
  251. <div class="all--place">
  252. <p>등록된 선상ㆍ낚시터</p>
  253. <ul class="all--place--list mt--6">
  254. <template v-for="group in groupedFilteredPlaces(place)" :key="group.area">
  255. <p class="group--header">
  256. {{ group.area }}
  257. <button
  258. type="button"
  259. @click="toggleAllInGroup(place, group.items)"
  260. >
  261. {{ isAllInGroupSelected(place, group.items) ? '그룹 해제' : '그룹 전체 선택' }}
  262. </button>
  263. </p>
  264. <li v-for="p in group.items" :key="placeKey(p)">
  265. <label>
  266. <input
  267. type="checkbox"
  268. :checked="place.tempSelected.includes(placeKey(p))"
  269. @change="togglePlaceInTemp(place, placeKey(p))"
  270. >
  271. <span>{{ p._placeType === 'onboard' ? '🚤' : '🎣' }} {{ p.name }}</span>
  272. <span :class="p.partnership_YN === 'Y' ? 'on' : 'off'">
  273. {{ p.partnership_YN === 'Y' ? '제휴' : '비제휴' }}
  274. </span>
  275. <p>{{ p.field_name || '-' }}</p>
  276. </label>
  277. </li>
  278. </template>
  279. <li v-if="filteredPlaces(place).length === 0" class="empty">
  280. 조건에 맞는 장소가 없습니다.
  281. </li>
  282. </ul>
  283. </div>
  284. </div>
  285. <div class="place--bot">
  286. <p>{{ place.tempSelected.length }}개 선택</p>
  287. <button type="button" @click="applyDropdown(place)">적용</button>
  288. </div>
  289. </div>
  290. </div>
  291. </div>
  292. <!-- 장소 선택 후 — 별도 영역에 "선상ㆍ낚시터 복수 선택" + 칩 -->
  293. <template v-if="place.onboards.length > 0">
  294. <p class="mt--16 mb--4">선상ㆍ낚시터 복수 선택</p>
  295. <div class="place--select--btn--wrap">
  296. <div
  297. class="admin--form-select"
  298. @click.stop="openDropdown(place)"
  299. >
  300. <div
  301. v-for="key in place.onboards.slice(0, 2)"
  302. :key="key"
  303. class="place--selected"
  304. >
  305. {{ placeTypeByKey(key) === 'onboard' ? '🚤' : '🎣' }} {{ placeNameByKey(key) }}
  306. <button
  307. type="button"
  308. @click.stop="removePlaceChip(place, key)"
  309. >✕</button>
  310. </div>
  311. <div v-if="place.onboards.length > 2" class="place--selected">
  312. + {{ place.onboards.length - 2 }}
  313. </div>
  314. </div>
  315. <div
  316. v-if="place.dropdownOpen"
  317. class="all--place--wrap"
  318. @click.stop
  319. >
  320. <div class="place--top">
  321. <div class="search--wrap">
  322. <input v-model="place.searchKeyword" type="text" placeholder="선상ㆍ낚시터명 검색">
  323. </div>
  324. <div class="check--wrap">
  325. <label>
  326. <input
  327. type="checkbox"
  328. :checked="isAllFilteredSelected(place)"
  329. @change="toggleAll(place)"
  330. >
  331. 전체
  332. <span>조건의 모든 장소에 적용</span>
  333. </label>
  334. </div>
  335. <div class="all--place">
  336. <p>등록된 선상ㆍ낚시터</p>
  337. <ul class="all--place--list mt--6">
  338. <template v-for="group in groupedFilteredPlaces(place)" :key="group.area">
  339. <p class="group--header">
  340. {{ group.area }}
  341. <button
  342. type="button"
  343. @click="toggleAllInGroup(place, group.items)"
  344. >
  345. {{ isAllInGroupSelected(place, group.items) ? '그룹 해제' : '그룹 전체 선택' }}
  346. </button>
  347. </p>
  348. <li v-for="p in group.items" :key="placeKey(p)">
  349. <label>
  350. <input
  351. type="checkbox"
  352. :checked="place.tempSelected.includes(placeKey(p))"
  353. @change="togglePlaceInTemp(place, placeKey(p))"
  354. >
  355. <span>{{ p._placeType === 'onboard' ? '🚤' : '🎣' }} {{ p.name }}</span>
  356. <span :class="p.partnership_YN === 'Y' ? 'on' : 'off'">
  357. {{ p.partnership_YN === 'Y' ? '제휴' : '비제휴' }}
  358. </span>
  359. <p>{{ p.field_name || '-' }}</p>
  360. </label>
  361. </li>
  362. </template>
  363. <li v-if="filteredPlaces(place).length === 0" class="empty">
  364. 조건에 맞는 장소가 없습니다.
  365. </li>
  366. </ul>
  367. </div>
  368. </div>
  369. <div class="place--bot">
  370. <p>{{ place.tempSelected.length }}개 선택</p>
  371. <button type="button" @click="applyDropdown(place)">적용</button>
  372. </div>
  373. </div>
  374. </div>
  375. </template>
  376. </div>
  377. <!-- 장소별 아이템 -->
  378. <div class="item--select--wrap">
  379. <div class="item--select--btn--wrap mb--4 mt--16">
  380. <p>배정 아이템ㆍ수량 {{ place.items.length }}</p>
  381. <button type="button" @click="openItemModal(place)">+ 아이템 선택</button>
  382. </div>
  383. <div class="item--selected--wrap">
  384. <div v-for="(it, iIdx) in place.items" :key="it.item_id" class="item--selected">
  385. {{ it.name }}<button type="button" @click="place.items.splice(iIdx, 1)">✕</button>
  386. </div>
  387. </div>
  388. </div>
  389. </div>
  390. <button type="button" class="place--add--btn" @click="addPlace(round)">
  391. + 장소 추가
  392. </button>
  393. </template>
  394. </div>
  395. </div>
  396. <button
  397. v-if="rounds.length < 5"
  398. type="button"
  399. class="round--add--btn"
  400. @click="addRound"
  401. >
  402. + 라운드 추가 (최대 5라운드)
  403. </button>
  404. <!-- 버튼 영역 -->
  405. <div class="admin--form-actions">
  406. <button type="button" class="admin--btn" @click="goToList">
  407. ← 목록으로
  408. </button>
  409. <button type="submit" class="admin--btn admin--btn-red ml--auto" :disabled="isSaving">
  410. {{ isSaving ? "저장 중..." : "저장" }}
  411. </button>
  412. </div>
  413. <!-- 성공/에러 메시지 -->
  414. <div v-if="successMessage" class="admin--alert admin--alert-success">
  415. {{ successMessage }}
  416. </div>
  417. <div v-if="errorMessage" class="admin--alert admin--alert-error">
  418. {{ errorMessage }}
  419. </div>
  420. </form>
  421. </div>
  422. <!-- ============================
  423. 아이템 선택 모달
  424. ============================ -->
  425. <ClientOnly>
  426. <Teleport to="body">
  427. <div
  428. v-if="itemModal.isOpen"
  429. class="admin--modal-overlay admin--alert-overlay"
  430. @click.self="closeItemModal"
  431. >
  432. <div class="admin--modal admin--form-modal admin--item-modal" @click.stop>
  433. <div class="admin--modal-header">
  434. <h4>아이템 선택</h4>
  435. <button type="button" class="admin--modal-close" @click="closeItemModal">✕</button>
  436. </div>
  437. <div class="admin--modal-body">
  438. <div class="admin--item-modal__search mb--16">
  439. <input
  440. v-model="itemModal.searchKeyword"
  441. type="text"
  442. class="admin--form-input w--full"
  443. placeholder="🔍 아이템명 검색"
  444. />
  445. </div>
  446. <ul v-if="filteredItems().length > 0" class="admin--item-modal__grid">
  447. <li
  448. v-for="it in filteredItems()"
  449. :key="it.id"
  450. class="admin--item-modal__card"
  451. :class="{ 'is-selected': itemModal.tempSelected.includes(it.id) }"
  452. >
  453. <label>
  454. <input
  455. type="checkbox"
  456. :checked="itemModal.tempSelected.includes(it.id)"
  457. @change="toggleItemInModal(it.id)"
  458. />
  459. <div class="admin--item-modal__thumb">
  460. <img
  461. v-if="it.file_path"
  462. :src="getImageUrl(it.file_path)"
  463. :alt="it.name"
  464. />
  465. <div v-else class="admin--item-modal__no-img">🎁</div>
  466. </div>
  467. <div class="admin--item-modal__name">{{ it.name }}</div>
  468. <div class="admin--item-modal__meta">
  469. <span v-if="it.type" class="admin--item-modal__type">{{ it.type == 'B' ? '뱃지' : it.type == 'P' ? '포인트' : '진출권' }}</span>
  470. <span v-if="it.point !== null && it.point !== undefined" class="admin--item-modal__point">{{ it.point }}P</span>
  471. </div>
  472. </label>
  473. </li>
  474. </ul>
  475. <div v-else class="admin--item-modal__empty">
  476. {{ itemModal.searchKeyword ? '검색 결과가 없습니다.' : '등록된 아이템이 없습니다.' }}
  477. </div>
  478. </div>
  479. <div class="admin--modal-footer">
  480. <span class="admin--item-modal__count mr--auto">{{ itemModal.tempSelected.length }}개 선택</span>
  481. <button type="button" class="admin--btn" @click="closeItemModal">취소</button>
  482. <button type="button" class="admin--btn admin--btn-primary-fill ml--8" @click="applyItemModal">적용</button>
  483. </div>
  484. </div>
  485. </div>
  486. </Teleport>
  487. </ClientOnly>
  488. </div>
  489. </template>
  490. <script setup>
  491. import { ref, onMounted, onBeforeUnmount } from "vue";
  492. import { useRouter } from "vue-router";
  493. import DatePicker from "~/components/admin/DatePicker.vue";
  494. import SunEditor from "~/components/admin/SunEditor.vue";
  495. definePageMeta({
  496. layout: "admin",
  497. middleware: ["auth"],
  498. });
  499. const router = useRouter();
  500. const { get, post, upload } = useApi();
  501. const { getImageUrl } = useImage();
  502. const isSaving = ref(false);
  503. const successMessage = ref("");
  504. const errorMessage = ref("");
  505. // ============================
  506. // 옵션 데이터
  507. // ============================
  508. const fieldOptions = ref([]);
  509. const areaOptions = ref([]);
  510. const placesAll = ref([]); // 검색용 전체 장소 (선상 + 낚시터, _placeType 필드로 구분)
  511. const itemsAll = ref([]); // 아이템 모달용 전체 아이템
  512. // ============================
  513. // 챌린지 기본 정보
  514. // ============================
  515. const formData = ref({
  516. name: "",
  517. fee: "",
  518. max_participants: "",
  519. status_YN: "Y",
  520. description: "",
  521. });
  522. const startDate = ref("");
  523. const endDate = ref("");
  524. const isFree = ref(false);
  525. // 무료 체크박스 토글
  526. const onFreeChange = () => {
  527. if (isFree.value) {
  528. formData.value.fee = "0";
  529. } else {
  530. formData.value.fee = "";
  531. }
  532. };
  533. // ============================
  534. // 이미지 업로드
  535. // ============================
  536. const imageInput = ref(null);
  537. const image = ref(null);
  538. const MAX_IMAGE_SIZE = 5 * 1024 * 1024;
  539. const triggerImageInput = () => imageInput.value?.click();
  540. const onImageChange = (e) => {
  541. const file = (e.target.files || [])[0];
  542. e.target.value = "";
  543. if (!file) return;
  544. if (!file.type.startsWith("image/")) {
  545. errorMessage.value = "이미지 파일만 업로드할 수 있습니다.";
  546. return;
  547. }
  548. if (file.size > MAX_IMAGE_SIZE) {
  549. errorMessage.value = "이미지가 5MB를 초과합니다.";
  550. return;
  551. }
  552. if (image.value) URL.revokeObjectURL(image.value.preview);
  553. image.value = { file, preview: URL.createObjectURL(file) };
  554. };
  555. const removeImage = () => {
  556. if (image.value) {
  557. URL.revokeObjectURL(image.value.preview);
  558. image.value = null;
  559. }
  560. };
  561. // ============================
  562. // 라운드/장소 동적 배열
  563. // ============================
  564. let _keySeq = 0;
  565. const nextKey = () => ++_keySeq;
  566. function createPlace() {
  567. return {
  568. _key: nextKey(),
  569. field_id: "",
  570. area_id: "",
  571. partnership_YN: "",
  572. onboards: [], // 적용된 장소 키 배열 (예: 'onboard-1', 'fishing-3')
  573. items: [], // [{ item_id, name, qty }] — Phase 2
  574. // UI 상태
  575. dropdownOpen: false,
  576. searchKeyword: "",
  577. tempSelected: [], // 드롭다운 내 임시 체크 (장소 키 배열)
  578. };
  579. }
  580. function createRound(no) {
  581. return {
  582. _key: nextKey(),
  583. round_no: no,
  584. place_mode: "all",
  585. qualified: "",
  586. items: [], // [{ item_id, name, qty }] — Phase 2
  587. places: [],
  588. };
  589. }
  590. const rounds = ref([createRound(1), createRound(2)]);
  591. function renumberRounds() {
  592. rounds.value.forEach((r, i) => { r.round_no = i + 1; });
  593. }
  594. function addRound() {
  595. if (rounds.value.length >= 5) return;
  596. rounds.value.push(createRound(rounds.value.length + 1));
  597. }
  598. function removeRound(idx) {
  599. if (rounds.value.length <= 2) return;
  600. rounds.value.splice(idx, 1);
  601. renumberRounds();
  602. }
  603. function changePlaceMode(round, mode) {
  604. round.place_mode = mode;
  605. // specific 으로 전환했는데 장소가 없으면 자동으로 장소 1 생성
  606. if (mode === "specific" && round.places.length === 0) {
  607. round.places.push(createPlace());
  608. }
  609. }
  610. function addPlace(round) {
  611. round.places.push(createPlace());
  612. }
  613. function removePlace(round, idx) {
  614. round.places.splice(idx, 1);
  615. // specific 모드인데 장소가 0개면 자동으로 1개 다시 추가 (또는 all 모드로 되돌리기 — 여기선 하나 자동 추가)
  616. if (round.places.length === 0) {
  617. round.places.push(createPlace());
  618. }
  619. }
  620. // ============================
  621. // 장소(선상+낚시터) 검색 드롭다운
  622. // ============================
  623. // 장소 키 헬퍼: 'onboard-1', 'fishing-2' 형태로 고유 식별
  624. const placeKey = (p) => `${p._placeType}-${p.id}`;
  625. const placeByKey = (k) => placesAll.value.find((p) => placeKey(p) === k);
  626. const placeNameByKey = (k) => placeByKey(k)?.name || "?";
  627. const placeTypeByKey = (k) => (k && k.startsWith("fishing-")) ? "fishing" : "onboard";
  628. function closeAllDropdowns() {
  629. rounds.value.forEach((r) =>
  630. r.places.forEach((p) => { p.dropdownOpen = false; })
  631. );
  632. }
  633. function openDropdown(place) {
  634. closeAllDropdowns();
  635. place.tempSelected = [...place.onboards];
  636. place.dropdownOpen = true;
  637. }
  638. function filteredPlaces(place) {
  639. return placesAll.value.filter((p) => {
  640. if (place.field_id && String(p.field_id) !== String(place.field_id)) return false;
  641. if (place.area_id && String(p.area_id) !== String(place.area_id)) return false;
  642. if (place.partnership_YN && p.partnership_YN !== place.partnership_YN) return false;
  643. if (place.searchKeyword) {
  644. const kw = place.searchKeyword.toLowerCase();
  645. if (!String(p.name || "").toLowerCase().includes(kw)) return false;
  646. }
  647. return true;
  648. });
  649. }
  650. function togglePlaceInTemp(place, key) {
  651. const idx = place.tempSelected.indexOf(key);
  652. if (idx === -1) place.tempSelected.push(key);
  653. else place.tempSelected.splice(idx, 1);
  654. }
  655. function isAllFilteredSelected(place) {
  656. const filtered = filteredPlaces(place);
  657. if (filtered.length === 0) return false;
  658. return filtered.every((p) => place.tempSelected.includes(placeKey(p)));
  659. }
  660. function toggleAll(place) {
  661. const filtered = filteredPlaces(place);
  662. const filteredKeys = filtered.map(placeKey);
  663. if (isAllFilteredSelected(place)) {
  664. const set = new Set(filteredKeys);
  665. place.tempSelected = place.tempSelected.filter((k) => !set.has(k));
  666. } else {
  667. const merged = new Set([...place.tempSelected, ...filteredKeys]);
  668. place.tempSelected = [...merged];
  669. }
  670. }
  671. // 지역별 그룹화: [{area, items: [...]}, ...]
  672. function groupedFilteredPlaces(place) {
  673. const filtered = filteredPlaces(place);
  674. const map = new Map();
  675. filtered.forEach((p) => {
  676. const area = p.area_name || "미분류";
  677. if (!map.has(area)) map.set(area, []);
  678. map.get(area).push(p);
  679. });
  680. return Array.from(map.entries()).map(([area, items]) => ({ area, items }));
  681. }
  682. function isAllInGroupSelected(place, items) {
  683. if (!items || items.length === 0) return false;
  684. return items.every((p) => place.tempSelected.includes(placeKey(p)));
  685. }
  686. function toggleAllInGroup(place, items) {
  687. const keys = items.map(placeKey);
  688. if (isAllInGroupSelected(place, items)) {
  689. const set = new Set(keys);
  690. place.tempSelected = place.tempSelected.filter((k) => !set.has(k));
  691. } else {
  692. const merged = new Set([...place.tempSelected, ...keys]);
  693. place.tempSelected = [...merged];
  694. }
  695. }
  696. function applyDropdown(place) {
  697. place.onboards = [...place.tempSelected];
  698. place.dropdownOpen = false;
  699. }
  700. function removePlaceChip(place, key) {
  701. place.onboards = place.onboards.filter((k) => k !== key);
  702. }
  703. // 외부 클릭 시 모든 드롭다운 닫기
  704. function handleDocumentClick() {
  705. closeAllDropdowns();
  706. }
  707. // ============================
  708. // 아이템 선택 모달
  709. // ============================
  710. const itemModal = ref({
  711. isOpen: false,
  712. target: null, // round 또는 place 객체 (둘 다 .items 배열 가짐)
  713. tempSelected: [], // 임시 선택된 item id 배열
  714. searchKeyword: "",
  715. });
  716. function openItemModal(target) {
  717. itemModal.value.target = target;
  718. itemModal.value.tempSelected = target.items.map((i) => i.item_id);
  719. itemModal.value.searchKeyword = "";
  720. itemModal.value.isOpen = true;
  721. }
  722. function closeItemModal() {
  723. itemModal.value.isOpen = false;
  724. itemModal.value.target = null;
  725. itemModal.value.tempSelected = [];
  726. itemModal.value.searchKeyword = "";
  727. }
  728. function toggleItemInModal(itemId) {
  729. const idx = itemModal.value.tempSelected.indexOf(itemId);
  730. if (idx === -1) itemModal.value.tempSelected.push(itemId);
  731. else itemModal.value.tempSelected.splice(idx, 1);
  732. }
  733. function filteredItems() {
  734. if (!itemModal.value.searchKeyword) return itemsAll.value;
  735. const kw = itemModal.value.searchKeyword.toLowerCase();
  736. return itemsAll.value.filter((i) =>
  737. String(i.name || "").toLowerCase().includes(kw)
  738. );
  739. }
  740. function applyItemModal() {
  741. const target = itemModal.value.target;
  742. if (!target) return;
  743. target.items = itemModal.value.tempSelected.map((id) => {
  744. const it = itemsAll.value.find((x) => x.id === id);
  745. return {
  746. item_id: id,
  747. name: it?.name || "?",
  748. type: it?.type || "",
  749. point: it?.point ?? null,
  750. };
  751. });
  752. closeItemModal();
  753. }
  754. // ============================
  755. // 데이터 로드
  756. // ============================
  757. async function loadOptions() {
  758. try {
  759. const [fieldRes, areaRes, onboardRes, fishingRes, itemRes] = await Promise.all([
  760. get("/field/list", { params: { per_page: 1000 } }),
  761. get("/area/list", { params: { per_page: 1000 } }),
  762. get("/onboard/list", { params: { per_page: 1000 } }),
  763. get("/fishing/list", { params: { per_page: 1000 } }),
  764. get("/item/list", { params: { per_page: 1000, status: "Y" } }),
  765. ]);
  766. if (fieldRes.data?.success) fieldOptions.value = (fieldRes.data.data.items || []).reverse();
  767. if (areaRes.data?.success) areaOptions.value = (areaRes.data.data.items || []).reverse();
  768. // 선상 + 낚시터 통합 (_placeType으로 구분)
  769. const onboards = (onboardRes.data?.success ? (onboardRes.data.data.items || []) : [])
  770. .map((o) => ({ ...o, _placeType: "onboard" }));
  771. const fishings = (fishingRes.data?.success ? (fishingRes.data.data.items || []) : [])
  772. .map((f) => ({ ...f, _placeType: "fishing" }));
  773. placesAll.value = [...onboards, ...fishings];
  774. if (itemRes.data?.success) itemsAll.value = itemRes.data.data.items || [];
  775. } catch (e) {
  776. console.error("Load options error:", e);
  777. }
  778. }
  779. // ============================
  780. // 폼 제출
  781. // ============================
  782. async function handleSubmit() {
  783. errorMessage.value = "";
  784. successMessage.value = "";
  785. // 프론트 1차 검증
  786. if (!formData.value.name.trim()) return (errorMessage.value = "챌린지명을 입력하세요.");
  787. if (!formData.value.fee.toString().trim()) return (errorMessage.value = "참가비를 입력하세요.");
  788. if (!startDate.value) return (errorMessage.value = "시작일을 선택하세요.");
  789. if (!endDate.value) return (errorMessage.value = "종료일을 선택하세요.");
  790. if (!formData.value.max_participants) return (errorMessage.value = "최대 참가자를 입력하세요.");
  791. for (let i = 0; i < rounds.value.length; i++) {
  792. const r = rounds.value[i];
  793. if (!r.qualified) {
  794. return (errorMessage.value = `라운드 ${i + 1}의 진출자 수를 입력하세요.`);
  795. }
  796. if (r.place_mode === "specific") {
  797. if (r.places.length === 0) {
  798. return (errorMessage.value = `라운드 ${i + 1}에 장소를 1개 이상 추가하세요.`);
  799. }
  800. for (let j = 0; j < r.places.length; j++) {
  801. if (r.places[j].onboards.length === 0) {
  802. return (errorMessage.value = `라운드 ${i + 1} 장소 ${j + 1}에 선상을 1개 이상 선택하세요.`);
  803. }
  804. }
  805. }
  806. }
  807. isSaving.value = true;
  808. try {
  809. const payload = {
  810. name: formData.value.name,
  811. fee: formData.value.fee,
  812. start_date: startDate.value,
  813. end_date: endDate.value,
  814. max_participants: Number(formData.value.max_participants),
  815. description: formData.value.description,
  816. status_YN: formData.value.status_YN,
  817. rounds: rounds.value.map((r) => ({
  818. round_no: r.round_no,
  819. place_mode: r.place_mode,
  820. qualified: Number(r.qualified),
  821. items: r.place_mode === "all"
  822. ? r.items.map((it) => ({ item_id: it.item_id }))
  823. : [],
  824. places: r.place_mode === "specific"
  825. ? r.places.map((p) => ({
  826. // 'onboard-1', 'fishing-3' → [{type:'onboard', id:1}, {type:'fishing', id:3}, ...]
  827. onboards: p.onboards.map((key) => {
  828. const i = key.indexOf("-");
  829. return { type: key.substring(0, i), id: Number(key.substring(i + 1)) };
  830. }),
  831. items: p.items.map((it) => ({ item_id: it.item_id })),
  832. }))
  833. : [],
  834. })),
  835. };
  836. const { data, error } = await post("/challenge", payload);
  837. if (error || !data?.success) {
  838. errorMessage.value = error?.message || data?.message || "등록에 실패했습니다.";
  839. return;
  840. }
  841. const newId = data.data?.id;
  842. // 이미지가 있으면 업로드 (챌린지 id 받은 뒤)
  843. if (newId && image.value) {
  844. const fd = new FormData();
  845. fd.append("image", image.value.file);
  846. const { data: imgRes, error: imgErr } = await upload(`/challenge/${newId}/image`, fd);
  847. if (imgErr || !imgRes?.success) {
  848. errorMessage.value = "챌린지는 등록됐지만 이미지 업로드에 실패했습니다. 수정에서 다시 시도해주세요.";
  849. setTimeout(() => router.push("/site-manager/challenge/list"), 1500);
  850. return;
  851. }
  852. }
  853. successMessage.value = data.message || "챌린지가 등록되었습니다.";
  854. setTimeout(() => {
  855. router.push("/site-manager/challenge/list");
  856. }, 1000);
  857. } catch (e) {
  858. errorMessage.value = "서버 오류가 발생했습니다.";
  859. console.error("Challenge save error:", e);
  860. } finally {
  861. isSaving.value = false;
  862. }
  863. }
  864. const goToList = () => router.push("/site-manager/challenge/list");
  865. onMounted(() => {
  866. loadOptions();
  867. document.addEventListener("click", handleDocumentClick);
  868. });
  869. onBeforeUnmount(() => {
  870. document.removeEventListener("click", handleDocumentClick);
  871. });
  872. </script>