mp-ss-components.js 97 KB

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