SImportModal2.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493
  1. const n = `<template>
  2. <s-modal
  3. v-model:value="isVisible"
  4. :title="$l(title)"
  5. :width="width"
  6. :mask-closable="false"
  7. :show-full-screen="false"
  8. @handCancel="handleClose"
  9. >
  10. <div class="header-steps">
  11. <a-steps v-model:current="activeStep" type="navigation" size="small">
  12. <a-step :title="$l('上传文件')" :disabled="true" />
  13. <a-step :title="$l('数据预览')" :disabled="true" />
  14. <a-step :title="$l('导入数据')" :disabled="true" />
  15. </a-steps>
  16. </div>
  17. <!-- 第一步:上传文件 -->
  18. <div class="import-main" v-show="activeStep == 0">
  19. <div class="upload">
  20. <div class="up_right">
  21. <p class="title">{{ $l('上传填好的数据表') }}</p>
  22. <p class="tip">
  23. {{ $l('文件后缀名必须是xls或xlsx,文件大小不超过500KB,最多支持导入1000条数据') }}
  24. </p>
  25. <a-upload
  26. v-model:file-list="fileList"
  27. class="upload-area"
  28. accept=".xls,.xlsx"
  29. :max-count="1"
  30. :custom-request="customRequest"
  31. :before-upload="beforeUpload"
  32. @remove="handleFileRemove"
  33. >
  34. <a-button type="link">{{ $l('上传文件') }}</a-button>
  35. </a-upload>
  36. </div>
  37. </div>
  38. <div class="upload">
  39. <div class="up_right">
  40. <p class="title">{{ $l('填写导入数据信息') }}</p>
  41. <p class="tip">
  42. {{ $l('请按照数据模板的格式准备导入数据,模板中的表头名称不可更改,表头行不能删除') }}
  43. </p>
  44. <div class="extra-select-wrapper">
  45. <!-- 业务自定义参数(如设备分类)由外部传入选项,选中值会随各导入接口一起提交 -->
  46. <a-select
  47. v-if="typeSelect"
  48. v-model:value="typeValue"
  49. :options="typeSelect.options"
  50. :loading="typeSelect.loading"
  51. :placeholder="typeSelect.placeholder || $l('请选择')"
  52. style="width: 200px; margin-right: 12px"
  53. @change="handleTypeChange"
  54. />
  55. <a-button type="link" :loading="downloading" @click="handleTemplateDownload">{{
  56. $l('下载模板')
  57. }}</a-button>
  58. </div>
  59. </div>
  60. </div>
  61. </div>
  62. <!-- 第二步:数据预览 -->
  63. <div class="import-main" v-show="activeStep == 1">
  64. <a-table
  65. :data-source="list"
  66. :columns="previewColumns"
  67. size="small"
  68. :pagination="false"
  69. :scroll="{ x: 'max-content', y: '420px' }"
  70. class="import-preview-table"
  71. >
  72. <template #bodyCell="{ column, record, index }">
  73. <template v-for="item in localColumns" :key="item.dataIndex">
  74. <template v-if="column.dataIndex === item.dataIndex">
  75. <a-input v-model:value="record[column.dataIndex]" />
  76. </template>
  77. </template>
  78. <template v-if="column.dataIndex === 'action'">
  79. <a-button
  80. class="action-btn"
  81. type="link"
  82. danger
  83. @click="handleDelItem(index)"
  84. size="small"
  85. >{{ $l('删除') }}</a-button
  86. >
  87. </template>
  88. </template>
  89. </a-table>
  90. </div>
  91. <!-- 第三步:导入结果 -->
  92. <div class="import-main" v-show="activeStep == 2">
  93. <div class="success" v-if="!result.resultType">
  94. <p class="success-title">{{ $l('批量导入成功') }}</p>
  95. <p class="success-tip">{{ $l('您已成功导入') }}{{ result.snum }}{{ $l('条数据') }}</p>
  96. </div>
  97. <div class="unsuccess" v-if="result.resultType">
  98. <div class="upload error-show">
  99. <div class="up_right">
  100. <p class="tip success-tip">
  101. {{ $l('正常数据条数') }}:<span>{{ result.snum }}{{ $l('条') }}</span>
  102. </p>
  103. <p class="tip error-tip">
  104. {{ $l('异常数据条数') }}:<span>{{ result.fnum }}{{ $l('条') }}</span>
  105. </p>
  106. </div>
  107. </div>
  108. <div class="conTips">
  109. <p>{{ $l('以下文件数据为导入异常数据') }}</p>
  110. <a-button type="link" :loading="downloading" @click="handleExportExceptionData">{{
  111. $l('导出异常数据')
  112. }}</a-button>
  113. </div>
  114. <a-table
  115. :data-source="resultList"
  116. :columns="resultColumns"
  117. size="small"
  118. :pagination="false"
  119. :scroll="{ x: 'max-content', y: '205px' }"
  120. />
  121. </div>
  122. </div>
  123. <template #footer>
  124. <a-button v-if="activeStep == 0" @click="handleClose">{{ $l('取消') }}</a-button>
  125. <a-button v-if="activeStep === 1" @click="handlePrev">{{ $l('上一步') }}</a-button>
  126. <a-button
  127. type="primary"
  128. :loading="btnLoading"
  129. v-if="activeStep < 2"
  130. :disabled="activeStep === 0 && (!fileName || (typeSelect && !typeValue))"
  131. @click="handleNext"
  132. >
  133. {{ $l('下一步') }}
  134. </a-button>
  135. <a-button type="primary" v-else @click="handleClose(true)">{{ $l('关闭') }}</a-button>
  136. </template>
  137. </s-modal>
  138. </template>
  139. <script setup>
  140. /**
  141. * SImportModal 通用批量导入弹窗
  142. * 三步式:上传文件 -> 数据预览(可编辑/删除行)-> 导入结果(含异常数据导出)
  143. *
  144. * 用法(基座重新构建发布后,业务项目可直接使用 <s-import-modal>):
  145. * <s-import-modal ref="importModalRef" :upload-url="uploadUrl" :columns="columns"
  146. * :apis="apis" :type-select="typeSelect" @reload="reload" />
  147. * importModalRef.value.show()
  148. */
  149. import { ref, computed, watch } from 'vue'
  150. defineOptions({ name: 'SImportModal' })
  151. const props = defineProps({
  152. // 显隐(v-model:value)
  153. value: { type: Boolean, default: false },
  154. // 弹窗标题
  155. title: { type: String, default: () => window.$l('批量导入') },
  156. // 弹窗宽度
  157. width: { type: [String, Number], default: 1000 },
  158. // 文件上传地址(完整网关地址,如 /monitor/DeviceInfo/Uploader)
  159. uploadUrl: { type: String, default: '' },
  160. // 预览/结果表格列:[{ title, dataIndex, width }],作为默认列,接口返回 headerRow 后以接口为准
  161. columns: { type: Array, default: () => [] },
  162. // 四个导入接口方法:{ templateDownload, importPreview, importData, exportExceptionData }
  163. apis: {
  164. type: Object,
  165. default: () => ({})
  166. },
  167. // 可选的业务参数下拉(如设备分类):{ options: [{ label, value }], value, placeholder, loading }
  168. // 选中值会以 { extraKey: value } 的形式随各接口一起提交
  169. typeSelect: { type: Object, default: null },
  170. // typeSelect 选中值提交时的字段名
  171. extraKey: { type: String, default: 'deviceTypeId' }
  172. })
  173. const emit = defineEmits(['update:value', 'reload'])
  174. const activeStep = ref(0)
  175. const fileName = ref('')
  176. const fileList = ref([])
  177. const btnLoading = ref(false)
  178. const downloading = ref(false)
  179. const list = ref([])
  180. // 预览/结果表格列(接口返回 headerRow 后由接口决定,避免直接修改 props.columns)
  181. const localColumns = ref([])
  182. const result = ref({})
  183. const resultList = ref([])
  184. const typeValue = ref(undefined)
  185. const isVisible = computed({
  186. get: () => props.value,
  187. set: (val) => emit('update:value', val)
  188. })
  189. const previewColumns = computed(() => [
  190. { width: 50, title: window.$l('序号'), align: 'center', customRender: ({ index }) => index + 1 },
  191. ...localColumns.value,
  192. { title: window.$l('操作'), dataIndex: 'action', key: 'action', width: 50, fixed: 'right' }
  193. ])
  194. const resultColumns = computed(() => [
  195. { width: 50, title: window.$l('序号'), align: 'center', customRender: ({ index }) => index + 1 },
  196. ...localColumns.value,
  197. { title: window.$l('异常原因'), dataIndex: 'errorsInfo', width: 150, fixed: 'right' }
  198. ])
  199. // 随接口一起提交的额外参数(如设备分类)
  200. const extraParams = computed(() => {
  201. if (!props.typeSelect) return {}
  202. return typeValue.value ? { [props.extraKey]: typeValue.value } : {}
  203. })
  204. // 外部传入的选项变化时默认选中第一项
  205. watch(
  206. () => props.typeSelect?.options,
  207. (options) => {
  208. if (options && options.length) {
  209. const hasValue = options.some((item) => item.value === typeValue.value)
  210. if (!hasValue) typeValue.value = options[0].value
  211. }
  212. },
  213. { immediate: true, deep: true }
  214. )
  215. const resetState = () => {
  216. activeStep.value = 0
  217. fileName.value = ''
  218. fileList.value = []
  219. btnLoading.value = false
  220. list.value = []
  221. localColumns.value = []
  222. result.value = {}
  223. resultList.value = []
  224. if (props.typeSelect) {
  225. typeValue.value = props.typeSelect.options?.length
  226. ? props.typeSelect.options[0].value
  227. : undefined
  228. }
  229. }
  230. const show = () => {
  231. isVisible.value = true
  232. resetState()
  233. }
  234. // 统一取数:兼容网关返回 { code, data } 与直接返回数据两种格式
  235. const unwrap = (res) => {
  236. return res && Object.prototype.hasOwnProperty.call(res, 'data') ? res.data : res
  237. }
  238. // 把接口返回的 headerRow([{ fullName, id }]) 转成表格列配置
  239. const transformHeaderRow = (headerRow) => {
  240. return (headerRow || []).map((col) => ({
  241. title: col.fullName || '',
  242. dataIndex: col.id || '',
  243. key: col.id || ''
  244. }))
  245. }
  246. // 上传(复用 window.$utils.http,自动携带网关与 user-token 鉴权)
  247. const customRequest = ({ file, onSuccess, onError }) => {
  248. const http = window.$utils?.http
  249. if (!http) {
  250. window.$message.error(window.$l('未获取到请求工具,无法上传'))
  251. onError && onError(new Error('http not found'))
  252. return
  253. }
  254. const formData = new FormData()
  255. formData.append('file', file)
  256. return http({
  257. url: props.uploadUrl,
  258. method: 'post',
  259. data: formData,
  260. headers: { 'Content-Type': 'multipart/form-data' }
  261. })
  262. .then((res) => {
  263. const data = unwrap(res) || {}
  264. const name = data?.name ?? data?.fileName ?? ''
  265. if (!name) throw new Error(window.$l('上传返回文件名无效'))
  266. fileName.value = name
  267. onSuccess && onSuccess(res)
  268. })
  269. .catch((error) => {
  270. window.$message.error(typeof error?.msg === 'string' ? error.msg : window.$l('上传失败'))
  271. onError && onError(error)
  272. })
  273. }
  274. const beforeUpload = (file) => {
  275. const fileType = file.name.replace(/.+\\./, '')
  276. const isAccept = ['xls', 'xlsx'].indexOf(fileType.toLowerCase()) !== -1
  277. if (!isAccept) {
  278. window.$message.error(window.$l('文件格式不正确'))
  279. return false
  280. }
  281. if (file.size / 1024 >= 500) {
  282. window.$message.error(window.$l('文件大小超过500KB'))
  283. return false
  284. }
  285. return true
  286. }
  287. const handleFileRemove = (file) => {
  288. return new Promise((resolve, reject) => {
  289. window.$modal.confirm({
  290. title: window.$l('提示'),
  291. content: \`\${window.$l('确定移除')}\${file.name}?\`,
  292. onOk: () => {
  293. fileName.value = ''
  294. resolve()
  295. },
  296. onCancel: () => reject()
  297. })
  298. })
  299. }
  300. const handleTypeChange = () => {
  301. // 切换业务参数时清空已上传的文件与预览数据
  302. if (fileList.value.length || fileName.value) {
  303. resetState()
  304. }
  305. }
  306. const handlePrev = () => {
  307. if (activeStep.value == 0) return
  308. activeStep.value -= 1
  309. }
  310. const handleNext = () => {
  311. if (activeStep.value == 0) {
  312. if (!fileList.value.length || !fileName.value) {
  313. window.$message.warning(window.$l('请先上传文件'))
  314. return
  315. }
  316. if (props.typeSelect && !typeValue.value) {
  317. window.$message.warning(
  318. props.typeSelect.placeholder
  319. ? \`\${window.$l('请先')}\${props.typeSelect.placeholder}\`
  320. : window.$l('请先选择业务参数')
  321. )
  322. return
  323. }
  324. btnLoading.value = true
  325. props.apis
  326. .importPreview({ fileName: fileName.value, ...extraParams.value })
  327. .then((res) => {
  328. const data = unwrap(res) || {}
  329. list.value = data.dataRow || []
  330. // 用接口返回的 headerRow 生成表格列(存本地,避免修改 props.columns)
  331. localColumns.value = transformHeaderRow(data.headerRow)
  332. btnLoading.value = false
  333. activeStep.value += 1
  334. })
  335. .catch(() => {
  336. btnLoading.value = false
  337. })
  338. return
  339. }
  340. if (activeStep.value == 1) {
  341. if (!list.value.length) {
  342. window.$message.warning(window.$l('导入数据为空'))
  343. return
  344. }
  345. btnLoading.value = true
  346. props.apis
  347. .importData({ list: list.value, ...extraParams.value })
  348. .then((res) => {
  349. const data = unwrap(res) || {}
  350. result.value = data
  351. resultList.value = data.failResult || []
  352. btnLoading.value = false
  353. activeStep.value += 1
  354. emit('reload')
  355. })
  356. .catch(() => {
  357. btnLoading.value = false
  358. })
  359. }
  360. }
  361. // 通过返回的 url 触发下载
  362. const downloadByUrl = (url) => {
  363. if (!url) {
  364. window.$message.error(window.$l('未获取到下载地址'))
  365. return
  366. }
  367. const a = document.createElement('a')
  368. a.href = url
  369. a.download = ''
  370. document.body.appendChild(a)
  371. a.click()
  372. document.body.removeChild(a)
  373. }
  374. const handleTemplateDownload = () => {
  375. if (props.typeSelect && !typeValue.value) {
  376. window.$message.warning(
  377. props.typeSelect.placeholder
  378. ? \`\${window.$l('请先')}\${window.$l(props.typeSelect.placeholder)}\`
  379. : window.$l('请先选择业务参数')
  380. )
  381. return
  382. }
  383. downloading.value = true
  384. props.apis
  385. .templateDownload({ ...extraParams.value })
  386. .then((res) => {
  387. const data = unwrap(res) || {}
  388. downloadByUrl(data?.url)
  389. })
  390. .catch(() => window.$message.error(window.$l('模板下载失败')))
  391. .finally(() => {
  392. downloading.value = false
  393. })
  394. }
  395. const handleExportExceptionData = () => {
  396. downloading.value = true
  397. props.apis
  398. .exportExceptionData({ list: resultList.value, ...extraParams.value })
  399. .then((res) => {
  400. const data = unwrap(res) || {}
  401. downloadByUrl(data?.url)
  402. })
  403. .catch(() => window.$message.error(window.$l('异常数据导出失败')))
  404. .finally(() => {
  405. downloading.value = false
  406. })
  407. }
  408. const handleDelItem = (index) => {
  409. list.value.splice(index, 1)
  410. }
  411. const handleClose = (reload = false) => {
  412. isVisible.value = false
  413. if (reload) emit('reload')
  414. }
  415. defineExpose({ show, resetState })
  416. <\/script>
  417. <style lang="less" scoped>
  418. .header-steps {
  419. margin-bottom: 16px;
  420. }
  421. .upload {
  422. display: flex;
  423. justify-content: flex-start;
  424. align-items: flex-start;
  425. padding: 16px;
  426. margin-bottom: 16px;
  427. background-color: var(--s-bg-color-hover);
  428. border-radius: 6px;
  429. .up_right {
  430. flex: 1;
  431. .title {
  432. font-weight: 500;
  433. margin-bottom: 8px;
  434. }
  435. .tip {
  436. color: var(--s-text-color-secondary);
  437. font-size: 13px;
  438. margin-bottom: 8px;
  439. }
  440. }
  441. }
  442. .extra-select-wrapper {
  443. display: flex;
  444. align-items: center;
  445. margin-top: 8px;
  446. }
  447. .success {
  448. text-align: center;
  449. padding: 40px 0;
  450. .success-title {
  451. font-size: 18px;
  452. font-weight: 500;
  453. margin-bottom: 8px;
  454. }
  455. .success-tip {
  456. color: var(--s-color-success);
  457. }
  458. }
  459. .conTips {
  460. display: flex;
  461. justify-content: space-between;
  462. align-items: center;
  463. margin: 8px 0;
  464. }
  465. </style>
  466. `;
  467. export {
  468. n as default
  469. };