hook.tsx 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806
  1. import dayjs from "dayjs";
  2. import { message } from "@/utils/message";
  3. import { addDialog } from "@/components/ReDialog";
  4. import type { PaginationProps } from "@pureadmin/table";
  5. import { deviceDetection } from "@pureadmin/utils";
  6. import {
  7. getOrderList,
  8. getOrderById,
  9. refundOrder,
  10. cancelPayScoreOrder,
  11. queryOrderFromHaha,
  12. repairPayScorePayment
  13. } from "@/api/order";
  14. import { type Ref, ref, computed, reactive, onMounted } from "vue";
  15. import {
  16. ElForm,
  17. ElFormItem,
  18. ElInput,
  19. ElInputNumber,
  20. ElSelect,
  21. ElOption,
  22. ElDatePicker,
  23. ElDescriptions,
  24. ElDescriptionsItem,
  25. ElImage,
  26. ElTable,
  27. ElTableColumn,
  28. ElMessageBox
  29. } from "element-plus";
  30. import type { OrderItem, OrderSearchForm, RefundProductItem } from "./types";
  31. import {
  32. initPagination,
  33. handlePageSizeChange,
  34. handleCurrentPageChange,
  35. resetPagination,
  36. updatePaginationData
  37. } from "@/utils/paginationHelper";
  38. export function useOrder(tableRef: Ref) {
  39. const form = reactive<OrderSearchForm>({
  40. orderNo: "",
  41. phone: "",
  42. deviceId: "",
  43. payStatus: "",
  44. status: "",
  45. startDate: "",
  46. endDate: ""
  47. });
  48. const formRef = ref();
  49. const ruleFormRef = ref();
  50. const dataList = ref([]);
  51. const loading = ref(true);
  52. const pagination = reactive<PaginationProps>(initPagination());
  53. const columns: TableColumnList = [
  54. {
  55. label: "订单编号",
  56. prop: "orderNo",
  57. minWidth: 160,
  58. formatter: ({ orderNo }) => orderNo || "-"
  59. },
  60. {
  61. label: "活动ID",
  62. prop: "activityId",
  63. minWidth: 120,
  64. formatter: ({ activityId }) => activityId || "-"
  65. },
  66. {
  67. label: "支付订单号",
  68. prop: "outTradeNo",
  69. minWidth: 150,
  70. formatter: ({ outTradeNo }) => outTradeNo || "-"
  71. },
  72. {
  73. label: "用户 ID",
  74. prop: "userId",
  75. minWidth: 80,
  76. formatter: ({ userId }) => userId || "-"
  77. },
  78. {
  79. label: "手机号",
  80. prop: "phone",
  81. minWidth: 120,
  82. formatter: ({ phone }) => phone || "-"
  83. },
  84. {
  85. label: "门店名称",
  86. prop: "storeName",
  87. minWidth: 120,
  88. formatter: ({ storeName }) => storeName || "-"
  89. },
  90. {
  91. label: "设备 ID",
  92. prop: "deviceId",
  93. minWidth: 120,
  94. formatter: ({ deviceId }) => deviceId || "-"
  95. },
  96. {
  97. label: "订单金额",
  98. prop: "totalAmount",
  99. minWidth: 100,
  100. formatter: ({ totalAmount }) => totalAmount ? `¥${totalAmount}` : "¥0.00"
  101. },
  102. {
  103. label: "优惠金额",
  104. prop: "discountAmount",
  105. minWidth: 100,
  106. formatter: ({ discountAmount }) => {
  107. const amount = discountAmount || 0;
  108. return amount > 0 ? `¥${amount}` : "¥0.00";
  109. },
  110. cellRenderer: ({ row }) => {
  111. const amount = row.discountAmount || 0;
  112. if (amount > 0) {
  113. return <el-tag type="success" size="small">-¥{amount}</el-tag>;
  114. }
  115. return <span class="text-gray-400">¥0.00</span>;
  116. }
  117. },
  118. {
  119. label: "实付金额",
  120. prop: "paidAmount",
  121. minWidth: 100,
  122. formatter: ({ paidAmount, totalAmount, discountAmount }) => {
  123. const amount = paidAmount || (totalAmount || 0) - (discountAmount || 0);
  124. return `¥${amount}`;
  125. },
  126. cellRenderer: ({ row }) => {
  127. const amount = row.paidAmount || (row.totalAmount || 0) - (row.discountAmount || 0);
  128. return <span class="text-red-600 font-bold">¥{amount}</span>;
  129. }
  130. },
  131. {
  132. label: "支付方式",
  133. prop: "payType",
  134. minWidth: 90,
  135. cellRenderer: ({ row }) => {
  136. const payTypeMap: Record<string, { text: string; type: string }> = {
  137. "wechat": { text: "微信支付", type: "success" },
  138. "alipay": { text: "支付宝", type: "primary" },
  139. "cash": { text: "现金", type: "warning" },
  140. "free": { text: "免费", type: "info" }
  141. };
  142. const payType = payTypeMap[row.payType] || { text: row.payType || "-", type: "info" };
  143. return <el-tag type={payType.type as any} size="small">{payType.text}</el-tag>;
  144. }
  145. },
  146. {
  147. label: "支付状态",
  148. prop: "payStatus",
  149. minWidth: 85,
  150. cellRenderer: ({ row }) => {
  151. const statusMap: Record<string, { label: string; type: string }> = {
  152. "UNPAID": { label: "未支付", type: "warning" },
  153. "PAID": { label: "已支付", type: "success" },
  154. "PARTIAL_REFUND": { label: "部分退款", type: "warning" },
  155. "REFUND": { label: "全额退款", type: "danger" }
  156. };
  157. const status = statusMap[row.payStatus] || { label: "未知", type: "info" };
  158. return <el-tag type={status.type as any}>{status.label}</el-tag>;
  159. }
  160. },
  161. {
  162. label: "订单状态",
  163. prop: "status",
  164. minWidth: 85,
  165. cellRenderer: ({ row }) => {
  166. const statusMap: Record<number, { text: string; type: string }> = {
  167. 0: { text: "待支付", type: "warning" },
  168. 1: { text: "已完成", type: "success" },
  169. 2: { text: "已取消", type: "info" },
  170. 3: { text: "已关闭", type: "info" }
  171. };
  172. const status = statusMap[row.status] || { text: "未知", type: "info" };
  173. return <el-tag type={status.type as any}>{status.text}</el-tag>;
  174. }
  175. },
  176. {
  177. label: "用户标签",
  178. prop: "userTagLabel",
  179. minWidth: 90,
  180. cellRenderer: ({ row }) => {
  181. if (!row.userTagLabel) return <span>-</span>;
  182. const tagMap: Record<string, { type: string; label: string }> = {
  183. "new": { type: "success", label: "新用户" },
  184. "regular": { type: "", label: "老用户" },
  185. "frequent": { type: "warning", label: "常客" }
  186. };
  187. const tag = tagMap[row.userTag] || { type: "info", label: row.userTagLabel };
  188. return <el-tag type={tag.type as any} size="small">{tag.label}</el-tag>;
  189. }
  190. },
  191. {
  192. label: "下单时间",
  193. prop: "createTime",
  194. minWidth: 160,
  195. formatter: ({ createTime }) =>
  196. createTime ? dayjs(createTime).format("YYYY-MM-DD HH:mm:ss") : "-"
  197. },
  198. {
  199. label: "支付时间",
  200. prop: "payTime",
  201. minWidth: 160,
  202. formatter: ({ payTime }) =>
  203. payTime ? dayjs(payTime).format("YYYY-MM-DD HH:mm:ss") : "-"
  204. },
  205. {
  206. label: "操作",
  207. fixed: "right",
  208. width: 150,
  209. slot: "operation"
  210. }
  211. ];
  212. async function onSearch() {
  213. loading.value = true;
  214. try {
  215. const searchParams: any = {
  216. page: pagination.currentPage,
  217. pageSize: pagination.pageSize
  218. };
  219. if (form.orderNo) searchParams.orderNo = form.orderNo;
  220. if (form.phone) searchParams.phone = form.phone;
  221. if (form.deviceId) searchParams.deviceId = form.deviceId;
  222. if (form.payStatus) searchParams.payStatus = form.payStatus;
  223. if (form.status !== "") {
  224. searchParams.status = parseInt(form.status as string, 10);
  225. }
  226. if (form.startDate) searchParams.startDate = form.startDate;
  227. if (form.endDate) searchParams.endDate = form.endDate;
  228. const { data } = await getOrderList(searchParams as {
  229. page?: number;
  230. pageSize?: number;
  231. orderNo?: string;
  232. deviceId?: string;
  233. payStatus?: string;
  234. status?: number;
  235. startDate?: string;
  236. endDate?: string;
  237. });
  238. dataList.value = data.list || [];
  239. pagination.total = Number(data.total) || 0;
  240. } catch (error) {
  241. console.error("获取订单列表失败:", error);
  242. dataList.value = [];
  243. pagination.total = 0;
  244. } finally {
  245. setTimeout(() => {
  246. loading.value = false;
  247. }, 300);
  248. }
  249. }
  250. const resetForm = formEl => {
  251. if (!formEl) return;
  252. formEl.resetFields();
  253. resetPagination(pagination, onSearch);
  254. };
  255. function handleSizeChange(val: number) {
  256. handlePageSizeChange(val, pagination, onSearch);
  257. }
  258. function handleCurrentChange(val: number) {
  259. handleCurrentPageChange(val, pagination, onSearch);
  260. }
  261. // 从哈哈平台同步查询订单
  262. async function handleQueryFromHaha(orderNo?: string, activityId?: string) {
  263. const queryForm = reactive({ orderId: orderNo || "", activityId: activityId || "" });
  264. addDialog({
  265. title: "从哈哈平台查询订单",
  266. width: "40%",
  267. draggable: true,
  268. closeOnClickModal: false,
  269. contentRenderer: () => (
  270. <div>
  271. <div style="display: flex; gap: 8px; margin-bottom: 12px;">
  272. <ElInput v-model={queryForm.orderId} placeholder="哈哈订单号" style="flex:1" />
  273. <ElInput v-model={queryForm.activityId} placeholder="活动ID" style="flex:1" />
  274. </div>
  275. </div>
  276. ),
  277. beforeSure: async (done) => {
  278. try {
  279. const { data } = await queryOrderFromHaha({
  280. orderId: queryForm.orderId || undefined,
  281. activityId: queryForm.activityId || undefined
  282. });
  283. if (data) {
  284. message("查询成功,订单信息已返回", { type: "success" });
  285. // 展示查询结果
  286. addDialog({
  287. title: "哈哈平台订单详情",
  288. width: "60%",
  289. draggable: true,
  290. closeOnClickModal: false,
  291. contentRenderer: () => (
  292. <pre style="max-height: 60vh; overflow-y: auto; padding: 12px; background: #f5f5f5; border-radius: 8px; font-size: 13px;">
  293. {JSON.stringify(data, null, 2)}
  294. </pre>
  295. ),
  296. hideFooter: true
  297. });
  298. }
  299. done();
  300. } catch {
  301. message("查询失败", { type: "error" });
  302. }
  303. }
  304. });
  305. }
  306. async function handleDetail(row: OrderItem) {
  307. try {
  308. const { data } = await getOrderById(row.id);
  309. const order = data;
  310. const payStatusStyle = order.payStatus === "PAID"
  311. ? "success" : order.payStatus === "PARTIAL_REFUND"
  312. ? "warning" : order.payStatus === "REFUND"
  313. ? "danger" : "warning";
  314. const payStatusText = order.payStatusLabel || (
  315. order.payStatus === "PAID" ? "已支付"
  316. : order.payStatus === "PARTIAL_REFUND" ? "部分退款"
  317. : order.payStatus === "REFUND" ? "全额退款"
  318. : "未支付");
  319. const statusStyle = order.status === 1
  320. ? "success" : order.status === 0
  321. ? "warning" : "info";
  322. const statusText = order.statusText || (order.status === 0 ? "待支付" : order.status === 1 ? "已完成" : order.status === 2 ? "已取消" : "已关闭");
  323. const payTypeMap: Record<string, { text: string; type: string }> = {
  324. "wechat": { text: "微信支付", type: "success" },
  325. "alipay": { text: "支付宝", type: "primary" },
  326. "cash": { text: "现金", type: "warning" },
  327. "free": { text: "免费", type: "info" }
  328. };
  329. const payType = payTypeMap[order.payType] || { text: order.payType || "-", type: "info" };
  330. addDialog({
  331. title: `订单详情`,
  332. width: "720px",
  333. draggable: true,
  334. closeOnClickModal: false,
  335. contentRenderer: () => (
  336. <div style="max-height: 70vh; overflow-y: auto; padding: 0 4px;">
  337. <div style="font-size: 15px; font-weight: 600; margin-bottom: 10px; color: var(--el-text-color-primary);">基本信息</div>
  338. <ElDescriptions column={3} border size="small">
  339. <ElDescriptionsItem label="订单编号" span={2}>{order.orderNo}</ElDescriptionsItem>
  340. <ElDescriptionsItem label="门店名称">{order.shopName || "-"}</ElDescriptionsItem>
  341. <ElDescriptionsItem label="支付订单号" span={2}>{order.outTradeNo || "-"}</ElDescriptionsItem>
  342. <ElDescriptionsItem label="设备 ID">{order.deviceId || "-"}</ElDescriptionsItem>
  343. <ElDescriptionsItem label="活动 ID" span={2}>{order.activityId || "-"}</ElDescriptionsItem>
  344. <ElDescriptionsItem label="用户 ID">{order.userId || "-"}</ElDescriptionsItem>
  345. </ElDescriptions>
  346. <div style="font-size: 15px; font-weight: 600; margin: 14px 0 10px; color: var(--el-text-color-primary);">金额与状态</div>
  347. <ElDescriptions column={3} border size="small">
  348. <ElDescriptionsItem label="订单金额">
  349. <span>¥{order.totalAmount || "0.00"}</span>
  350. </ElDescriptionsItem>
  351. <ElDescriptionsItem label="优惠金额">
  352. {order.discountAmount > 0 ? (
  353. <el-tag type="success" size="small">-¥{order.discountAmount}</el-tag>
  354. ) : (
  355. <span style="color: #999">¥0.00</span>
  356. )}
  357. </ElDescriptionsItem>
  358. <ElDescriptionsItem label="实付金额">
  359. <span style="color: #e6a23c; font-weight: 600; font-size: 15px;">¥{order.paidAmount || (order.totalAmount || 0) - (order.discountAmount || 0)}</span>
  360. </ElDescriptionsItem>
  361. <ElDescriptionsItem label="支付方式">
  362. <el-tag type={payType.type as any} size="small">{payType.text}</el-tag>
  363. </ElDescriptionsItem>
  364. <ElDescriptionsItem label="支付状态">
  365. <el-tag type={payStatusStyle as any} size="small">{payStatusText}</el-tag>
  366. </ElDescriptionsItem>
  367. <ElDescriptionsItem label="订单状态">
  368. <el-tag type={statusStyle as any} size="small">{statusText}</el-tag>
  369. </ElDescriptionsItem>
  370. <ElDescriptionsItem label="下单时间">{dayjs(order.createTime).format("YYYY-MM-DD HH:mm:ss")}</ElDescriptionsItem>
  371. <ElDescriptionsItem label="支付时间" span={2}>{order.payTime ? dayjs(order.payTime).format("YYYY-MM-DD HH:mm:ss") : "-"}</ElDescriptionsItem>
  372. </ElDescriptions>
  373. {(order.videoUrl || order.confidence) && (
  374. <>
  375. <div style="font-size: 15px; font-weight: 600; margin: 14px 0 10px; color: var(--el-text-color-primary);">其他信息</div>
  376. <ElDescriptions column={3} border size="small">
  377. {order.videoUrl && (
  378. <ElDescriptionsItem label="支付视频" span={3}>
  379. <video src={order.videoUrl} controls style="width: 100%; max-width: 360px; max-height: 200px;" />
  380. </ElDescriptionsItem>
  381. )}
  382. {order.confidence && (
  383. <ElDescriptionsItem label="置信度">{(order.confidence * 100).toFixed(2)}%</ElDescriptionsItem>
  384. )}
  385. </ElDescriptions>
  386. </>
  387. )}
  388. {order.products && order.products.length > 0 && (
  389. <>
  390. <div style="font-size: 15px; font-weight: 600; margin: 14px 0 10px; color: var(--el-text-color-primary);">订单商品</div>
  391. <ElTable data={order.products} border size="small" style="width: 100%">
  392. <ElTableColumn prop="productName" label="商品名称" min-width={140} />
  393. <ElTableColumn
  394. prop="pic"
  395. label="图片"
  396. width={70}
  397. align="center"
  398. v-slots={{
  399. default: ({ row }: any) => row.pic ? (
  400. <el-image src={row.pic} style="width: 40px; height: 40px" fit="cover" preview-teleported={true} preview-src-list={[row.pic]} />
  401. ) : <span style="color: #999">-</span>
  402. }}
  403. />
  404. <ElTableColumn
  405. label="单价"
  406. width={90}
  407. align="right"
  408. v-slots={{
  409. default: ({ row }: any) => <span>¥{row.price || "0.00"}</span>
  410. }}
  411. />
  412. <ElTableColumn
  413. label="数量"
  414. width={60}
  415. align="center"
  416. v-slots={{
  417. default: ({ row }: any) => <span>×{row.productNum || 1}</span>
  418. }}
  419. />
  420. <ElTableColumn
  421. label="小计"
  422. width={100}
  423. align="right"
  424. v-slots={{
  425. default: ({ row }: any) => {
  426. const subtotal = row.price && row.productNum ? (row.price * row.productNum) : 0;
  427. return <span style="font-weight: 500">¥{subtotal.toFixed(2)}</span>;
  428. }
  429. }}
  430. />
  431. </ElTable>
  432. </>
  433. )}
  434. </div>
  435. ),
  436. hideFooter: true
  437. });
  438. } catch (error) {
  439. message("获取订单详情失败", { type: "error" });
  440. }
  441. }
  442. async function handleRefund(row: OrderItem) {
  443. if (row.status !== 1) {
  444. message("只有已完成的订单才能退款", { type: "warning" });
  445. return;
  446. }
  447. // 累计退款已达实付金额则不允许继续退款
  448. const paidAmount = row.paidAmount || row.totalAmount || 0;
  449. const refundedAmount = (row as any).refundAmount || 0;
  450. if (refundedAmount >= paidAmount) {
  451. message("该订单已全额退款", { type: "warning" });
  452. return;
  453. }
  454. const refundState = reactive({
  455. loadingDetail: true,
  456. orderDetail: null as any,
  457. selectedProducts: [] as number[],
  458. refundQuantities: {} as Record<number, number>,
  459. reason: "",
  460. customAmount: null as number | null
  461. });
  462. const refundFormRef = ref();
  463. const refundTotalAmount = computed(() => {
  464. if (!refundState.orderDetail?.products) return 0;
  465. return refundState.selectedProducts.reduce((sum, i) => {
  466. const p = refundState.orderDetail.products[i];
  467. return sum + (p.price || 0) * (refundState.refundQuantities[i] || 1);
  468. }, 0);
  469. });
  470. try {
  471. const { data } = await getOrderById(row.id);
  472. refundState.orderDetail = data;
  473. if (data.products && data.products.length > 0) {
  474. data.products.forEach((p: any, i: number) => {
  475. // 已全额退款的商品不预选
  476. const refundedQty = p.refundedQuantity || 0;
  477. if (refundedQty < (p.productNum || 1)) {
  478. refundState.selectedProducts.push(i);
  479. refundState.refundQuantities[i] = (p.productNum || 1) - refundedQty;
  480. }
  481. });
  482. }
  483. } catch {
  484. message("加载订单商品失败", { type: "error" });
  485. } finally {
  486. refundState.loadingDetail = false;
  487. }
  488. addDialog({
  489. title: `订单退款 - ${row.orderNo}`,
  490. width: "40%",
  491. draggable: true,
  492. closeOnClickModal: false,
  493. fullscreen: deviceDetection(),
  494. contentRenderer: () => (
  495. <div style="max-height: 60vh; overflow-y: auto; padding: 0 4px;">
  496. {refundState.loadingDetail ? (
  497. <div style="text-align: center; padding: 40px; color: #999;">正在加载订单商品...</div>
  498. ) : (
  499. <>
  500. <div style="font-size: 15px; font-weight: 600; margin-bottom: 10px; color: var(--el-text-color-primary);">退款商品</div>
  501. <ElTable data={refundState.orderDetail?.products || []} border size="small" style="width: 100%">
  502. <ElTableColumn width={55} align="center"
  503. v-slots={{
  504. default: ({ $index, row: r }: any) => (
  505. <el-checkbox
  506. model-value={refundState.selectedProducts.includes($index)}
  507. disabled={(r.refundedQuantity || 0) >= (r.productNum || 1)}
  508. onChange={(val: boolean) => {
  509. if (val) {
  510. refundState.selectedProducts.push($index);
  511. if (!refundState.refundQuantities[$index]) {
  512. const remaining = (r.productNum || 1) - (r.refundedQuantity || 0);
  513. refundState.refundQuantities[$index] = Math.max(1, remaining);
  514. }
  515. } else {
  516. const idx = refundState.selectedProducts.indexOf($index);
  517. if (idx > -1) refundState.selectedProducts.splice(idx, 1);
  518. }
  519. }}
  520. />
  521. )
  522. }}
  523. />
  524. <ElTableColumn label="商品名称" min-width={160}>
  525. {{
  526. default: ({ row: r }: any) => (
  527. <div style="display: flex; align-items: center; gap: 8px;">
  528. {r.pic ? (
  529. <ElImage
  530. src={r.pic}
  531. style="width: 40px; height: 40px; border-radius: 4px; flex-shrink: 0;"
  532. fit="cover"
  533. >
  534. {{
  535. error: () => (
  536. <div style="width: 40px; height: 40px; background: #f5f5f5; border-radius: 4px; display: flex; align-items: center; justify-content: center; font-size: 12px; color: #999;">暂无</div>
  537. )
  538. }}
  539. </ElImage>
  540. ) : (
  541. <div style="width: 40px; height: 40px; background: #f5f5f5; border-radius: 4px; display: flex; align-items: center; justify-content: center; font-size: 12px; color: #999; flex-shrink: 0;">暂无</div>
  542. )}
  543. <div>
  544. <span>{r.productName}</span>
  545. {(r.refundedQuantity || 0) > 0 && (
  546. <span style="color: var(--el-color-warning); font-size: 12px; margin-left: 6px;">(已退{r.refundedQuantity}件)</span>
  547. )}
  548. </div>
  549. </div>
  550. )
  551. }}
  552. </ElTableColumn>
  553. <ElTableColumn label="单价" width={90} align="right"
  554. v-slots={{ default: ({ row: r }: any) => <span>¥{(r.price || 0).toFixed(2)}</span> }}
  555. />
  556. <ElTableColumn label="购买数量" width={90} align="center"
  557. v-slots={{ default: ({ row: r }: any) => <span>×{r.productNum || 1}</span> }}
  558. />
  559. <ElTableColumn label="退款数量" width={160} align="center"
  560. v-slots={{
  561. default: ({ $index, row: r }: any) => (
  562. refundState.selectedProducts.includes($index) ? (
  563. <el-input-number
  564. model-value={refundState.refundQuantities[$index] || 1}
  565. min={1}
  566. max={(r.productNum || 1) - (r.refundedQuantity || 0)}
  567. size="small"
  568. controls-position="right"
  569. style="width: 120px"
  570. onUpdate:modelValue={(val: number) => { refundState.refundQuantities[$index] = val; }}
  571. />
  572. ) : <span style="color: #999">-</span>
  573. )
  574. }}
  575. />
  576. <ElTableColumn label="退款金额" width={110} align="right"
  577. v-slots={{
  578. default: ({ $index, row: r }: any) => (
  579. refundState.selectedProducts.includes($index) ? (
  580. <span style="color: #e6a23c; font-weight: 600; font-size: 14px;">
  581. ¥{((r.price || 0) * (refundState.refundQuantities[$index] || 1)).toFixed(2)}
  582. </span>
  583. ) : <span style="color: #999">¥0.00</span>
  584. )
  585. }}
  586. />
  587. </ElTable>
  588. <div style="text-align: right; padding: 14px 0; font-size: 15px; border-bottom: 1px solid #eee; margin-bottom: 12px;">
  589. 退款总金额:
  590. <span style="color: #f56c6c; font-weight: 700; font-size: 18px;">¥{refundTotalAmount.value.toFixed(2)}</span>
  591. </div>
  592. <div style="font-size: 15px; font-weight: 600; margin-bottom: 10px; color: var(--el-text-color-primary);">自定义退款金额</div>
  593. <div style="margin-bottom: 16px; padding: 12px; background: #fafafa; border-radius: 6px;">
  594. {refundState.selectedProducts.length > 0 ? (
  595. <div style="color: #909399; font-size: 13px;">
  596. 已选择商品退款,退款金额根据所选商品自动计算。如需自定义金额,请先取消所有商品选择。
  597. </div>
  598. ) : (
  599. <div>
  600. <el-input-number
  601. model-value={refundState.customAmount}
  602. min={0.01}
  603. max={refundState.orderDetail?.paidAmount || refundState.orderDetail?.totalAmount || 0}
  604. precision={2}
  605. placeholder="输入自定义退款金额"
  606. style="width: 100%"
  607. controls-position="right"
  608. onUpdate:modelValue={(val: number | null) => { refundState.customAmount = val; }}
  609. />
  610. <div style="color: #909399; font-size: 12px; margin-top: 6px;">
  611. 退款金额上限:实付金额 ¥
  612. {((refundState.orderDetail?.paidAmount || refundState.orderDetail?.totalAmount || 0)).toFixed(2)}
  613. ,若不选择商品也未输入金额,则全额退款
  614. </div>
  615. </div>
  616. )}
  617. </div>
  618. <div style="font-size: 15px; font-weight: 600; margin-bottom: 10px; color: var(--el-text-color-primary);">退款原因</div>
  619. <ElForm ref={refundFormRef} model={refundState}>
  620. <ElFormItem
  621. prop="reason"
  622. rules={[{ required: true, message: "请输入退款原因", trigger: "blur" }]}
  623. >
  624. <ElInput
  625. v-model={refundState.reason}
  626. type="textarea"
  627. placeholder="请输入退款原因"
  628. rows={3}
  629. />
  630. </ElFormItem>
  631. </ElForm>
  632. </>
  633. )}
  634. </div>
  635. ),
  636. beforeSure: async (done) => {
  637. // 校验:必须选择商品或输入自定义金额(都不选则全额退款)
  638. if (refundState.selectedProducts.length === 0 && (!refundState.customAmount || refundState.customAmount <= 0)) {
  639. // 未选择商品也未输入金额,走全额退款(确认提示)
  640. try {
  641. await ElMessageBox.confirm(
  642. "未选择商品也未输入自定义金额,将对整单实付金额进行全额退款,是否继续?",
  643. "确认全额退款",
  644. { confirmButtonText: "确认退款", cancelButtonText: "取消", type: "warning" }
  645. );
  646. } catch {
  647. return;
  648. }
  649. }
  650. const valid = await refundFormRef.value?.validate().catch(() => false);
  651. if (!valid) return;
  652. // 构建请求体
  653. const refundData: any = { reason: refundState.reason };
  654. if (refundState.selectedProducts.length > 0) {
  655. refundData.products = refundState.selectedProducts.map((i) => {
  656. const p = refundState.orderDetail.products[i];
  657. return {
  658. productId: p.productId || p.id,
  659. productName: p.productName,
  660. quantity: refundState.refundQuantities[i] || 1,
  661. price: p.price || 0
  662. };
  663. });
  664. } else if (refundState.customAmount && refundState.customAmount > 0) {
  665. refundData.refundAmount = refundState.customAmount;
  666. }
  667. // 两者都没有 → 全额退款,不传 products 和 refundAmount
  668. try {
  669. const res = await refundOrder(row.id, refundData);
  670. if (res.code === 200 || res.code === 0) {
  671. message(`订单 ${row.orderNo} 退款成功`, { type: "success" });
  672. done();
  673. onSearch();
  674. } else {
  675. message(res.message || "退款失败", { type: "error" });
  676. }
  677. } catch (error) {
  678. message("退款失败", { type: "error" });
  679. }
  680. }
  681. });
  682. }
  683. async function handleRepairPayScore() {
  684. const repairForm = reactive({ orderId: "", outOrderNo: "" });
  685. addDialog({
  686. title: "修复支付分扣费",
  687. width: "460px",
  688. draggable: true,
  689. closeOnClickModal: false,
  690. contentRenderer: () => (
  691. <div>
  692. <div style="margin-bottom: 12px;">
  693. <div style="margin-bottom: 4px; font-size: 13px; color: var(--el-text-color-regular);">
  694. 订单ID 或 订单编号 <span style="color: #f56c6c;">*</span>
  695. </div>
  696. <ElInput v-model={repairForm.orderId} placeholder="如 202607081727441260270668" />
  697. </div>
  698. <div>
  699. <div style="margin-bottom: 4px; font-size: 13px; color: var(--el-text-color-regular);">
  700. outOrderNo(选填)
  701. </div>
  702. <ElInput v-model={repairForm.outOrderNo} placeholder="如 PS1782351340B150534,本地丢失时从微信商户后台获取" />
  703. <div style="margin-top: 4px; font-size: 12px; color: #909399;">
  704. 仅在本地 payScoreOrderId 丢失时填写,从微信商户后台「支付分订单」中查找
  705. </div>
  706. </div>
  707. </div>
  708. ),
  709. beforeSure: async (done) => {
  710. const orderId = repairForm.orderId.trim();
  711. if (!orderId) {
  712. message("请输入订单ID或订单编号", { type: "warning" });
  713. return;
  714. }
  715. const outOrderNo = repairForm.outOrderNo.trim() || undefined;
  716. try {
  717. const res = await repairPayScorePayment(orderId, outOrderNo);
  718. if (res.code === 200) {
  719. message(res.message || "修复完成", { type: "success" });
  720. onSearch();
  721. } else {
  722. message(res.message || "修复失败", { type: "error" });
  723. }
  724. done();
  725. } catch {
  726. message("修复请求失败", { type: "error" });
  727. }
  728. }
  729. });
  730. }
  731. async function handlePayScoreCancel(cancelForm: { outOrderNo: string; reason?: string }) {
  732. const outOrderNo = cancelForm.outOrderNo?.trim();
  733. if (!outOrderNo) {
  734. message("请输入 outOrderNo", { type: "warning" });
  735. return;
  736. }
  737. try {
  738. const res = await cancelPayScoreOrder({
  739. outOrderNo,
  740. reason: cancelForm.reason || undefined
  741. });
  742. if (res.code === 200) {
  743. message(`支付分订单 ${outOrderNo} 取消成功`, { type: "success" });
  744. } else {
  745. message(res.message || "取消失败", { type: "error" });
  746. }
  747. } catch (error: any) {
  748. message(error?.message || "取消失败", { type: "error" });
  749. }
  750. }
  751. onMounted(() => {
  752. onSearch();
  753. });
  754. return {
  755. form,
  756. loading,
  757. columns,
  758. dataList,
  759. pagination,
  760. onSearch,
  761. resetForm,
  762. handleDetail,
  763. handleRefund,
  764. handleRepairPayScore,
  765. handlePayScoreCancel,
  766. handleQueryFromHaha,
  767. handleSizeChange,
  768. handleCurrentChange
  769. };
  770. }