mp-ss-components.js 98 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386
  1. // H5版本的小程序组件库
  2. // 参考 alf/ss-components.js 的组件形式
  3. (function () {
  4. const {
  5. ref,
  6. createApp,
  7. watch,
  8. inject,
  9. onMounted,
  10. onBeforeUnmount,
  11. computed,
  12. } = Vue;
  13. async function ensureOptionalAssets(name) {
  14. if (window.SS && typeof window.SS.ensureOptionalAssets === "function") {
  15. return window.SS.ensureOptionalAssets(name);
  16. }
  17. throw new Error(`可选资源加载器未就绪: ${name}`);
  18. }
  19. // ===== 公共上传函数 =====
  20. /**
  21. * 统一文件上传函数
  22. * @param {File|Blob} file - 文件或Blob对象
  23. * @param {String} type - 'image' | 'file'
  24. * @param {String} fileName - 文件名(可选)
  25. * @returns {Promise<String>} 服务器路径
  26. */
  27. async function uploadFile(file, type = "image", fileName) {
  28. try {
  29. window.showToast?.("上传中...", "loading");
  30. const formData = new FormData();
  31. const name = fileName || (file instanceof Blob ? "file" : file.name);
  32. formData.append("fileEdit", file, name);
  33. formData.append("application", "");
  34. // 根据类型选择接口参数
  35. const apiType = type === "image" ? "img" : "file";
  36. const result = await window.request.post(
  37. `/service?ssServ=ulByHttp&type=${apiType}`,
  38. formData,
  39. { loading: false }
  40. );
  41. if (result?.data?.fileList?.[0]?.path) {
  42. const serverPath = result.data.fileList[0].path;
  43. window.showToast?.("上传成功", "success");
  44. return serverPath;
  45. } else {
  46. throw new Error("上传返回数据格式错误");
  47. }
  48. } catch (error) {
  49. console.error("上传失败:", error);
  50. window.showToast?.("上传失败,请重试", "error");
  51. throw error;
  52. }
  53. }
  54. const SsCommonIcon = {
  55. name: "SsCommonIcon",
  56. props: {
  57. class: {
  58. type: String,
  59. required: true,
  60. },
  61. },
  62. setup(props) {
  63. const { h } = Vue;
  64. return () =>
  65. h("i", {
  66. class: props.class + " common-icon",
  67. });
  68. },
  69. };
  70. // ss-input 智能输入组件
  71. const SsInput = {
  72. name: "SsInput",
  73. inheritAttrs: false, // 不直接继承属性到组件根元素
  74. props: {
  75. // v-model 绑定的值
  76. modelValue: {
  77. type: [String, Number],
  78. default: "",
  79. },
  80. // 字段名称
  81. name: {
  82. type: String,
  83. default: "",
  84. },
  85. // 占位符
  86. placeholder: {
  87. type: String,
  88. default: "请输入",
  89. },
  90. // 错误提示
  91. errTip: {
  92. type: String,
  93. default: "",
  94. },
  95. },
  96. emits: ["update:modelValue", "input", "blur", "change", "focus"],
  97. setup(props, { emit }) {
  98. const inputValue = ref(props.modelValue || "");
  99. const validationState = ref({
  100. hasError: false,
  101. errorMessage: "",
  102. isRequired: false,
  103. isEmpty: true,
  104. hasInteracted: false, // 是否已经交互过
  105. isSubmitMode: false, // 是否处于提交模式
  106. });
  107. // 从ValidatedTd注入事件处理函数(兼容小程序方式)
  108. const onInputInject = inject("onInput", null);
  109. const onBlurInject = inject("onBlur", null);
  110. // 检查是否为必填字段
  111. const checkRequired = () => {
  112. if (window.ssVm && props.name) {
  113. validationState.value.isRequired = window.ssVm.isRequired(props.name);
  114. }
  115. };
  116. // 更新父级td的class
  117. const updateTdClass = () => {
  118. // 找到父级td元素
  119. const inputElement = document.querySelector(
  120. `input[name="${props.name}"]`
  121. );
  122. if (inputElement) {
  123. const tdElement = inputElement.closest("td");
  124. if (tdElement) {
  125. // 移除所有校验相关的class
  126. tdElement.classList.remove("td-required", "td-error");
  127. // 逻辑分离:
  128. // 1. 初始状态:必填且为空 → 只有左侧红线 (td-required)
  129. // 2. 实时校验失败 → 左侧红线 + 底部红线 + 错误文字 (td-error)
  130. if (
  131. validationState.value.hasError &&
  132. validationState.value.hasInteracted
  133. ) {
  134. // 用户交互后校验失败:左侧红线 + 底部红线 + 错误文字
  135. tdElement.classList.add("td-error");
  136. } else if (
  137. validationState.value.isRequired &&
  138. validationState.value.isEmpty
  139. ) {
  140. // 必填且为空:只有左侧红线
  141. tdElement.classList.add("td-required");
  142. }
  143. }
  144. }
  145. };
  146. // 校验字段
  147. const validateField = (value) => {
  148. if (window.ssVm && props.name) {
  149. const result = window.ssVm.validateField(props.name);
  150. validationState.value.hasError = !result.valid;
  151. validationState.value.errorMessage = result.message || "";
  152. validationState.value.isEmpty = !value || value.trim() === "";
  153. // 更新td的class
  154. setTimeout(updateTdClass, 0);
  155. return result;
  156. }
  157. return { valid: true, message: "" };
  158. };
  159. // 监听props变化
  160. watch(
  161. () => props.modelValue,
  162. (newVal) => {
  163. inputValue.value = newVal;
  164. validateField(newVal);
  165. }
  166. );
  167. // 挂载时初始化
  168. onMounted(() => {
  169. checkRequired();
  170. validateField(inputValue.value);
  171. // 监听ssVm规则更新事件
  172. const inputElement = document.querySelector(
  173. `input[name="${props.name}"]`
  174. );
  175. if (inputElement) {
  176. inputElement.addEventListener("ssvm-rules-updated", () => {
  177. console.log(`收到规则更新通知: ${props.name}`);
  178. checkRequired();
  179. validateField(inputValue.value);
  180. updateTdClass();
  181. });
  182. }
  183. // 确保初始状态正确显示,延迟更长时间确保DOM完全渲染
  184. setTimeout(() => {
  185. updateTdClass();
  186. }, 200);
  187. });
  188. // 事件处理函数
  189. const handleInput = (event) => {
  190. const value = event.target.value;
  191. inputValue.value = value;
  192. // 标记已交互
  193. validationState.value.hasInteracted = true;
  194. // 1. 支持v-model
  195. emit("update:modelValue", value);
  196. emit("input", event);
  197. // 2. 内部校验(实时校验)
  198. validateField(value);
  199. // 3. 兼容小程序inject方式
  200. if (onInputInject) {
  201. onInputInject(event);
  202. }
  203. };
  204. const handleBlur = (event) => {
  205. // 标记已交互
  206. validationState.value.hasInteracted = true;
  207. emit("blur", event);
  208. // 失焦时再次校验
  209. validateField(inputValue.value);
  210. // 兼容小程序inject方式
  211. if (onBlurInject) {
  212. onBlurInject(event);
  213. }
  214. };
  215. const handleFocus = (event) => {
  216. emit("focus", event);
  217. };
  218. return {
  219. inputValue,
  220. validationState,
  221. handleInput,
  222. handleBlur,
  223. handleFocus,
  224. };
  225. },
  226. template: `
  227. <!-- 移动端简化的错误提示 - 显示在输入框右下角 -->
  228. <div v-if="validationState.hasError && validationState.hasInteracted" class="ss-input__error">
  229. {{ validationState.errorMessage }}
  230. </div>
  231. <div class="ss-input">
  232. <input
  233. class="ss-input__field"
  234. :name="name"
  235. type="text"
  236. :value="inputValue"
  237. :placeholder="placeholder"
  238. @input="handleInput"
  239. @blur="handleBlur"
  240. @focus="handleFocus"
  241. autocomplete="off"
  242. v-bind="$attrs"
  243. />
  244. </div>
  245. `,
  246. };
  247. // icon 图标组件 - 从小程序转换
  248. const Icon = {
  249. name: "Icon",
  250. props: {
  251. // 图标名称,对应iconfont中的类名,如'icon-home'
  252. name: {
  253. type: String,
  254. required: true,
  255. },
  256. // 图标颜色
  257. color: {
  258. type: String,
  259. default: "#000",
  260. },
  261. // 图标大小,单位rpx (H5中转换为px)
  262. size: {
  263. type: [Number, String],
  264. default: 32,
  265. },
  266. },
  267. emits: ["click"],
  268. setup(props, { emit }) {
  269. // 计算完整的图标类名
  270. const iconClass = computed(() => {
  271. return props.name;
  272. });
  273. // 计算样式
  274. const iconStyle = computed(() => ({
  275. color: props.color,
  276. fontSize: parseInt(props.size) / 2 + "px", // rpx转px,除以2
  277. verticalAlign: "middle",
  278. }));
  279. // 点击事件处理
  280. const handleClick = (event) => {
  281. emit("click", event);
  282. };
  283. return {
  284. iconClass,
  285. iconStyle,
  286. handleClick,
  287. };
  288. },
  289. template: `
  290. <span
  291. :class="['iconfont', iconClass]"
  292. :style="iconStyle"
  293. @click="handleClick"
  294. ></span>
  295. `,
  296. };
  297. // ss-card 卡片组件 - 从小程序转换
  298. const SsCard = {
  299. name: "SsCard",
  300. props: {
  301. item: {
  302. type: Object,
  303. default: () => ({}),
  304. },
  305. },
  306. emits: ["click", "buttonClick"],
  307. setup(props, { emit }) {
  308. // 状态
  309. const showButtonMenu = ref(false);
  310. const swipeOffset = ref(0);
  311. const touchStartX = ref(0);
  312. const touchStartY = ref(0);
  313. const swipeOpening = ref(false);
  314. const isSwiping = ref(false);
  315. const swipeActions = computed(() => {
  316. return Array.isArray(props.item?.swipeActions)
  317. ? props.item.swipeActions.filter(Boolean)
  318. : [];
  319. });
  320. const hasSwipeActions = computed(() => swipeActions.value.length > 0);
  321. const swipeActionPalette = [
  322. { backgroundColor: "#357cdf", color: "#fff" },
  323. { backgroundColor: "#94bfff", color: "#000000" },
  324. { backgroundColor: "#e0edff", color: "#000000" },
  325. ];
  326. const actionPaneWidth = computed(() => {
  327. if (!hasSwipeActions.value) return 0;
  328. return 66 * swipeActions.value.length;
  329. });
  330. // 计算属性
  331. const hasButtons = computed(() => {
  332. return (
  333. props.item?.buttons &&
  334. Array.isArray(props.item.buttons) &&
  335. props.item.buttons.length > 0
  336. );
  337. });
  338. const isMultipleButtons = computed(() => {
  339. return props.item?.buttons && props.item.buttons.length > 1;
  340. });
  341. const isSingleButton = computed(() => {
  342. return props.item?.buttons && props.item.buttons.length === 1;
  343. });
  344. const cardContentStyle = computed(() => ({
  345. transform: `translateX(-${swipeOffset.value}px)`,
  346. }));
  347. const actionPaneStyle = computed(() => ({
  348. width: `${actionPaneWidth.value}px`,
  349. }));
  350. const swipeIndicatorStyle = computed(() => {
  351. const palette = getSwipeActionStyle(0) || {};
  352. return {
  353. backgroundColor: palette.backgroundColor || "#357cdf",
  354. opacity: swipeOffset.value > 0 ? 0 : 1,
  355. };
  356. });
  357. const getSwipeActionStyle = (index) => {
  358. const paletteIndex = Math.min(
  359. Number(index || 0),
  360. swipeActionPalette.length - 1
  361. );
  362. return swipeActionPalette[paletteIndex] || swipeActionPalette[0];
  363. };
  364. const closeSwipe = () => {
  365. swipeOffset.value = 0;
  366. swipeOpening.value = false;
  367. };
  368. const openSwipe = () => {
  369. if (!hasSwipeActions.value) return;
  370. swipeOffset.value = actionPaneWidth.value;
  371. swipeOpening.value = true;
  372. };
  373. // 处理卡片点击
  374. const handleCardClick = () => {
  375. if (isSwiping.value) {
  376. isSwiping.value = false;
  377. return;
  378. }
  379. if (swipeOpening.value) {
  380. closeSwipe();
  381. return;
  382. }
  383. // 如果菜单打开,先关闭菜单
  384. if (showButtonMenu.value) {
  385. showButtonMenu.value = false;
  386. return;
  387. }
  388. emit("click");
  389. };
  390. // 处理设置按钮点击
  391. const handleSettingClick = () => {
  392. if (isSingleButton.value) {
  393. // 只有一个按钮,直接执行
  394. handleButtonClick(props.item.buttons[0], 0);
  395. } else if (isMultipleButtons.value) {
  396. // 先记录当前状态
  397. const wasOpen = showButtonMenu.value;
  398. // 关闭其他卡片的菜单
  399. document.dispatchEvent(new CustomEvent("closeAllCardMenus"));
  400. // 切换当前菜单状态
  401. showButtonMenu.value = !wasOpen;
  402. }
  403. };
  404. // 关闭菜单
  405. const closeMenu = () => {
  406. showButtonMenu.value = false;
  407. };
  408. const handleTouchStart = (event) => {
  409. if (!hasSwipeActions.value) return;
  410. const touch = event.touches && event.touches[0];
  411. if (!touch) return;
  412. touchStartX.value = touch.clientX;
  413. touchStartY.value = touch.clientY;
  414. isSwiping.value = false;
  415. document.dispatchEvent(new CustomEvent("closeAllCardSwipes"));
  416. };
  417. const handleTouchMove = (event) => {
  418. if (!hasSwipeActions.value) return;
  419. const touch = event.touches && event.touches[0];
  420. if (!touch) return;
  421. const deltaX = touch.clientX - touchStartX.value;
  422. const deltaY = touch.clientY - touchStartY.value;
  423. if (Math.abs(deltaY) > Math.abs(deltaX) || Math.abs(deltaX) < 8) {
  424. return;
  425. }
  426. isSwiping.value = true;
  427. const nextOffset = swipeOpening.value
  428. ? actionPaneWidth.value - deltaX
  429. : -deltaX;
  430. swipeOffset.value = Math.max(
  431. 0,
  432. Math.min(actionPaneWidth.value, nextOffset)
  433. );
  434. };
  435. const handleTouchEnd = () => {
  436. if (!hasSwipeActions.value) return;
  437. if (swipeOffset.value > actionPaneWidth.value / 2) {
  438. openSwipe();
  439. } else {
  440. closeSwipe();
  441. }
  442. setTimeout(() => {
  443. isSwiping.value = false;
  444. }, 0);
  445. };
  446. const handleCloseAllSwipes = () => {
  447. closeSwipe();
  448. };
  449. // 处理按钮点击
  450. const handleButtonClick = (btn, index) => {
  451. showButtonMenu.value = false;
  452. closeSwipe();
  453. // 执行按钮的回调
  454. if (btn.onclick && typeof btn.onclick === "function") {
  455. btn.onclick();
  456. }
  457. // 触发组件事件
  458. emit("buttonClick", { button: btn, index, item: props.item });
  459. };
  460. // 监听全局关闭事件
  461. onMounted(() => {
  462. document.addEventListener("closeAllCardMenus", closeMenu);
  463. document.addEventListener("closeAllCardSwipes", handleCloseAllSwipes);
  464. });
  465. onBeforeUnmount(() => {
  466. document.removeEventListener("closeAllCardMenus", closeMenu);
  467. document.removeEventListener(
  468. "closeAllCardSwipes",
  469. handleCloseAllSwipes
  470. );
  471. });
  472. // H5环境下的清理逻辑
  473. // 注意:Vue 3的beforeUnmount在某些H5环境下可能不可用
  474. // 这里暂时省略,依赖页面刷新时的自动清理
  475. return {
  476. showButtonMenu,
  477. swipeActions,
  478. hasSwipeActions,
  479. hasButtons,
  480. isMultipleButtons,
  481. isSingleButton,
  482. cardContentStyle,
  483. actionPaneStyle,
  484. swipeIndicatorStyle,
  485. getSwipeActionStyle,
  486. handleCardClick,
  487. handleSettingClick,
  488. handleTouchStart,
  489. handleTouchMove,
  490. handleTouchEnd,
  491. handleButtonClick,
  492. };
  493. },
  494. template: `
  495. <div class="ss-card" :class="{ 'ss-card--swipeable': hasSwipeActions }">
  496. <div
  497. v-if="hasSwipeActions"
  498. class="ss-card-swipe__indicator"
  499. :style="swipeIndicatorStyle"
  500. ></div>
  501. <div v-if="hasSwipeActions" class="ss-card-swipe__actions" :style="actionPaneStyle">
  502. <!-- 功能说明:卡片左滑露出记录操作按钮(如“变动”),替代齿轮菜单入口 by xu 2026-03-06 -->
  503. <button
  504. v-for="(btn, index) in swipeActions"
  505. :key="index"
  506. class="ss-card-swipe__action"
  507. :style="getSwipeActionStyle(index)"
  508. @click.stop="handleButtonClick(btn, index)"
  509. >
  510. {{ btn.title || btn.text || btn.desc }}
  511. </button>
  512. </div>
  513. <div
  514. class="ss-card-swipe__content"
  515. :style="cardContentStyle"
  516. @touchstart="handleTouchStart"
  517. @touchmove="handleTouchMove"
  518. @touchend="handleTouchEnd"
  519. >
  520. <div class="ss-card-main" @click="handleCardClick">
  521. <!-- 右上角设置按钮 - 只有buttons且长度>0时显示 -->
  522. <div
  523. v-if="hasButtons && !hasSwipeActions"
  524. class="card-setting-header"
  525. @click.stop="handleSettingClick"
  526. >
  527. <div class="setting-icon">
  528. <Icon name="icon-chilun" size="32" color="#999"/>
  529. </div>
  530. <!-- 按钮弹窗菜单 - 只有多个按钮时显示 -->
  531. <div
  532. v-if="showButtonMenu && isMultipleButtons"
  533. class="button-menu"
  534. @click.stop
  535. >
  536. <div
  537. v-for="(btn, index) in item.buttons"
  538. :key="index"
  539. class="menu-item"
  540. @click="handleButtonClick(btn, index)"
  541. >
  542. <Icon v-if="btn.icon" :name="btn.icon" size="28" color="inherit"/>
  543. <span class="menu-text">{{ btn.title }}</span>
  544. </div>
  545. </div>
  546. </div>
  547. <!-- 卡片内容 -->
  548. <slot></slot>
  549. </div>
  550. </div>
  551. </div>
  552. `,
  553. };
  554. // ss-search-button 搜索按钮组件 - 从小程序转换
  555. const SsSearchButton = {
  556. name: "SsSearchButton",
  557. props: {
  558. // 按钮文本
  559. text: {
  560. type: String,
  561. default: "增加",
  562. },
  563. // 是否禁用
  564. disabled: {
  565. type: Boolean,
  566. default: false,
  567. },
  568. // 按钮高度
  569. height: {
  570. type: [String, Number],
  571. default: "36px",
  572. },
  573. // 前置图标名称
  574. preIcon: {
  575. type: String,
  576. default: "",
  577. },
  578. // 后置图标名称
  579. suffixIcon: {
  580. type: String,
  581. default: "",
  582. },
  583. // 图标大小
  584. iconSize: {
  585. type: [String, Number],
  586. default: "32",
  587. },
  588. // 图标颜色
  589. iconColor: {
  590. type: String,
  591. default: "#585d6e",
  592. },
  593. // 自定义按钮样式
  594. customStyle: {
  595. type: Object,
  596. default: () => ({}),
  597. },
  598. // 跳转链接(兼容原JSP用法)
  599. href: {
  600. type: String,
  601. default: "",
  602. },
  603. // 选项列表
  604. options: {
  605. type: Array,
  606. default: () => [],
  607. },
  608. },
  609. emits: ["click", "optionClick"],
  610. setup(props, { emit }) {
  611. // 状态
  612. const showOptionsMenu = ref(false);
  613. // 计算属性
  614. const hasOptions = computed(() => {
  615. return (
  616. props.options &&
  617. Array.isArray(props.options) &&
  618. props.options.length > 0
  619. );
  620. });
  621. const hasMultipleOptions = computed(() => {
  622. return props.options && props.options.length > 1;
  623. });
  624. const isSingleOption = computed(() => {
  625. return props.options && props.options.length === 1;
  626. });
  627. // 按钮样式
  628. const buttonStyle = computed(() => ({
  629. height:
  630. typeof props.height === "number" ? `${props.height}px` : props.height,
  631. ...props.customStyle,
  632. }));
  633. // 处理按钮点击
  634. const handleClick = () => {
  635. if (!hasOptions.value) {
  636. // 没有选项,直接触发点击事件
  637. emit("click");
  638. } else if (isSingleOption.value) {
  639. // 单个选项,直接执行
  640. handleOptionClick(props.options[0], 0);
  641. } else if (hasMultipleOptions.value) {
  642. // 先记录当前状态
  643. const wasOpen = showOptionsMenu.value;
  644. // 关闭其他按钮的菜单
  645. document.dispatchEvent(new CustomEvent("closeAllButtonMenus"));
  646. // 切换当前菜单状态
  647. showOptionsMenu.value = !wasOpen;
  648. }
  649. };
  650. // 处理选项点击
  651. const handleOptionClick = (option, index) => {
  652. showOptionsMenu.value = false;
  653. // 执行选项的回调
  654. if (option.onclick && typeof option.onclick === "function") {
  655. option.onclick();
  656. }
  657. // 触发组件事件
  658. emit("optionClick", { option, index });
  659. };
  660. // 关闭菜单
  661. const closeMenu = () => {
  662. showOptionsMenu.value = false;
  663. };
  664. // 监听全局关闭事件
  665. onMounted(() => {
  666. document.addEventListener("closeAllButtonMenus", closeMenu);
  667. });
  668. return {
  669. showOptionsMenu,
  670. hasOptions,
  671. hasMultipleOptions,
  672. isSingleOption,
  673. buttonStyle,
  674. handleClick,
  675. handleOptionClick,
  676. };
  677. },
  678. template: `
  679. <div class="ss-search-button-container" :class="{ open: showOptionsMenu }">
  680. <button
  681. class="ss-search-button"
  682. :style="buttonStyle"
  683. @click="handleClick"
  684. :disabled="disabled"
  685. >
  686. <!-- 前置图标插槽 -->
  687. <div v-if="preIcon" class="ss-search-button__pre-icon">
  688. <Icon :name="preIcon" :size="iconSize" :color="iconColor"/>
  689. </div>
  690. <!-- 按钮文本 -->
  691. <span class="ss-search-button__text">{{ text }}</span>
  692. <!-- 后置图标插槽 -->
  693. <div v-if="suffixIcon" class="ss-search-button__suffix-icon">
  694. <Icon :name="suffixIcon" :size="iconSize" :color="iconColor"/>
  695. </div>
  696. </button>
  697. <!-- 选项弹窗菜单 -->
  698. <div
  699. v-if="showOptionsMenu && hasMultipleOptions"
  700. class="options-menu"
  701. @click.stop
  702. >
  703. <div
  704. v-for="(option, index) in options"
  705. :key="index"
  706. class="option-item"
  707. @click="handleOptionClick(option, index)"
  708. >
  709. <Icon v-if="option.icon" :name="option.icon" size="28" color="inherit"/>
  710. <span class="option-text">{{ option.text }}</span>
  711. </div>
  712. </div>
  713. </div>
  714. `,
  715. };
  716. let activeSsSelectCloser = null;
  717. // ss-select 下拉选择组件 - 从小程序转换
  718. const SsSelect = {
  719. name: "SsSelect",
  720. props: {
  721. // 选项数组
  722. options: {
  723. type: Array,
  724. default: () => [],
  725. },
  726. // 字段映射
  727. mapping: {
  728. type: Object,
  729. default: () => ({ text: "n", value: "v" }),
  730. },
  731. // 默认值
  732. modelValue: {
  733. type: [String, Number],
  734. default: "",
  735. },
  736. // 占位符
  737. placeholder: {
  738. type: String,
  739. default: "请选择",
  740. },
  741. // 校验配置
  742. validation: {
  743. type: Object,
  744. default: () => ({ enable: false, message: "" }),
  745. },
  746. // 是否禁用
  747. disabled: {
  748. type: Boolean,
  749. default: false,
  750. },
  751. // 是否支持搜索
  752. searchable: {
  753. type: Boolean,
  754. default: false,
  755. },
  756. // 是否支持清空
  757. clearable: {
  758. type: Boolean,
  759. default: false,
  760. },
  761. // 加载状态
  762. loading: {
  763. type: Boolean,
  764. default: false,
  765. },
  766. // 宽度设置
  767. width: {
  768. type: String,
  769. default: "100%",
  770. },
  771. minWidth: {
  772. type: String,
  773. default: "unset",
  774. },
  775. // 功能说明:对齐PC端 ss-objp,用 codebook 在组件内部拉取下拉选项 by xu 2026-02-28
  776. cb: {
  777. type: String,
  778. default: "",
  779. },
  780. url: {
  781. type: String,
  782. default: "/service?ssServ=loadObjpOpt&objectpickerdropdown1=1",
  783. },
  784. inp: {
  785. type: [Boolean, String],
  786. default: false,
  787. },
  788. filter: {
  789. type: [Object, String],
  790. default: null,
  791. },
  792. autoSelectFirst: {
  793. type: Boolean,
  794. default: false,
  795. },
  796. },
  797. emits: ["update:modelValue", "change", "search", "clear", "loaded"],
  798. setup(props, { emit }) {
  799. const isOpen = ref(false);
  800. const containerRef = ref(null);
  801. const inputRef = ref(null);
  802. const selectedValue = ref(props.modelValue);
  803. const searchKeyword = ref("");
  804. const filterKeyword = ref("");
  805. const remoteOptions = ref([]);
  806. const remoteLoading = ref(false);
  807. const autoMinWidth = ref("");
  808. const forceShowAll = ref(false);
  809. const canInput = computed(() => {
  810. return props.inp === true || props.inp === "true";
  811. });
  812. // 功能说明:ss-select 未显式传宽度时,按 placeholder/选项文本计算稳定最小宽度,避免回显和下拉宽度随选中项抖动 by xu 2026-03-06
  813. const normalizeCssSize = (value) => {
  814. if (value === undefined || value === null) return "";
  815. if (typeof value === "number") return `${value}px`;
  816. const text = String(value).trim();
  817. return text;
  818. };
  819. const hasExplicitWidth = computed(() => {
  820. const widthText = normalizeCssSize(props.width);
  821. if (!widthText) return false;
  822. return widthText !== "100%" && widthText !== "auto";
  823. });
  824. const parseFilterObj = () => {
  825. if (!props.filter) return {};
  826. if (typeof props.filter === "object") return props.filter;
  827. if (typeof props.filter === "string") {
  828. try {
  829. const obj = JSON.parse(props.filter);
  830. return obj && typeof obj === "object" ? obj : {};
  831. } catch (_) {
  832. return {};
  833. }
  834. }
  835. return {};
  836. };
  837. const normalizeResultToOptions = (respData) => {
  838. const raw = respData || {};
  839. if (Array.isArray(raw.resultList)) {
  840. return raw.resultList.map((it) => {
  841. if (it && typeof it === "object") return it;
  842. return { n: String(it || ""), v: String(it || "") };
  843. });
  844. }
  845. if (Array.isArray(raw.result)) {
  846. return raw.result
  847. .map((it) => {
  848. if (!it || typeof it !== "object") return null;
  849. const entry = Object.entries(it)[0];
  850. if (!entry) return null;
  851. return { n: entry[1], v: entry[0] };
  852. })
  853. .filter(Boolean);
  854. }
  855. if (raw.result && typeof raw.result === "object") {
  856. return Object.keys(raw.result).map((k) => ({
  857. n: raw.result[k],
  858. v: k,
  859. }));
  860. }
  861. if (Array.isArray(raw.objectList)) {
  862. return raw.objectList.map((it) => {
  863. if (it && typeof it === "object") return it;
  864. return { n: String(it || ""), v: String(it || "") };
  865. });
  866. }
  867. return [];
  868. };
  869. const needRemoteData = computed(() => !!String(props.cb || "").trim());
  870. const optionsList = computed(() => {
  871. if (Array.isArray(props.options) && props.options.length > 0) {
  872. return props.options;
  873. }
  874. if (needRemoteData.value) {
  875. return remoteOptions.value;
  876. }
  877. return [];
  878. });
  879. const getOptionText = (option) => {
  880. if (!option || typeof option !== "object") return "";
  881. const text = option[props.mapping.text];
  882. return text === undefined || text === null ? "" : String(text);
  883. };
  884. const findSelectedOption = () => {
  885. return optionsList.value.find(
  886. (option) => option?.[props.mapping.value] === selectedValue.value
  887. );
  888. };
  889. const syncInputFromSelection = () => {
  890. if (!canInput.value) return;
  891. const selectedOption = findSelectedOption();
  892. searchKeyword.value = selectedOption
  893. ? getOptionText(selectedOption)
  894. : "";
  895. filterKeyword.value = "";
  896. forceShowAll.value = false;
  897. };
  898. const filteredOptions = computed(() => {
  899. const list = Array.isArray(optionsList.value) ? optionsList.value : [];
  900. if (!canInput.value || forceShowAll.value) {
  901. return list;
  902. }
  903. const keyword = String(filterKeyword.value || "")
  904. .trim()
  905. .toLowerCase();
  906. if (!keyword) {
  907. return list;
  908. }
  909. return list.filter((option) =>
  910. getOptionText(option).toLowerCase().includes(keyword)
  911. );
  912. });
  913. const measureStableMinWidth = () => {
  914. if (hasExplicitWidth.value) {
  915. autoMinWidth.value = "";
  916. return;
  917. }
  918. const texts = [props.placeholder]
  919. .concat(
  920. (Array.isArray(optionsList.value) ? optionsList.value : []).map(
  921. (option) => option?.[props.mapping.text]
  922. )
  923. )
  924. .map((item) =>
  925. item === undefined || item === null ? "" : String(item).trim()
  926. )
  927. .filter(Boolean);
  928. if (!texts.length || typeof document === "undefined") {
  929. autoMinWidth.value = "";
  930. return;
  931. }
  932. const measureNode =
  933. containerRef.value?.querySelector?.(".select-text") ||
  934. containerRef.value;
  935. const computedStyle = measureNode
  936. ? window.getComputedStyle(measureNode)
  937. : null;
  938. const fontSize = computedStyle?.fontSize || "16px";
  939. const fontWeight = computedStyle?.fontWeight || "400";
  940. const fontFamily = computedStyle?.fontFamily || "sans-serif";
  941. const canvas = document.createElement("canvas");
  942. const context = canvas.getContext("2d");
  943. if (!context) return;
  944. context.font = `${fontWeight} ${fontSize} ${fontFamily}`;
  945. const widestText = texts.reduce((maxWidth, text) => {
  946. return Math.max(maxWidth, context.measureText(text).width);
  947. }, 0);
  948. const reservedWidth = 52;
  949. autoMinWidth.value = `${Math.max(
  950. 88,
  951. Math.ceil(widestText + reservedWidth)
  952. )}px`;
  953. };
  954. const maybeAutoSelectFirst = (opts) => {
  955. if (!props.autoSelectFirst) return;
  956. if (!Array.isArray(opts) || opts.length === 0) return;
  957. if (
  958. selectedValue.value !== undefined &&
  959. selectedValue.value !== null &&
  960. selectedValue.value !== ""
  961. ) {
  962. return;
  963. }
  964. const first = opts[0];
  965. if (!first || typeof first !== "object") return;
  966. const value = first[props.mapping.value];
  967. if (value === undefined || value === null || value === "") return;
  968. selectedValue.value = value;
  969. emit("update:modelValue", value);
  970. emit("change", value);
  971. syncInputFromSelection();
  972. };
  973. const loadRemoteOptions = async () => {
  974. if (!needRemoteData.value) return;
  975. if (!window.request || typeof window.request.post !== "function")
  976. return;
  977. remoteLoading.value = true;
  978. try {
  979. const filterObj = parseFilterObj();
  980. const objpParam = {
  981. input: String(canInput.value),
  982. codebook: String(props.cb || ""),
  983. ...filterObj,
  984. };
  985. const postData = {
  986. objectpickerparam: JSON.stringify(objpParam),
  987. objectpickertype: 1,
  988. objectpickersearchAll: 1,
  989. };
  990. // 功能说明:xyByBj 人员码本按班级级联时,补充固定 cascadingLevel 和上级班级值 by xu 2026-03-18
  991. if (String(props.cb || "") === "xyByBj" && filterObj.bjid) {
  992. objpParam.cascadingLevel = "bjid,ryid";
  993. postData.objectpickerparam = JSON.stringify(objpParam);
  994. postData.upperValue = filterObj.bjid;
  995. }
  996. const resp = await window.request.post(
  997. props.url || "/service?ssServ=loadObjpOpt&objectpickerdropdown1=1",
  998. postData,
  999. { loading: false, formData: true }
  1000. );
  1001. const opts = normalizeResultToOptions(
  1002. resp && resp.data ? resp.data : null
  1003. );
  1004. remoteOptions.value = opts;
  1005. emit("loaded", opts);
  1006. maybeAutoSelectFirst(opts);
  1007. if (!isOpen.value) {
  1008. syncInputFromSelection();
  1009. }
  1010. } catch (e) {
  1011. remoteOptions.value = [];
  1012. emit("loaded", []);
  1013. console.error("[ss-select] loadRemoteOptions failed", props.cb, e);
  1014. } finally {
  1015. remoteLoading.value = false;
  1016. }
  1017. };
  1018. const finalLoading = computed(() => {
  1019. return !!props.loading || remoteLoading.value;
  1020. });
  1021. const selectContainerStyle = computed(() => {
  1022. const style = {};
  1023. const widthText = normalizeCssSize(props.width);
  1024. const minWidthText = normalizeCssSize(props.minWidth);
  1025. // 功能说明:ss-select 在 td 等窄容器中限制最大宽度,避免自动 minWidth 把父布局撑开 by xu 2026-03-07
  1026. style.maxWidth = "100%";
  1027. if (hasExplicitWidth.value) {
  1028. style.width = widthText;
  1029. }
  1030. if (minWidthText && minWidthText !== "unset") {
  1031. style.minWidth = `min(${minWidthText}, 100%)`;
  1032. } else if (autoMinWidth.value) {
  1033. style.minWidth = `min(${autoMinWidth.value}, 100%)`;
  1034. }
  1035. return style;
  1036. });
  1037. const displayText = computed(() => {
  1038. if (!selectedValue.value) return props.placeholder;
  1039. const selectedOption = findSelectedOption();
  1040. return selectedOption
  1041. ? getOptionText(selectedOption)
  1042. : props.placeholder;
  1043. });
  1044. const enterInputFilterMode = () => {
  1045. if (!canInput.value) return;
  1046. const selectedOption = findSelectedOption();
  1047. const selectedText = selectedOption
  1048. ? getOptionText(selectedOption)
  1049. : "";
  1050. if (!filterKeyword.value && searchKeyword.value === selectedText) {
  1051. searchKeyword.value = "";
  1052. }
  1053. filterKeyword.value = searchKeyword.value;
  1054. forceShowAll.value = false;
  1055. };
  1056. const openDropdown = (showAll = false) => {
  1057. if (props.disabled) return;
  1058. if (activeSsSelectCloser && activeSsSelectCloser !== closeDropdown) {
  1059. activeSsSelectCloser({ restoreInput: true });
  1060. }
  1061. forceShowAll.value = showAll;
  1062. isOpen.value = true;
  1063. activeSsSelectCloser = closeDropdown;
  1064. };
  1065. const closeDropdown = ({ restoreInput = true } = {}) => {
  1066. isOpen.value = false;
  1067. forceShowAll.value = false;
  1068. if (activeSsSelectCloser === closeDropdown) {
  1069. activeSsSelectCloser = null;
  1070. }
  1071. if (restoreInput) {
  1072. syncInputFromSelection();
  1073. }
  1074. };
  1075. const toggleDropdown = () => {
  1076. if (props.disabled) return;
  1077. if (isOpen.value) {
  1078. closeDropdown();
  1079. } else {
  1080. openDropdown(false);
  1081. }
  1082. };
  1083. const handleContainerClick = () => {
  1084. if (props.disabled || canInput.value) return;
  1085. toggleDropdown();
  1086. };
  1087. const handleTextClick = () => {
  1088. if (props.disabled) return;
  1089. if (!canInput.value) {
  1090. toggleDropdown();
  1091. return;
  1092. }
  1093. enterInputFilterMode();
  1094. openDropdown(false);
  1095. if (inputRef.value) {
  1096. inputRef.value.focus();
  1097. }
  1098. };
  1099. const handleInputFocus = () => {
  1100. if (props.disabled || !canInput.value) return;
  1101. enterInputFilterMode();
  1102. openDropdown(false);
  1103. };
  1104. const handleInput = (event) => {
  1105. const value = event?.target?.value || "";
  1106. searchKeyword.value = value;
  1107. filterKeyword.value = value;
  1108. forceShowAll.value = false;
  1109. isOpen.value = true;
  1110. emit("search", value);
  1111. };
  1112. const handleArrowClick = () => {
  1113. if (props.disabled) return;
  1114. if (!canInput.value) {
  1115. toggleDropdown();
  1116. return;
  1117. }
  1118. filterKeyword.value = "";
  1119. forceShowAll.value = true;
  1120. isOpen.value = true;
  1121. };
  1122. const selectOption = (option) => {
  1123. const value = option[props.mapping.value];
  1124. selectedValue.value = value;
  1125. searchKeyword.value = getOptionText(option);
  1126. filterKeyword.value = "";
  1127. forceShowAll.value = false;
  1128. isOpen.value = false;
  1129. emit("update:modelValue", value);
  1130. emit("change", value);
  1131. };
  1132. const handleClickOutside = (event) => {
  1133. if (!containerRef.value?.contains(event.target)) {
  1134. closeDropdown();
  1135. }
  1136. };
  1137. watch(
  1138. () => props.modelValue,
  1139. (newValue) => {
  1140. selectedValue.value = newValue;
  1141. if (!isOpen.value) {
  1142. syncInputFromSelection();
  1143. }
  1144. },
  1145. { immediate: true }
  1146. );
  1147. watch(
  1148. () => props.options,
  1149. (newVal) => {
  1150. if (needRemoteData.value) return;
  1151. emit("loaded", Array.isArray(newVal) ? newVal : []);
  1152. if (!isOpen.value) {
  1153. syncInputFromSelection();
  1154. }
  1155. }
  1156. );
  1157. watch(
  1158. () => [props.cb, props.url, props.filter],
  1159. () => {
  1160. if (!needRemoteData.value) return;
  1161. loadRemoteOptions();
  1162. }
  1163. );
  1164. watch(
  1165. () => [
  1166. props.placeholder,
  1167. props.width,
  1168. props.minWidth,
  1169. optionsList.value
  1170. .map((option) => option?.[props.mapping.text])
  1171. .join("||"),
  1172. ],
  1173. () => {
  1174. measureStableMinWidth();
  1175. },
  1176. { immediate: true }
  1177. );
  1178. watch(
  1179. () => optionsList.value,
  1180. () => {
  1181. if (!isOpen.value) {
  1182. syncInputFromSelection();
  1183. }
  1184. },
  1185. { deep: true }
  1186. );
  1187. onMounted(() => {
  1188. document.addEventListener("click", handleClickOutside);
  1189. loadRemoteOptions();
  1190. if (!needRemoteData.value && Array.isArray(props.options)) {
  1191. emit("loaded", props.options);
  1192. }
  1193. syncInputFromSelection();
  1194. measureStableMinWidth();
  1195. });
  1196. onBeforeUnmount(() => {
  1197. if (activeSsSelectCloser === closeDropdown) {
  1198. activeSsSelectCloser = null;
  1199. }
  1200. document.removeEventListener("click", handleClickOutside);
  1201. });
  1202. return {
  1203. containerRef,
  1204. inputRef,
  1205. isOpen,
  1206. selectedValue,
  1207. searchKeyword,
  1208. canInput,
  1209. filteredOptions,
  1210. finalLoading,
  1211. displayText,
  1212. selectContainerStyle,
  1213. handleContainerClick,
  1214. handleTextClick,
  1215. handleInputFocus,
  1216. handleInput,
  1217. handleArrowClick,
  1218. selectOption,
  1219. };
  1220. },
  1221. template: `
  1222. <div
  1223. ref="containerRef"
  1224. class="ss-select-container"
  1225. :class="{ open: isOpen }"
  1226. :style="selectContainerStyle"
  1227. @click.stop="handleContainerClick"
  1228. >
  1229. <div class="ss-select" :class="{ disabled: disabled }">
  1230. <div class="select-text" @click.stop="handleTextClick">
  1231. <input
  1232. v-if="canInput"
  1233. ref="inputRef"
  1234. :type="'text'"
  1235. :value="searchKeyword"
  1236. :placeholder="placeholder"
  1237. :disabled="disabled"
  1238. @focus.stop="handleInputFocus"
  1239. @click.stop="handleTextClick"
  1240. @input="handleInput"
  1241. style="width: 100%; border: none; outline: none; background: transparent; color: inherit; font-size: inherit; padding: 0; margin: 0;"
  1242. />
  1243. <span v-else :class="{ placeholder: !selectedValue }">{{ displayText }}</span>
  1244. </div>
  1245. <div class="select-arrow" :class="{ rotate: isOpen }" @click.stop="handleArrowClick">
  1246. <Icon name="icon-xiangxiajiantou" size="32" :color="disabled ? '#ccc' : '#999'"/>
  1247. </div>
  1248. </div>
  1249. <div class="ss-options" v-show="isOpen">
  1250. <div
  1251. v-if="finalLoading"
  1252. class="option-item loading-item"
  1253. >
  1254. <span class="loading-text">加载中...</span>
  1255. </div>
  1256. <div
  1257. v-else-if="filteredOptions.length === 0"
  1258. class="option-item no-options"
  1259. >
  1260. 无选项
  1261. </div>
  1262. <div
  1263. v-else
  1264. v-for="(option, index) in filteredOptions"
  1265. :key="index"
  1266. class="option-item"
  1267. :class="{ selected: option[mapping.value] === selectedValue }"
  1268. @click.stop="selectOption(option)"
  1269. >
  1270. {{ option[mapping.text] }}
  1271. </div>
  1272. </div>
  1273. </div>
  1274. `,
  1275. };
  1276. // ss-bottom 底部按钮组件
  1277. const SsBottom = {
  1278. name: "SsBottom",
  1279. props: {
  1280. // 是否显示审核意见
  1281. showShyj: {
  1282. type: Boolean,
  1283. default: false,
  1284. },
  1285. // 审核意见标题
  1286. shyjTitle: {
  1287. type: String,
  1288. default: "审核意见",
  1289. },
  1290. // 审核意见占位符
  1291. shyjPlaceholder: {
  1292. type: String,
  1293. default: "请输入审核意见",
  1294. },
  1295. divider: {
  1296. type: Boolean,
  1297. default: true,
  1298. },
  1299. // 按钮配置
  1300. buttons: {
  1301. type: Array,
  1302. default: () => [
  1303. { text: "取消", action: "cancel" },
  1304. { text: "保存并提交", action: "submit" },
  1305. ],
  1306. },
  1307. },
  1308. emits: ["button-click", "update:shyjValue"],
  1309. setup(props, { emit }) {
  1310. const reason = ref("");
  1311. const activeButtonIndex = ref(-1);
  1312. // 处理按钮点击
  1313. const handleButtonClick = (button, index) => {
  1314. emit("button-click", {
  1315. action: button.action,
  1316. button: button,
  1317. index: index,
  1318. shyjValue: reason.value, // 传递审核意见
  1319. });
  1320. };
  1321. // 监听审核意见变化
  1322. const handleShyjInput = (event) => {
  1323. const value = event.target.value;
  1324. reason.value = value;
  1325. emit("update:shyjValue", value);
  1326. };
  1327. // 处理按钮按下
  1328. const handleButtonMouseDown = (index) => {
  1329. activeButtonIndex.value = index;
  1330. };
  1331. // 处理按钮释放
  1332. const handleButtonMouseUp = () => {
  1333. activeButtonIndex.value = -1;
  1334. };
  1335. // 处理鼠标离开
  1336. const handleMouseLeave = () => {
  1337. activeButtonIndex.value = -1;
  1338. };
  1339. // 计算按钮样式
  1340. const getButtonStyle = (button) => {
  1341. const styles = {};
  1342. // 如果有背景颜色配置
  1343. if (button.backgroundColor) {
  1344. styles.backgroundColor = button.backgroundColor;
  1345. }
  1346. // 如果有字体颜色配置
  1347. if (button.color) {
  1348. styles.color = button.color;
  1349. }
  1350. return styles;
  1351. };
  1352. // 计算按钮点击样式
  1353. const getButtonActiveStyle = (button) => {
  1354. const styles = {};
  1355. // 如果有点击背景色配置,使用点击背景色
  1356. if (button.clickBgColor) {
  1357. styles.backgroundColor = button.clickBgColor;
  1358. } else if (button.backgroundColor) {
  1359. // 如果没有点击背景色,但有背景色,点击时使用背景色
  1360. styles.backgroundColor = button.backgroundColor;
  1361. }
  1362. // 如果有点击字体色配置,使用点击字体色
  1363. if (button.clickColor) {
  1364. styles.color = button.clickColor;
  1365. } else if (button.color) {
  1366. // 如果没有点击字体色,但有字体色,点击时使用字体色
  1367. styles.color = button.color;
  1368. }
  1369. return styles;
  1370. };
  1371. return {
  1372. reason,
  1373. activeButtonIndex,
  1374. handleButtonClick,
  1375. handleShyjInput,
  1376. handleButtonMouseDown,
  1377. handleButtonMouseUp,
  1378. handleMouseLeave,
  1379. getButtonStyle,
  1380. getButtonActiveStyle,
  1381. };
  1382. },
  1383. template: `
  1384. <div class="ss-bottom">
  1385. <!-- 审核意见区域 -->
  1386. <div v-if="showShyj" class="ss-bottom__opinion">
  1387. <table class="ss-bottom__opinion-table">
  1388. <tr>
  1389. <th class="ss-bottom__opinion-label">{{ shyjTitle }}</th>
  1390. <td class="ss-bottom__opinion-input">
  1391. <ss-input
  1392. :placeholder="shyjPlaceholder"
  1393. v-model="reason"
  1394. @input="handleShyjInput"
  1395. />
  1396. </td>
  1397. </tr>
  1398. </table>
  1399. </div>
  1400. <!-- 按钮区域 -->
  1401. <div class="ss-bottom__buttons" :class="{ 'ss-bottom__buttons--with-border': !showShyj }">
  1402. <template v-for="(button, index) in buttons" :key="index">
  1403. <div
  1404. class="ss-bottom__button"
  1405. :class="{
  1406. 'ss-bottom__button--custom': button.backgroundColor || button.color || button.clickBgColor || button.clickColor,
  1407. 'ss-bottom__button--active': activeButtonIndex === index
  1408. }"
  1409. :style="activeButtonIndex === index ? getButtonActiveStyle(button) : getButtonStyle(button)"
  1410. @click="handleButtonClick(button, index)"
  1411. @mousedown="handleButtonMouseDown(index)"
  1412. @mouseup="handleButtonMouseUp"
  1413. @mouseleave="handleMouseLeave"
  1414. @touchstart="handleButtonMouseDown(index)"
  1415. @touchend="handleButtonMouseUp"
  1416. >
  1417. {{ button.text }}
  1418. </div>
  1419. <!-- 分割线,最后一个按钮不显示 -->
  1420. <div v-if="index < buttons.length - 1 && divider" class="ss-bottom__divider"></div>
  1421. </template>
  1422. </div>
  1423. </div>
  1424. `,
  1425. };
  1426. // ===== SsVerify 审核节点链组件 =====
  1427. const SsVerify = {
  1428. name: "SsVerify",
  1429. props: {
  1430. verifyList: {
  1431. type: Array,
  1432. required: true,
  1433. },
  1434. },
  1435. setup(props) {
  1436. const toggleOpen = (item) => {
  1437. item.open = !item.open;
  1438. // 切换后重新计算连线高度
  1439. setTimeout(() => {
  1440. calculateLineHeight();
  1441. }, 50);
  1442. };
  1443. // 计算连线高度的函数
  1444. const calculateLineHeight = () => {
  1445. const lastOpenGroup = document.querySelector(".group-item-last-open");
  1446. console.log("lastOpenGroup", lastOpenGroup);
  1447. if (lastOpenGroup) {
  1448. // 使用原生JavaScript代替jQuery
  1449. const nodes = lastOpenGroup.querySelectorAll(
  1450. ".verify-node-container"
  1451. );
  1452. if (nodes.length) {
  1453. let totalHeight = 0;
  1454. if (nodes.length === 1) {
  1455. // 只有一个节点时,连线伸到节点的中间位置
  1456. const nodeHeight = nodes[0].offsetHeight;
  1457. const nodeTop = nodes[0].offsetTop;
  1458. totalHeight = nodeTop + nodeHeight / 2 - 15; // 减去圆点半径5px
  1459. } else {
  1460. // 多个节点时,连线延伸到最后一个节点的中间位置
  1461. const lastNode = nodes[nodes.length - 1];
  1462. const lastNodeTop = lastNode.offsetTop;
  1463. const lastNodeHeight = lastNode.offsetHeight;
  1464. totalHeight = lastNodeTop + lastNodeHeight / 2 - 15; // 减去圆点半径5px
  1465. }
  1466. console.log("节点信息:", {
  1467. 节点总数: nodes.length,
  1468. 计算后的高度: totalHeight,
  1469. 最后节点top: nodes[nodes.length - 1]?.offsetTop,
  1470. 最后节点高度: nodes[nodes.length - 1]?.offsetHeight,
  1471. });
  1472. lastOpenGroup.style.setProperty(
  1473. "--group-line-height",
  1474. `${totalHeight}px`
  1475. );
  1476. }
  1477. }
  1478. };
  1479. onMounted(() => {
  1480. setTimeout(() => {
  1481. calculateLineHeight();
  1482. }, 100);
  1483. });
  1484. return {
  1485. toggleOpen,
  1486. };
  1487. },
  1488. render() {
  1489. const { h } = Vue;
  1490. return h(
  1491. "div",
  1492. { class: "verify-nodes" },
  1493. this.verifyList.map((item, i) =>
  1494. h(
  1495. "div",
  1496. {
  1497. key: i,
  1498. class: {
  1499. "group-item": true,
  1500. "group-item-last-open":
  1501. i === this.verifyList.length - 1 && item.open,
  1502. },
  1503. },
  1504. [
  1505. h(
  1506. "div",
  1507. {
  1508. class: "group-item-title",
  1509. onClick: () => this.toggleOpen(item),
  1510. },
  1511. [
  1512. h("div", { class: "icon" }, [
  1513. h("i", {
  1514. class: item.open
  1515. ? "common-icon-folder-open common-icon"
  1516. : "common-icon-folder-close common-icon",
  1517. }),
  1518. h(
  1519. "div",
  1520. {
  1521. class: "num",
  1522. style: { top: item.open ? "60%" : "55%" },
  1523. },
  1524. item.children?.length || 0
  1525. ),
  1526. ]),
  1527. h("div", { class: "name" }, item.groupName),
  1528. ]
  1529. ),
  1530. item.open && item.children?.length > 0
  1531. ? h(
  1532. "div",
  1533. { class: "group-item-children" },
  1534. item.children.map((citem, j) =>
  1535. h(SsVerifyNode, {
  1536. key: j,
  1537. item: citem,
  1538. // isGroup: i + 1 !== this.verifyList.length,
  1539. isGroup: true,
  1540. })
  1541. )
  1542. )
  1543. : null,
  1544. ]
  1545. )
  1546. )
  1547. );
  1548. },
  1549. };
  1550. // ===== SsVerifyNode 审核节点组件 =====
  1551. const SsVerifyNode = {
  1552. name: "SsVerifyNode",
  1553. props: {
  1554. item: {
  1555. type: Object,
  1556. required: true,
  1557. },
  1558. isGroup: {
  1559. type: Boolean,
  1560. default: false,
  1561. },
  1562. },
  1563. render() {
  1564. const { h } = Vue;
  1565. return h("div", { class: "verify-node-container" }, [
  1566. h("div", { class: "info" }, [
  1567. h("div", { class: "avatar" }, [
  1568. h("img", {
  1569. src: this.item.thumb,
  1570. style: {
  1571. width: "50px",
  1572. height: "50px",
  1573. borderRadius: "50%",
  1574. },
  1575. }),
  1576. ]),
  1577. h("div", { class: "desc" }, [
  1578. h("div", this.item.name),
  1579. h("div", this.item.role),
  1580. ]),
  1581. h("div", { class: "link" }, [
  1582. h("div", [
  1583. this.item.video
  1584. ? h("i", { class: "common-icon-video common-icon" })
  1585. : null,
  1586. this.item.link
  1587. ? h("i", { class: "common-icon-paper-clip common-icon" })
  1588. : null,
  1589. ]),
  1590. ]),
  1591. ]),
  1592. h(
  1593. "div",
  1594. {
  1595. class: {
  1596. description: true,
  1597. link: this.isGroup,
  1598. },
  1599. attrs: { "data-num": "3" },
  1600. },
  1601. [h("div", this.item.description)]
  1602. ),
  1603. h("div", { class: "time" }, this.item.time),
  1604. ]);
  1605. },
  1606. };
  1607. // ===== SsOnoffButton 开关按钮 =====
  1608. const SsOnoffButton = {
  1609. name: "SsOnoffButton",
  1610. props: {
  1611. // 字段名称,用于表单校验
  1612. name: { type: String, required: true },
  1613. // 显示标签
  1614. label: { type: String, required: true },
  1615. // 按钮的值
  1616. value: { type: [String, Number], required: true },
  1617. // 宽度设置
  1618. width: { type: String, default: "" },
  1619. // v-model 绑定的值
  1620. modelValue: { type: [String, Number, Array], default: "" },
  1621. // 是否多选模式
  1622. multiple: { type: Boolean, default: false },
  1623. // 是否禁用
  1624. disabled: { type: Boolean, default: false },
  1625. },
  1626. emits: ["update:modelValue", "change"],
  1627. setup(props, { emit }) {
  1628. // 解析 modelValue,支持逗号分隔的字符串和数组
  1629. const parseModelValue = (val) => {
  1630. if (!val) return [];
  1631. // 如果是数组,直接返回字符串数组
  1632. if (Array.isArray(val)) {
  1633. return val.map((v) => v.toString());
  1634. }
  1635. // 如果是字符串,按逗号分割
  1636. const cleanValue = val.toString().replace(/^,+/, ""); // 去掉开头的逗号
  1637. if (cleanValue.includes("|")) {
  1638. return cleanValue.split("|");
  1639. }
  1640. if (cleanValue.includes(",")) {
  1641. return cleanValue.split(",");
  1642. }
  1643. return cleanValue ? [cleanValue] : [];
  1644. };
  1645. // 判断当前按钮是否选中
  1646. const isChecked = computed(() => {
  1647. if (props.multiple) {
  1648. const currentValue = parseModelValue(props.modelValue);
  1649. return currentValue.includes(props.value.toString());
  1650. }
  1651. return props.modelValue === props.value;
  1652. });
  1653. // 切换选中状态
  1654. const toggleSelect = () => {
  1655. // 如果禁用,不执行任何操作
  1656. if (props.disabled) return;
  1657. if (props.multiple) {
  1658. // 多选模式
  1659. const currentValue = parseModelValue(props.modelValue);
  1660. const index = currentValue.indexOf(props.value.toString());
  1661. let newValue;
  1662. if (index === -1) {
  1663. // 添加选项
  1664. newValue = [...currentValue, props.value.toString()];
  1665. } else {
  1666. // 移除选项
  1667. newValue = currentValue.filter((v) => v !== props.value.toString());
  1668. }
  1669. // 发送更新事件,使用逗号分隔的字符串格式
  1670. const emitValue = newValue.join(",");
  1671. emit("update:modelValue", emitValue);
  1672. emit("change", emitValue, newValue);
  1673. } else {
  1674. // 单选模式
  1675. emit("update:modelValue", props.value);
  1676. emit("change", props.value);
  1677. }
  1678. };
  1679. return { isChecked, toggleSelect };
  1680. },
  1681. template: `
  1682. <div class="ss-onoff-button" :class="{ checked: isChecked, disabled: disabled }" @click="toggleSelect">
  1683. <span class="button-label">{{ label }}</span>
  1684. <div class="button-mark">
  1685. <span class="form-icon" :class="isChecked ? 'form-icon-onoffbutton-checked' : 'form-icon-onoffbutton-unchecked'"></span>
  1686. </div>
  1687. </div>
  1688. `,
  1689. };
  1690. // ===== SsDatetimePicker 日期时间选择(使用 Vant 4) =====
  1691. const SsDatetimePicker = {
  1692. name: "SsDatetimePicker",
  1693. props: {
  1694. mode: { type: String, default: "date" }, // date | time | datetime
  1695. placeholder: { type: String, default: "请选择日期" },
  1696. modelValue: { type: String, default: "" },
  1697. minDate: { type: String, default: "" },
  1698. maxDate: { type: String, default: "" },
  1699. // 字段名称 - 用于ssVm校验
  1700. name: { type: String, default: "" },
  1701. // 是否禁用
  1702. disabled: { type: Boolean, default: false },
  1703. },
  1704. emits: [
  1705. "update:modelValue",
  1706. "change",
  1707. "confirm",
  1708. "cancel",
  1709. "open",
  1710. "close",
  1711. ],
  1712. setup(props, { emit }) {
  1713. const showPicker = ref(false);
  1714. const showTimePicker = ref(false);
  1715. const currentStep = ref("date"); // 'date' | 'time'
  1716. // 功能说明:统一在组件层处理 iframe 场景底部按钮显隐,避免每个页面重复绑定 by xu 2026-02-28
  1717. const notifyParentBottomVisible = (visible) => {
  1718. try {
  1719. const fn = window.parent && window.parent.__mpObjInpSetBottomVisible;
  1720. if (typeof fn === "function") fn(visible !== false);
  1721. } catch (_) {}
  1722. };
  1723. // 功能说明:监听弹层显隐,点遮罩/取消关闭时也恢复父层底部按钮 by xu 2026-03-01
  1724. watch(
  1725. [showPicker, showTimePicker],
  1726. ([dateOpen, timeOpen], [prevDateOpen, prevTimeOpen]) => {
  1727. const hasOpen = !!(dateOpen || timeOpen);
  1728. const hadOpen = !!(prevDateOpen || prevTimeOpen);
  1729. if (!hadOpen && hasOpen) {
  1730. emit("open");
  1731. notifyParentBottomVisible(false);
  1732. return;
  1733. }
  1734. if (hadOpen && !hasOpen) {
  1735. emit("close");
  1736. notifyParentBottomVisible(true);
  1737. }
  1738. }
  1739. );
  1740. // Vant DatePicker 需要数组格式 [year, month, day]
  1741. const currentDateArray = ref([]);
  1742. const currentTimeArray = ref(["12", "00"]); // [hour, minute]
  1743. const tempDateStr = ref(""); // 临时存储选择的日期
  1744. // 格式化显示文本
  1745. const displayText = computed(() => {
  1746. if (!props.modelValue) return props.placeholder;
  1747. try {
  1748. const d = new Date(props.modelValue);
  1749. if (isNaN(d.getTime())) return props.modelValue;
  1750. const year = d.getFullYear();
  1751. const month = String(d.getMonth() + 1).padStart(2, "0");
  1752. const day = String(d.getDate()).padStart(2, "0");
  1753. const hours = String(d.getHours()).padStart(2, "0");
  1754. const minutes = String(d.getMinutes()).padStart(2, "0");
  1755. if (props.mode === "time") {
  1756. return `${hours}:${minutes}`;
  1757. } else if (props.mode === "datetime") {
  1758. return `${year}-${month}-${day} ${hours}:${minutes}`;
  1759. }
  1760. return `${year}-${month}-${day}`;
  1761. } catch (e) {
  1762. return props.modelValue;
  1763. }
  1764. });
  1765. // 监听 modelValue 变化,转换为数组格式
  1766. watch(
  1767. () => props.modelValue,
  1768. (newVal) => {
  1769. console.log("📅 modelValue 变化:", newVal);
  1770. if (newVal) {
  1771. try {
  1772. const d = new Date(newVal);
  1773. if (!isNaN(d.getTime())) {
  1774. currentDateArray.value = [
  1775. d.getFullYear(),
  1776. d.getMonth() + 1,
  1777. d.getDate(),
  1778. ];
  1779. console.log("📅 转换为数组:", currentDateArray.value);
  1780. }
  1781. } catch (e) {
  1782. console.warn("Invalid date:", newVal);
  1783. }
  1784. } else {
  1785. const today = new Date();
  1786. currentDateArray.value = [
  1787. today.getFullYear(),
  1788. today.getMonth() + 1,
  1789. today.getDate(),
  1790. ];
  1791. }
  1792. },
  1793. { immediate: true }
  1794. );
  1795. // 确认选择 - 根据模式处理不同的数据
  1796. const onConfirm = (value) => {
  1797. console.log(
  1798. "📅 Vant Picker confirm 原始值:",
  1799. value,
  1800. "mode:",
  1801. props.mode
  1802. );
  1803. try {
  1804. // Vant 返回的是对象,包含 selectedValues 数组
  1805. const selectedValues = value.selectedValues || value;
  1806. console.log("📅 selectedValues:", selectedValues);
  1807. if (props.mode === "time") {
  1808. // 时间模式:处理时分
  1809. if (Array.isArray(selectedValues) && selectedValues.length >= 2) {
  1810. const [hour, minute] = selectedValues;
  1811. const timeStr = `${hour.padStart(2, "0")}:${minute.padStart(
  1812. 2,
  1813. "0"
  1814. )}`;
  1815. console.log("🕐 转换后的时间字符串:", timeStr);
  1816. emit("update:modelValue", timeStr);
  1817. emit("change", timeStr);
  1818. emit("confirm", timeStr);
  1819. emit("close");
  1820. notifyParentBottomVisible(true);
  1821. showPicker.value = false;
  1822. }
  1823. } else if (
  1824. Array.isArray(selectedValues) &&
  1825. selectedValues.length >= 3
  1826. ) {
  1827. // 日期模式:处理年月日
  1828. const [year, month, day] = selectedValues;
  1829. const dateStr = `${year}-${month.padStart(2, "0")}-${day.padStart(
  1830. 2,
  1831. "0"
  1832. )}`;
  1833. if (props.mode === "datetime") {
  1834. // datetime 模式:先存储日期,然后打开时间选择器
  1835. tempDateStr.value = dateStr;
  1836. showPicker.value = false;
  1837. showTimePicker.value = true;
  1838. currentStep.value = "time";
  1839. } else {
  1840. // date 模式:直接完成
  1841. emit("update:modelValue", dateStr);
  1842. emit("change", dateStr);
  1843. emit("confirm", dateStr);
  1844. emit("close");
  1845. notifyParentBottomVisible(true);
  1846. showPicker.value = false;
  1847. }
  1848. }
  1849. } catch (e) {
  1850. console.error("Picker conversion error:", e);
  1851. }
  1852. };
  1853. // 时间选择确认
  1854. const onTimeConfirm = (value) => {
  1855. try {
  1856. const selectedValues = value.selectedValues || value;
  1857. if (Array.isArray(selectedValues) && selectedValues.length >= 2) {
  1858. const [hour, minute] = selectedValues;
  1859. const datetimeStr = `${tempDateStr.value} ${hour.padStart(
  1860. 2,
  1861. "0"
  1862. )}:${minute.padStart(2, "0")}`;
  1863. emit("update:modelValue", datetimeStr);
  1864. emit("change", datetimeStr);
  1865. emit("confirm", datetimeStr);
  1866. emit("close");
  1867. notifyParentBottomVisible(true);
  1868. }
  1869. } catch (e) {
  1870. console.error("Time conversion error:", e);
  1871. }
  1872. showTimePicker.value = false;
  1873. currentStep.value = "date";
  1874. };
  1875. // 取消选择
  1876. const onCancel = () => {
  1877. emit("cancel");
  1878. showPicker.value = false;
  1879. };
  1880. const onTimeCancel = () => {
  1881. emit("cancel");
  1882. showTimePicker.value = false;
  1883. };
  1884. // 打开选择器
  1885. const openPicker = () => {
  1886. // 如果禁用,不打开选择器
  1887. if (props.disabled) return;
  1888. showPicker.value = true;
  1889. };
  1890. // 计算最小最大日期
  1891. const minDateObj = computed(() => {
  1892. return props.minDate ? new Date(props.minDate) : undefined;
  1893. });
  1894. const maxDateObj = computed(() => {
  1895. return props.maxDate ? new Date(props.maxDate) : undefined;
  1896. });
  1897. return {
  1898. showPicker,
  1899. showTimePicker,
  1900. currentDateArray,
  1901. currentTimeArray,
  1902. displayText,
  1903. openPicker,
  1904. onConfirm,
  1905. onTimeConfirm,
  1906. onTimeCancel,
  1907. onCancel,
  1908. minDateObj,
  1909. maxDateObj,
  1910. };
  1911. },
  1912. template: `
  1913. <div class="ss-datetime-picker ss-mobile-component" :class="{ disabled: disabled }">
  1914. <!-- 隐藏的input用于ssVm校验 -->
  1915. <input type="hidden" :name="name" :value="modelValue" />
  1916. <div class="datetime-picker-display" @click="openPicker">
  1917. <span class="datetime-picker-value" :class="{ placeholder: !modelValue }">{{ displayText }}</span>
  1918. </div>
  1919. <!-- 日期选择器 -->
  1920. <van-popup v-model:show="showPicker" position="bottom" :style="{ zIndex: 10000 }">
  1921. <van-date-picker
  1922. v-if="mode === 'date' || mode === 'datetime'"
  1923. v-model="currentDateArray"
  1924. :min-date="minDateObj"
  1925. :max-date="maxDateObj"
  1926. @confirm="onConfirm"
  1927. @cancel="onCancel"
  1928. title="选择日期"
  1929. />
  1930. <van-time-picker
  1931. v-if="mode === 'time'"
  1932. v-model="currentTimeArray"
  1933. @confirm="onConfirm"
  1934. @cancel="onCancel"
  1935. title="选择时间"
  1936. />
  1937. </van-popup>
  1938. <!-- 时间选择器(datetime 模式的第二步) -->
  1939. <van-popup v-model:show="showTimePicker" position="bottom" :style="{ zIndex: 10000 }">
  1940. <van-time-picker
  1941. v-model="currentTimeArray"
  1942. @confirm="onTimeConfirm"
  1943. @cancel="onTimeCancel"
  1944. title="选择时间"
  1945. />
  1946. </van-popup>
  1947. </div>
  1948. `,
  1949. };
  1950. const SsConfirm = {
  1951. name: "SsConfirm",
  1952. props: {
  1953. modelValue: { type: Boolean, default: false },
  1954. title: { type: String, default: "确认" },
  1955. content: { type: String, default: "" },
  1956. maskClosable: { type: Boolean, default: true },
  1957. },
  1958. emits: ["update:modelValue", "confirm", "cancel", "close"],
  1959. setup(props, { emit }) {
  1960. // 监听弹窗显示状态,控制 body 滚动
  1961. watch(
  1962. () => props.modelValue,
  1963. (newVal) => {
  1964. console.log("🔔 SsConfirm modelValue 变化:", newVal);
  1965. if (newVal) {
  1966. document.body.classList.add("modal-open");
  1967. } else {
  1968. document.body.classList.remove("modal-open");
  1969. }
  1970. },
  1971. { immediate: true }
  1972. ); // 添加 immediate 选项
  1973. const close = () => {
  1974. console.log("🚪 关闭确认弹窗");
  1975. emit("update:modelValue", false);
  1976. emit("close");
  1977. };
  1978. const onMask = () => {
  1979. console.log("👆 点击了遮罩层");
  1980. if (props.maskClosable) close();
  1981. };
  1982. const onCancel = () => {
  1983. console.log("❌ 点击了取消按钮");
  1984. emit("cancel");
  1985. close();
  1986. };
  1987. const onConfirm = () => {
  1988. console.log("✅ 点击了确认按钮,触发 confirm 事件");
  1989. emit("confirm");
  1990. close();
  1991. };
  1992. return { onMask, onCancel, onConfirm };
  1993. },
  1994. template: `
  1995. <div v-if="modelValue" class="ss-confirm">
  1996. <div class="confirm-mask" @click="onMask"></div>
  1997. <div class="confirm-content">
  1998. <div class="confirm-header" v-if="title">
  1999. <div class="header-title">{{ title }}</div>
  2000. </div>
  2001. <div class="header-line" v-if="title"></div>
  2002. <div class="confirm-body">
  2003. <div v-if="content" class="confirm-content-text" v-html="content"></div>
  2004. <div class="confirm-slot-content"><slot /></div>
  2005. </div>
  2006. <div class="confirm-bottom">
  2007. <button class="confirm-btn confirm-btn-cancel" @click.stop="onCancel">取消</button>
  2008. <button class="confirm-btn confirm-btn-confirm" @click.stop="onConfirm">确认</button>
  2009. </div>
  2010. </div>
  2011. </div>
  2012. `,
  2013. };
  2014. // ===== SsImageCropper 纯裁剪组件 =====
  2015. const SsImageCropper = {
  2016. name: "SsImageCropper",
  2017. props: {
  2018. // 是否显示裁剪器
  2019. show: { type: Boolean, default: false },
  2020. // 图片源(base64 或 URL)
  2021. src: { type: String, required: true },
  2022. // 图片形状:circle圆形 | square方形
  2023. shape: { type: String, required: true },
  2024. // 裁剪比例(宽/高)
  2025. aspectRatio: { type: Number, default: 1 },
  2026. // 输出图片宽度
  2027. outputWidth: { type: Number, default: 300 },
  2028. // 输出图片高度
  2029. outputHeight: { type: Number, default: 300 },
  2030. },
  2031. emits: ["update:show", "confirm", "cancel"],
  2032. setup(props, { emit }) {
  2033. const cropperInstance = ref(null);
  2034. // 监听 show 变化,初始化或销毁 Cropper
  2035. watch(
  2036. () => props.show,
  2037. (newVal) => {
  2038. if (newVal) {
  2039. // 等待 DOM 更新后初始化
  2040. Vue.nextTick(() => {
  2041. initCropper().catch((error) => {
  2042. console.error("图片裁剪组件初始化失败:", error);
  2043. });
  2044. });
  2045. } else {
  2046. destroyCropper();
  2047. }
  2048. }
  2049. );
  2050. // 监听 src 变化,重新初始化 Cropper
  2051. watch(
  2052. () => props.src,
  2053. () => {
  2054. if (props.show) {
  2055. Vue.nextTick(() => {
  2056. initCropper().catch((error) => {
  2057. console.error("图片裁剪组件重新初始化失败:", error);
  2058. });
  2059. });
  2060. }
  2061. }
  2062. );
  2063. // 初始化 Cropper
  2064. const initCropper = async () => {
  2065. if (!window.Cropper) {
  2066. await ensureOptionalAssets("cropper");
  2067. }
  2068. const imageElement = document.getElementById("ss-image-cropper-img");
  2069. if (!imageElement || !window.Cropper) return;
  2070. // 销毁旧实例
  2071. destroyCropper();
  2072. // 根据 shape 属性添加类名
  2073. const container = document.querySelector(".ss-image-cropper-container");
  2074. if (container) {
  2075. if (props.shape === "circle") {
  2076. container.classList.add("crop-shape-circle");
  2077. container.classList.remove("crop-shape-square");
  2078. } else {
  2079. container.classList.add("crop-shape-square");
  2080. container.classList.remove("crop-shape-circle");
  2081. }
  2082. }
  2083. cropperInstance.value = new window.Cropper(imageElement, {
  2084. aspectRatio: props.aspectRatio,
  2085. viewMode: 1,
  2086. dragMode: "move",
  2087. autoCropArea: 0.8,
  2088. restore: false,
  2089. guides: false, // 关闭辅助线
  2090. center: false, // 关闭中心指示器
  2091. highlight: false,
  2092. cropBoxMovable: true,
  2093. cropBoxResizable: true,
  2094. toggleDragModeOnDblclick: false,
  2095. minContainerWidth: window.innerWidth,
  2096. minContainerHeight: window.innerHeight - 50,
  2097. });
  2098. };
  2099. // 销毁 Cropper
  2100. const destroyCropper = () => {
  2101. if (cropperInstance.value) {
  2102. cropperInstance.value.destroy();
  2103. cropperInstance.value = null;
  2104. }
  2105. };
  2106. // 取消裁剪
  2107. const handleCancel = () => {
  2108. emit("update:show", false);
  2109. emit("cancel");
  2110. };
  2111. // 确认裁剪
  2112. const handleConfirm = () => {
  2113. if (!cropperInstance.value) return;
  2114. const canvas = cropperInstance.value.getCroppedCanvas({
  2115. width: props.outputWidth,
  2116. height: props.outputHeight,
  2117. imageSmoothingEnabled: true,
  2118. imageSmoothingQuality: "high",
  2119. fillColor: "#fff",
  2120. });
  2121. canvas.toBlob(
  2122. (blob) => {
  2123. emit("update:show", false);
  2124. emit("confirm", blob);
  2125. },
  2126. "image/jpeg",
  2127. 0.9
  2128. );
  2129. };
  2130. // 处理底部按钮事件
  2131. const handleCropAction = (data) => {
  2132. if (data.action === "cancel") {
  2133. handleCancel();
  2134. } else if (data.action === "confirm") {
  2135. handleConfirm();
  2136. }
  2137. };
  2138. return {
  2139. handleCropAction,
  2140. };
  2141. },
  2142. template: `
  2143. <div v-if="show" class="ss-image-cropper-container">
  2144. <!-- 左上角尺寸显示 -->
  2145. <div class="crop-size-display">
  2146. 长: {{ outputWidth }}px<br>宽: {{ outputHeight }}px
  2147. </div>
  2148. <div class="ss-crop-image-container">
  2149. <img id="ss-image-cropper-img" :src="src" />
  2150. </div>
  2151. <!-- 使用 ss-bottom 组件 -->
  2152. <ss-bottom
  2153. :show-shyj="false"
  2154. :buttons="[
  2155. { text: '取消', action: 'cancel' },
  2156. { text: '保存并提交', action: 'confirm' }
  2157. ]"
  2158. @button-click="handleCropAction"
  2159. />
  2160. </div>
  2161. `,
  2162. };
  2163. // ===== SsUploadImage 图片上传裁剪组件(支持单图/多图) =====
  2164. const SsUploadImage = {
  2165. name: "SsUploadImage",
  2166. props: {
  2167. // v-model 绑定的值(单图:String,多图:Array)
  2168. modelValue: { type: [String, Array], default: "" },
  2169. // 最大上传数量(默认1张,多图时设置大于1)
  2170. max: { type: Number, default: 1 },
  2171. // 是否禁用
  2172. disabled: { type: Boolean, default: false },
  2173. // 图片宽度(像素) - 必填
  2174. width: { type: [Number, String], required: true },
  2175. // 图片高度(像素) - 必填
  2176. height: { type: [Number, String], required: true },
  2177. // 图片形状:circle圆形 | square方形 - 必填
  2178. shape: { type: String, required: true },
  2179. // 裁剪比例(宽/高)
  2180. aspectRatio: { type: Number, default: undefined },
  2181. // 输出图片宽度
  2182. outputWidth: { type: Number, default: 300 },
  2183. // 输出图片高度
  2184. outputHeight: { type: Number, default: 300 },
  2185. },
  2186. emits: ["update:modelValue", "updated"],
  2187. setup(props, { emit }) {
  2188. const showCropper = ref(false);
  2189. const tempImageSrc = ref("");
  2190. // 图片列表(统一用数组管理)
  2191. const imageList = ref([]);
  2192. // 监听 modelValue 变化,同步到 imageList
  2193. watch(
  2194. () => props.modelValue,
  2195. (newVal) => {
  2196. if (props.max === 1) {
  2197. // 单图模式
  2198. imageList.value = newVal ? [newVal] : [];
  2199. } else {
  2200. // 多图模式
  2201. imageList.value = Array.isArray(newVal)
  2202. ? [...newVal]
  2203. : newVal
  2204. ? [newVal]
  2205. : [];
  2206. }
  2207. },
  2208. { immediate: true }
  2209. );
  2210. // 是否可以继续添加图片
  2211. const canAddMore = computed(() => {
  2212. return imageList.value.length < props.max;
  2213. });
  2214. // 容器样式
  2215. const itemStyle = computed(() => ({
  2216. width:
  2217. typeof props.width === "number" ? `${props.width}px` : props.width,
  2218. height:
  2219. typeof props.height === "number" ? `${props.height}px` : props.height,
  2220. borderRadius: props.shape === "circle" ? "50%" : "8px",
  2221. }));
  2222. // 获取图片 URL(用于显示)
  2223. const getImageUrl = (path) => {
  2224. if (!path) return "/static/images/yishuzhao_nv.svg";
  2225. if (path.startsWith("http") || path.startsWith("blob:")) {
  2226. return path;
  2227. }
  2228. return window.SS.utils?.getImageUrl?.(path) || path;
  2229. };
  2230. // 选择图片
  2231. const selectImage = () => {
  2232. if (props.disabled || !canAddMore.value) return;
  2233. const input = document.createElement("input");
  2234. input.type = "file";
  2235. input.accept = "image/*";
  2236. input.onchange = (e) => {
  2237. const file = e.target.files[0];
  2238. if (file) {
  2239. const reader = new FileReader();
  2240. reader.onload = (event) => {
  2241. tempImageSrc.value = event.target.result;
  2242. showCropper.value = true;
  2243. };
  2244. reader.readAsDataURL(file);
  2245. }
  2246. };
  2247. input.click();
  2248. };
  2249. // 删除图片
  2250. const deleteImage = (index) => {
  2251. const newList = imageList.value.filter((_, i) => i !== index);
  2252. updateModelValue(newList);
  2253. };
  2254. // 确认裁剪
  2255. const handleCropConfirm = async (blob) => {
  2256. try {
  2257. const serverPath = await uploadFile(blob, "image", "image.jpg");
  2258. const newList = [...imageList.value, serverPath];
  2259. updateModelValue(newList);
  2260. emit("updated", serverPath);
  2261. } catch (error) {
  2262. console.error("上传失败:", error);
  2263. }
  2264. };
  2265. // 取消裁剪
  2266. const handleCropCancel = () => {
  2267. tempImageSrc.value = "";
  2268. };
  2269. // 更新 modelValue
  2270. const updateModelValue = (list) => {
  2271. if (props.max === 1) {
  2272. // 单图模式:返回 String
  2273. emit("update:modelValue", list[0] || "");
  2274. } else {
  2275. // 多图模式:返回 Array
  2276. emit("update:modelValue", list);
  2277. }
  2278. };
  2279. return {
  2280. imageList,
  2281. canAddMore,
  2282. itemStyle,
  2283. showCropper,
  2284. tempImageSrc,
  2285. getImageUrl,
  2286. selectImage,
  2287. deleteImage,
  2288. handleCropConfirm,
  2289. handleCropCancel,
  2290. };
  2291. },
  2292. template: `
  2293. <div class="ss-upload-image-multi">
  2294. <!-- 图片列表 -->
  2295. <div class="image-list">
  2296. <!-- 已上传的图片 -->
  2297. <div
  2298. v-for="(img, index) in imageList"
  2299. :key="index"
  2300. class="image-item"
  2301. :style="itemStyle"
  2302. >
  2303. <img :src="getImageUrl(img)" class="image-display" />
  2304. <!-- 删除按钮 -->
  2305. <div v-if="!disabled" class="image-delete" @click.stop="deleteImage(index)">
  2306. <Icon name="icon-guanbi" size="32" color="#fff" />
  2307. </div>
  2308. </div>
  2309. <!-- 添加按钮 -->
  2310. <div
  2311. v-if="canAddMore && !disabled"
  2312. class="image-item image-add"
  2313. :style="itemStyle"
  2314. @click="selectImage"
  2315. >
  2316. <Icon name="icon-xiangji" size="48" color="#ccc" />
  2317. <div class="add-text">{{ imageList.length }}/{{ max }}</div>
  2318. </div>
  2319. </div>
  2320. <!-- 裁剪组件 -->
  2321. <ss-image-cropper
  2322. v-model:show="showCropper"
  2323. :src="tempImageSrc"
  2324. :shape="shape"
  2325. :aspect-ratio="aspectRatio"
  2326. :output-width="outputWidth"
  2327. :output-height="outputHeight"
  2328. @confirm="handleCropConfirm"
  2329. @cancel="handleCropCancel"
  2330. />
  2331. </div>
  2332. `,
  2333. };
  2334. // ===== SsCarCard 车辆卡片组件 =====
  2335. const SsCarCard = {
  2336. name: "SsCarCard",
  2337. props: {
  2338. // 车辆数据
  2339. carData: {
  2340. type: Object,
  2341. default: () => ({}),
  2342. },
  2343. // 车辆状态:'available' | 'reserved' | 'disabled'
  2344. status: {
  2345. type: String,
  2346. default: "available",
  2347. validator: (value) =>
  2348. ["available", "reserved", "disabled"].includes(value),
  2349. },
  2350. },
  2351. emits: ["click", "select"],
  2352. setup(props, { emit }) {
  2353. // 计算状态样式类
  2354. const statusClass = computed(() => {
  2355. return `status-${props.status}`;
  2356. });
  2357. // 获取图片URL
  2358. const getImageUrl = (path) => {
  2359. if (!path) return "/static/images/default-car.png";
  2360. if (path.startsWith("http") || path.startsWith("blob:")) {
  2361. return path;
  2362. }
  2363. return window.SS.utils?.getImageUrl?.(path) || path;
  2364. };
  2365. // 处理卡片点击
  2366. const handleCardClick = () => {
  2367. if (props.status === "disabled") {
  2368. return; // 禁用状态不响应点击
  2369. }
  2370. emit("click", props.carData);
  2371. emit("select", props.carData);
  2372. };
  2373. return {
  2374. statusClass,
  2375. getImageUrl,
  2376. handleCardClick,
  2377. };
  2378. },
  2379. template: `
  2380. <div class="car-card" :class="statusClass" @click="handleCardClick">
  2381. <!-- 第一行:车辆名称 -->
  2382. <div class="car-title">
  2383. {{ carData.name || '别克GL8' }}
  2384. </div>
  2385. <!-- 第二行:左右结构 -->
  2386. <div class="car-info">
  2387. <!-- 左边:车辆图片 -->
  2388. <div class="car-image-container">
  2389. <img class="car-image" :src="getImageUrl(carData.image)" />
  2390. </div>
  2391. <!-- 右边:车辆信息 -->
  2392. <div class="car-details">
  2393. <div class="detail-item car-name" v-if="carData.wph">
  2394. {{ carData.wph }}
  2395. </div>
  2396. <div class="detail-item seats" v-for="(wp, index) in carData.wpcsList" :key="index">
  2397. {{ wp.mc }} : {{ wp.sz || wp.zf }}
  2398. </div>
  2399. <div class="detail-item car-type">
  2400. {{ carData.type || '商务车' }}
  2401. </div>
  2402. </div>
  2403. </div>
  2404. </div>
  2405. `,
  2406. };
  2407. // ===== SsSubTab 移动端Tab组件 =====
  2408. const SsSubTab = {
  2409. name: "SsSubTab",
  2410. props: {
  2411. // Tab列表数据
  2412. tabList: {
  2413. type: Array,
  2414. required: true,
  2415. },
  2416. // 当前激活的Tab索引
  2417. activeIndex: {
  2418. type: Number,
  2419. default: 0,
  2420. },
  2421. // 基础URL参数(会传递给每个iframe)
  2422. baseParams: {
  2423. type: Object,
  2424. default: () => ({}),
  2425. },
  2426. },
  2427. emits: ["tab-change"],
  2428. setup(props, { emit }) {
  2429. const currentTab = ref(props.activeIndex);
  2430. const currentTabUrl = ref("");
  2431. // 加载Tab对应的URL
  2432. const loadTabUrl = (index) => {
  2433. const tab = props.tabList[index];
  2434. if (!tab || !tab.dest) return;
  2435. // 构建iframe URL:mp_ + dest + .html
  2436. const fileName = `mp_${tab.dest}.html`;
  2437. // 构建完整URL,包含所有参数
  2438. const tabService =
  2439. tab.service ||
  2440. tab.servName ||
  2441. props.baseParams.service ||
  2442. props.baseParams.ssServ ||
  2443. "";
  2444. const tabDest =
  2445. tab.dest || props.baseParams.dest || props.baseParams.ssDest || "";
  2446. const tabParam =
  2447. tab.param ||
  2448. tab.parm ||
  2449. props.baseParams.param ||
  2450. props.baseParams.parm ||
  2451. "";
  2452. const params = new URLSearchParams({
  2453. ...props.baseParams,
  2454. service: tabService,
  2455. dest: tabDest,
  2456. ssServ: tabService,
  2457. ssDest: tabDest,
  2458. param: tabParam,
  2459. parm: tabParam,
  2460. });
  2461. currentTabUrl.value = `/page/${fileName}?${params.toString()}`;
  2462. console.log(
  2463. "🔄 切换到Tab:",
  2464. tab.desc || tab.title,
  2465. "加载页面:",
  2466. currentTabUrl.value
  2467. );
  2468. };
  2469. // 监听 activeIndex 变化
  2470. watch(
  2471. () => props.activeIndex,
  2472. (newIndex) => {
  2473. currentTab.value = newIndex;
  2474. loadTabUrl(newIndex);
  2475. },
  2476. { immediate: true }
  2477. );
  2478. // 监听 tabList 变化
  2479. watch(
  2480. () => props.tabList,
  2481. () => {
  2482. if (props.tabList.length > 0 && currentTab.value === 0) {
  2483. loadTabUrl(0);
  2484. }
  2485. },
  2486. { immediate: true }
  2487. );
  2488. // 切换Tab
  2489. const handleTabClick = (index) => {
  2490. if (currentTab.value === index) return;
  2491. currentTab.value = index;
  2492. loadTabUrl(index);
  2493. emit("tab-change", { index, tab: props.tabList[index] });
  2494. };
  2495. return {
  2496. currentTab,
  2497. currentTabUrl,
  2498. handleTabClick,
  2499. };
  2500. },
  2501. template: `
  2502. <div class="ss-sub-tab">
  2503. <!-- Tab 栏 -->
  2504. <div class="ss-sub-tab__bar" v-if="tabList.length > 0">
  2505. <div
  2506. v-for="(tab, index) in tabList"
  2507. :key="index"
  2508. class="ss-sub-tab__item"
  2509. :class="{ 'ss-sub-tab__item--active': currentTab === index }"
  2510. @click="handleTabClick(index)"
  2511. >
  2512. {{ tab.desc || tab.title }}
  2513. </div>
  2514. </div>
  2515. <!-- 内容区域 -->
  2516. <div class="ss-sub-tab__content" v-if="currentTabUrl">
  2517. <iframe :src="currentTabUrl" frameborder="0"></iframe>
  2518. </div>
  2519. </div>
  2520. `,
  2521. };
  2522. // ===== SsUploadFile 文件上传组件(支持单文件/多文件) =====
  2523. const SsUploadFile = {
  2524. name: "SsUploadFile",
  2525. props: {
  2526. // v-model 绑定的值(单文件:String,多文件:Array)
  2527. modelValue: { type: [String, Array], default: "" },
  2528. // 最大上传数量(默认1个)
  2529. max: { type: Number, default: 1 },
  2530. // 是否禁用
  2531. disabled: { type: Boolean, default: false },
  2532. // 允许的文件类型(默认常见文件类型)
  2533. accept: {
  2534. type: String,
  2535. default: ".pdf,.doc,.docx,.xls,.xlsx,.txt,.zip,.rar",
  2536. },
  2537. // 最大文件大小(MB,默认5MB)
  2538. maxSize: { type: Number, default: 5 },
  2539. },
  2540. emits: ["update:modelValue", "uploaded"],
  2541. setup(props, { emit }) {
  2542. // 文件列表(统一用数组管理)
  2543. const fileList = ref([]);
  2544. // 监听 modelValue 变化,同步到 fileList
  2545. watch(
  2546. () => props.modelValue,
  2547. (newVal) => {
  2548. if (props.max === 1) {
  2549. // 单文件模式
  2550. fileList.value = newVal
  2551. ? [{ path: newVal, name: getFileName(newVal) }]
  2552. : [];
  2553. } else {
  2554. // 多文件模式
  2555. if (Array.isArray(newVal)) {
  2556. fileList.value = newVal.map((path) => ({
  2557. path,
  2558. name: getFileName(path),
  2559. }));
  2560. } else {
  2561. fileList.value = newVal
  2562. ? [{ path: newVal, name: getFileName(newVal) }]
  2563. : [];
  2564. }
  2565. }
  2566. },
  2567. { immediate: true }
  2568. );
  2569. // 是否可以继续添加文件
  2570. const canAddMore = computed(() => {
  2571. return fileList.value.length < props.max;
  2572. });
  2573. // 从路径中提取文件名
  2574. const getFileName = (path) => {
  2575. if (!path) return "";
  2576. const parts = path.split("/");
  2577. return parts[parts.length - 1];
  2578. };
  2579. // 获取文件图标
  2580. const getFileIcon = (fileName) => {
  2581. const ext = fileName.split(".").pop().toLowerCase();
  2582. const iconMap = {
  2583. pdf: "icon-pdf",
  2584. doc: "icon-word",
  2585. docx: "icon-word",
  2586. xls: "icon-excel",
  2587. xlsx: "icon-excel",
  2588. txt: "icon-txt",
  2589. zip: "icon-zip",
  2590. rar: "icon-zip",
  2591. };
  2592. return iconMap[ext] || "icon-wenjian";
  2593. };
  2594. // 选择文件
  2595. const selectFile = () => {
  2596. if (props.disabled || !canAddMore.value) return;
  2597. const input = document.createElement("input");
  2598. input.type = "file";
  2599. input.accept = props.accept;
  2600. input.onchange = async (e) => {
  2601. const file = e.target.files[0];
  2602. if (!file) return;
  2603. // 检查文件大小
  2604. const fileSizeMB = file.size / 1024 / 1024;
  2605. if (fileSizeMB > props.maxSize) {
  2606. window.showToast?.(`文件大小不能超过${props.maxSize}MB`, "error");
  2607. return;
  2608. }
  2609. // 上传文件
  2610. try {
  2611. const serverPath = await uploadFile(file, "file", file.name);
  2612. const newList = [
  2613. ...fileList.value,
  2614. { path: serverPath, name: file.name },
  2615. ];
  2616. updateModelValue(newList);
  2617. emit("uploaded", serverPath);
  2618. } catch (error) {
  2619. console.error("文件上传失败:", error);
  2620. }
  2621. };
  2622. input.click();
  2623. };
  2624. // 删除文件
  2625. const deleteFile = (index) => {
  2626. const newList = fileList.value.filter((_, i) => i !== index);
  2627. updateModelValue(newList);
  2628. };
  2629. // 下载文件
  2630. const downloadFile = (file) => {
  2631. const url =
  2632. window.SS.utils?.getFileUrl?.(file.path) ||
  2633. window.getFileUrl?.(file.path) ||
  2634. file.path;
  2635. window.open(url, "_blank");
  2636. };
  2637. // 更新 modelValue
  2638. const updateModelValue = (list) => {
  2639. const paths = list.map((f) => f.path);
  2640. if (props.max === 1) {
  2641. // 单文件模式:返回 String
  2642. emit("update:modelValue", paths[0] || "");
  2643. } else {
  2644. // 多文件模式:返回 Array
  2645. emit("update:modelValue", paths);
  2646. }
  2647. };
  2648. return {
  2649. fileList,
  2650. canAddMore,
  2651. getFileIcon,
  2652. selectFile,
  2653. deleteFile,
  2654. downloadFile,
  2655. };
  2656. },
  2657. template: `
  2658. <div class="ss-upload-file">
  2659. <!-- 文件列表 -->
  2660. <div v-if="fileList.length > 0" class="file-list">
  2661. <!-- 已上传的文件 -->
  2662. <div
  2663. v-for="(file, index) in fileList"
  2664. :key="index"
  2665. class="file-item"
  2666. >
  2667. <div class="file-icon">
  2668. <Icon :name="getFileIcon(file.name)" size="40" color="#40ac6d" />
  2669. </div>
  2670. <div class="file-info" @click="downloadFile(file)">
  2671. <span class="file-name">{{ file.name }}</span>
  2672. </div>
  2673. <!-- 文件操作按钮 -->
  2674. <div class="file-actions">
  2675. <div class="file-download" @click="downloadFile(file)">
  2676. <Icon name="icon-xiazai" size="32" color="#40ac6d" />
  2677. </div>
  2678. <div v-if="!disabled" class="file-delete" @click.stop="deleteFile(index)">
  2679. <Icon name="icon-guanbi" size="32" color="#ff3b30" />
  2680. </div>
  2681. </div>
  2682. </div>
  2683. </div>
  2684. <!-- 添加按钮 -->
  2685. <div
  2686. v-if="canAddMore && !disabled"
  2687. class="file-add-button"
  2688. @click="selectFile"
  2689. >
  2690. <div class="add-icon">
  2691. <Icon name="icon-tianjia" size="64" color="#999" />
  2692. </div>
  2693. <span class="add-text">上传文件 ({{ fileList.length }}/{{ max }})</span>
  2694. <span class="file-tip">支持格式: {{ accept }},最大{{ maxSize }}MB</span>
  2695. </div>
  2696. </div>
  2697. `,
  2698. };
  2699. /**
  2700. * 功能说明:H5移动端富文本组件(对齐PC字段协议 mswj/fjid/path 回显) by xu 2026-03-01
  2701. *
  2702. * 约定:
  2703. * - v-model 绑定文件路径字段(如 mswj)
  2704. * - 组件内部维护编辑内容,并输出隐藏字段:xxEdit / xxwj / ueditorpath / fjid
  2705. * - 回显通过 url + path 拉取 HTML 内容,不直接依赖 modelValue 的 HTML 字符串
  2706. *
  2707. * @component SsEditor
  2708. * @prop {String} modelValue 文件路径(如 mswj)
  2709. * @prop {String} name 字段名(默认 mswj)
  2710. * @prop {String} url 回显读取接口地址
  2711. * @prop {Number|String} height 编辑器高度
  2712. * @prop {String} placeholder 占位文案
  2713. * @prop {Boolean} readonly 是否只读
  2714. * @prop {String} uploadUrl 上传接口地址
  2715. * @prop {Object} param 附件参数(button.cmsAddUrl / button.cmsUpdUrl / mode)
  2716. * @emits update:modelValue 更新文件路径
  2717. * @emits ready 编辑器就绪
  2718. * @emits change 内容变化
  2719. */
  2720. const SsEditor = {
  2721. name: "SsEditor",
  2722. props: {
  2723. modelValue: { type: String, default: "" },
  2724. name: { type: String, default: "mswj" },
  2725. url: { type: String, default: "" },
  2726. height: { type: [Number, String], default: 280 },
  2727. placeholder: { type: String, default: "请输入内容" },
  2728. readonly: { type: Boolean, default: false },
  2729. uploadUrl: { type: String, default: "/service?ssServ=ulByHttp" },
  2730. param: { type: Object, default: () => ({}) },
  2731. },
  2732. emits: ["update:modelValue", "ready", "change"],
  2733. setup(props, { emit }) {
  2734. const editorElementId = `ss-editor-${Date.now()}-${Math.floor(
  2735. Math.random() * 10000
  2736. )}`;
  2737. const editorContent = ref("");
  2738. const editorInstance = ref(null);
  2739. const fjid = ref(props.param?.button?.val || "");
  2740. const fjName = props.param?.button?.desc || "附件";
  2741. const mode = props.param?.mode;
  2742. /**
  2743. * 功能说明:确保附件 fjid 存在,不存在时先通过 cmsAddUrl 创建 by xu 2026-03-01
  2744. * @returns {Promise<string>} fjid
  2745. */
  2746. const ensureFjid = async () => {
  2747. if (fjid.value) return fjid.value;
  2748. if (!props.param?.button?.cmsAddUrl) return "";
  2749. return new Promise((resolve) => {
  2750. $.ajax({
  2751. type: "post",
  2752. url: props.param.button.cmsAddUrl,
  2753. async: false,
  2754. data: {
  2755. name: "fjid",
  2756. ssNrObjName: "sh",
  2757. ssNrObjId: "",
  2758. },
  2759. success: (_fjid) => {
  2760. fjid.value = _fjid || "";
  2761. resolve(fjid.value);
  2762. },
  2763. error: () => resolve(""),
  2764. });
  2765. });
  2766. };
  2767. /**
  2768. * 功能说明:打开附件管理弹窗(与PC端行为一致) by xu 2026-03-01
  2769. * @returns {Promise<void>}
  2770. */
  2771. const openAttachmentDialog = async () => {
  2772. if (!props.param?.button?.cmsUpdUrl) {
  2773. console.warn("未配置附件编辑地址 cmsUpdUrl");
  2774. return;
  2775. }
  2776. const currentFjid = await ensureFjid();
  2777. if (!currentFjid) return;
  2778. const query =
  2779. `&nrid=T-${currentFjid}` +
  2780. `&objectId=${currentFjid}` +
  2781. `&objectName=${encodeURIComponent(fjName)}` +
  2782. `&callback=${window["fjidCallbackName"] || ""}`;
  2783. if (window.SS && typeof window.SS.openDialog === "function") {
  2784. window.SS.openDialog({
  2785. src: props.param.button.cmsUpdUrl + query,
  2786. headerTitle: "编辑",
  2787. width: 900,
  2788. high: 664,
  2789. zIndex: 51,
  2790. });
  2791. }
  2792. };
  2793. /**
  2794. * 功能说明:初始化 Jodit 编辑器并绑定工具栏/上传/change 事件 by xu 2026-03-01
  2795. * @returns {void}
  2796. */
  2797. const buildEditor = async () => {
  2798. if (!window.Jodit || !window.Jodit.make) {
  2799. await ensureOptionalAssets("jodit");
  2800. }
  2801. if (!window.Jodit || !window.Jodit.make) {
  2802. console.error("Jodit 未加载,无法初始化 ss-editor");
  2803. return;
  2804. }
  2805. const editorUploadUrl = props.uploadUrl.includes("?")
  2806. ? `${props.uploadUrl}&type=img`
  2807. : `${props.uploadUrl}?type=img`;
  2808. const instance = window.Jodit.make(`#${editorElementId}`, {
  2809. height: props.height,
  2810. placeholder: props.placeholder,
  2811. readonly: props.readonly,
  2812. language: "zh_cn",
  2813. showXPathInStatusbar: false,
  2814. showCharsCounter: false,
  2815. showWordsCounter: false,
  2816. allowResizeY: false,
  2817. toolbarSticky: false,
  2818. statusbar: false,
  2819. uploader: {
  2820. url: editorUploadUrl,
  2821. format: "json",
  2822. method: "POST",
  2823. filesVariableName: (i) => `imgs[${i}]`,
  2824. isSuccess: (resp) => resp?.code === 0 || !!resp?.data,
  2825. getMessage: (resp) => resp?.msg || "上传失败",
  2826. process: (resp) => resp?.data?.url || resp?.data?.path || "",
  2827. contentType: () => false,
  2828. },
  2829. controls: {
  2830. customLinkButton: {
  2831. name: "link",
  2832. tooltip: "附件",
  2833. exec: () => {
  2834. openAttachmentDialog();
  2835. },
  2836. },
  2837. },
  2838. buttons: [
  2839. "fullsize",
  2840. "bold",
  2841. "italic",
  2842. "underline",
  2843. "|",
  2844. "font",
  2845. "fontsize",
  2846. "|",
  2847. "left",
  2848. "center",
  2849. "right",
  2850. "|",
  2851. "ul",
  2852. "ol",
  2853. "|",
  2854. "image",
  2855. "table",
  2856. "customLinkButton",
  2857. "|",
  2858. "undo",
  2859. "redo",
  2860. ],
  2861. buttonsMD: [
  2862. "bold",
  2863. "italic",
  2864. "underline",
  2865. "|",
  2866. "image",
  2867. "customLinkButton",
  2868. "|",
  2869. "dots",
  2870. ],
  2871. buttonsSM: [
  2872. "bold",
  2873. "italic",
  2874. "|",
  2875. "image",
  2876. "customLinkButton",
  2877. "|",
  2878. "dots",
  2879. ],
  2880. buttonsXS: ["bold", "|", "dots"],
  2881. });
  2882. instance.value = editorContent.value || "";
  2883. instance.events.on("change", () => {
  2884. editorContent.value = instance.value || "";
  2885. emit("change", editorContent.value);
  2886. });
  2887. editorInstance.value = instance;
  2888. emit("ready", instance);
  2889. };
  2890. /**
  2891. * 功能说明:按路径加载富文本HTML内容并回填编辑器 by xu 2026-03-01
  2892. * @returns {Promise<void>}
  2893. */
  2894. const loadContentByPath = async () => {
  2895. if (!props.url || !props.modelValue) return;
  2896. try {
  2897. const params = new URLSearchParams();
  2898. if (mode) params.append("mode", mode);
  2899. params.append("path", props.modelValue);
  2900. const response = await window.axios.post(props.url, params, {
  2901. headers: { "Content-Type": "application/x-www-form-urlencoded" },
  2902. });
  2903. const content = response?.data?.content || "";
  2904. if (content) {
  2905. editorContent.value = content;
  2906. if (editorInstance.value) {
  2907. editorInstance.value.value = content;
  2908. }
  2909. }
  2910. const filePath = response?.data?.path;
  2911. if (filePath) {
  2912. emit("update:modelValue", filePath);
  2913. }
  2914. } catch (error) {
  2915. console.error("ss-editor 回显内容加载失败:", error);
  2916. }
  2917. };
  2918. onMounted(async () => {
  2919. try {
  2920. await buildEditor();
  2921. } catch (error) {
  2922. console.error("ss-editor 初始化失败:", error);
  2923. }
  2924. await loadContentByPath();
  2925. });
  2926. watch(
  2927. () => props.readonly,
  2928. (newVal) => {
  2929. if (
  2930. editorInstance.value &&
  2931. typeof editorInstance.value.setReadOnly === "function"
  2932. ) {
  2933. editorInstance.value.setReadOnly(newVal);
  2934. }
  2935. }
  2936. );
  2937. onBeforeUnmount(() => {
  2938. if (
  2939. editorInstance.value &&
  2940. typeof editorInstance.value.destruct === "function"
  2941. ) {
  2942. editorInstance.value.destruct();
  2943. }
  2944. });
  2945. return {
  2946. editorElementId,
  2947. editorContent,
  2948. fjid,
  2949. };
  2950. },
  2951. template: `
  2952. <div class="ss-editor-container">
  2953. <input v-if="fjid" type="hidden" name="fjid" :value="fjid" />
  2954. <input type="hidden" :name="name.replace(/wj$/, '') + 'Edit'" :value="editorContent" />
  2955. <input type="hidden" :name="name.replace(/wj$/, '') + 'wj'" :value="modelValue" />
  2956. <input type="hidden" name="ueditorpath" value="mswj" />
  2957. <textarea :id="editorElementId"></textarea>
  2958. </div>
  2959. `,
  2960. };
  2961. window.SS.dom.initializeFormApp = function (config) {
  2962. const { el, ...vueOptions } = config;
  2963. const app = createApp({
  2964. ...vueOptions,
  2965. });
  2966. // 注册组件
  2967. // app.component("SsLoginIcon", SsLoginIcon);
  2968. // app.component("SsMark", SsMark);
  2969. // app.component("SsFullStyleHeader", SsFullStyleHeader);
  2970. // app.component("SsDialog", SsDialog);
  2971. app.component("SsInput", SsInput);
  2972. app.component("SsBottom", SsBottom);
  2973. app.component("SsCard", SsCard);
  2974. app.component("SsSearchButton", SsSearchButton);
  2975. app.component("SsSelect", SsSelect);
  2976. app.component("Icon", Icon);
  2977. // 注册 Vant 组件
  2978. const vantLib = window.vant || window.Vant;
  2979. console.log("🔍 检查 Vant:", {
  2980. hasVant: !!window.vant,
  2981. hasVantCap: !!window.Vant,
  2982. vantLib: !!vantLib,
  2983. vantKeys: vantLib ? Object.keys(vantLib).slice(0, 20) : [],
  2984. hasPopup: vantLib?.Popup,
  2985. hasDatetimePicker: vantLib?.DatetimePicker,
  2986. hasDatePicker: vantLib?.DatePicker,
  2987. hasTimePicker: vantLib?.TimePicker,
  2988. allKeys: vantLib ? Object.keys(vantLib) : [],
  2989. });
  2990. if (vantLib) {
  2991. try {
  2992. // 使用 Vant 的 use 方法注册所有组件
  2993. app.use(vantLib);
  2994. console.log("✅ Vant 全部组件注册成功");
  2995. } catch (error) {
  2996. console.error("❌ Vant 组件注册失败:", error);
  2997. // 降级方案:手动注册具体组件
  2998. try {
  2999. app.component("van-popup", vantLib.Popup);
  3000. app.component("van-datetime-picker", vantLib.DatetimePicker);
  3001. console.log("✅ Vant 手动注册成功");
  3002. } catch (e) {
  3003. console.error("❌ Vant 手动注册也失败:", e);
  3004. }
  3005. }
  3006. } else {
  3007. console.warn("⚠️ Vant 未加载");
  3008. }
  3009. // 注册组件 - 统一使用 kebab-case
  3010. app.component("ss-verify", SsVerify);
  3011. app.component("ss-verify-node", SsVerifyNode);
  3012. app.component("ss-common-icon", SsCommonIcon);
  3013. app.component("ss-onoff-button", SsOnoffButton);
  3014. app.component("ss-datetime-picker", SsDatetimePicker);
  3015. app.component("ss-confirm", SsConfirm);
  3016. app.component("ss-image-cropper", SsImageCropper);
  3017. app.component("ss-upload-image", SsUploadImage);
  3018. app.component("ss-upload-file", SsUploadFile);
  3019. app.component("ss-car-card", SsCarCard);
  3020. app.component("ss-sub-tab", SsSubTab);
  3021. app.component("ss-editor", SsEditor);
  3022. app.component("SsEditor", SsEditor);
  3023. // app.component("SsObjp", SsObjp);
  3024. // app.component("SsHidden", SsHidden);
  3025. // app.component("SsCcp", SsCcp);
  3026. // app.component("SsDatePicker", SsDatePicker);
  3027. // app.component("SsIcon", SsIcon);
  3028. // app.component("SsCommonIcon", SsCommonIcon);
  3029. // app.component("SsBreadcrumb", SsBreadcrumb);
  3030. // app.component("SsEditor", SsEditor);
  3031. // app.component("SsDialogIcon", SsDialogIcon);
  3032. // app.component("SsBottomButton", SsBottomButton);
  3033. // app.component("SsNavIcon", SsNavIcon);
  3034. // app.component("SsHeaderIcon", SsHeaderIcon);
  3035. // app.component("SsGolbalMenuIcon", SsGolbalMenuIcon);
  3036. // app.component("SsCartListIcon", SsCartListIcon);
  3037. // app.component("SsQuickIcon", SsQuickIcon);
  3038. // app.component("SsFormIcon", SsFormIcon);
  3039. // app.component("SsBottomDivIcon", SsBottomDivIcon);
  3040. // app.component("SsEditorIcon", SsEditorIcon);
  3041. // app.component("SsValidate", SsValidate);
  3042. // app.component("SsOnoffbutton", SsOnoffbutton);
  3043. // app.component("SsOnoffbuttonArray", SsOnoffbuttonArray);
  3044. // app.component("SsTextarea", SsTextarea);
  3045. // app.component("SsLoginInput", SsLoginInput);
  3046. // app.component("SsLoginButton", SsLoginButton);
  3047. // app.component("SsSearch", SsSearch);
  3048. // app.component("SsCartItem", SsCartItem);
  3049. // app.component("SsCartItem2", SsCartItem2);
  3050. // app.component("SsListCard", SsListCard);
  3051. // app.component("SsFolderCard", SsFolderCard);
  3052. // app.component("SsFolderCartView", SsFolderCartView);
  3053. // app.component("SsPage", SsPage);
  3054. // app.component("SsRightInfo", SSRightInfo);
  3055. // app.component("SsSuccessPopup", SsSuccessPopup);
  3056. // app.component("SsErrorDialog", SsErrorDialog);
  3057. // app.component("SsVerify", SsVerify);
  3058. // app.component("SsVerifyNode", SsVerifyNode);
  3059. // app.component("SsOrcImgBox", SsOrcImgBox);
  3060. // app.component("ss-search-input", SsSearchInput);
  3061. // app.component("ss-search-date-picker", SsSearchDatePicker);
  3062. // app.component("ss-search-button", SsSearchButton);
  3063. // app.component("ss-drop-button", SsDropButton);
  3064. // app.component("ss-sub-tab", SsSubTab);
  3065. // app.component("ss-img", SsImgUpload);
  3066. // 设置为中文
  3067. // app.use(ElementPlus, {
  3068. // locale: ElementPlusLocaleZhCn,
  3069. // });
  3070. // console.log(ElementPlus);
  3071. // 确保 ElementPlusIconsVue
  3072. // if (window.ElementPlusIconsVue) {
  3073. // // 注册 Element Plus 图标组件
  3074. // for (const [key, component] of Object.entries(
  3075. // window.ElementPlusIconsVue
  3076. // )) {
  3077. // console.log(key, component);
  3078. // app.component(key, component);
  3079. // }
  3080. // }
  3081. // 挂载首页的组件
  3082. // for (const componentName in IndexComponents) {
  3083. // app.component(componentName, IndexComponents[componentName]);
  3084. // }
  3085. // 挂载echarts的组件
  3086. // for (const componentName in EchartComponents) {
  3087. // app.component(componentName, EchartComponents[componentName]);
  3088. // }
  3089. // 挂载 Vue 应用
  3090. const vm = app.mount(el);
  3091. vm.data = vueOptions.data();
  3092. return vm;
  3093. };
  3094. })();