huangbin 4 lat temu
rodzic
commit
7dc01c353b

+ 68 - 0
src/common/components/uploadImg/index.vue

@@ -0,0 +1,68 @@
+<template>
+  <div class="upload">
+    <a-upload :action="uploadUrl"
+              v-model:file-list="uploadImgList"
+              @change="uploadAction">
+      <a-button class="uploadBtn">上传</a-button>
+    </a-upload>
+    <div class="look"
+         v-if="uploadImgList.length"
+         @click="previewImg(uploadImgList[0])">查看附件</div>
+    <a-modal :visible="previewVisible"
+             :footer="null"
+             @cancel="cancelImg">
+      <img alt="预览附件"
+           style="width: 100%"
+           :src="previewImage" />
+    </a-modal>
+  </div>
+</template>
+
+<script lang="ts">
+import { defineComponent } from '@/common/export/table';
+import { handlePreviewImg, handleUplodImg } from '@/common/setup/upload';
+import { FileInfo, FileItem } from '@/common/setup/upload/interface';
+import { PropType, watchEffect } from '@vue/runtime-core';
+
+export default defineComponent({
+    name: 'upload-img',
+    props: {
+        visible: {
+            type: Boolean,
+            default: false,
+        },
+        imgList: {
+            type: Array as PropType<FileItem[]>,
+            default: [],
+        },
+    },
+    setup(props, context) {
+        // 上传附件
+        const { uploadUrl, uploadImgList, uploadChange, getUploadUrl, getUploadResultUrl, getImg } = handleUplodImg();
+        // 预览附件
+        const { previewVisible, previewImage, cancelImg, previewImg } = handlePreviewImg();
+        function uploadAction(obj: FileInfo) {
+            uploadChange(obj).then(() => {
+                const arr = getUploadResultUrl();
+                context.emit('upload', arr);
+            });
+        }
+        watchEffect(() => {
+            if (props.visible) {
+                getUploadUrl();
+                uploadImgList.value = props.imgList;
+            }
+        });
+        return {
+            uploadUrl,
+            uploadAction,
+            uploadChange,
+            uploadImgList,
+            previewVisible,
+            previewImage,
+            cancelImg,
+            previewImg,
+        };
+    },
+});
+</script>

+ 136 - 0
src/common/setup/upload/index.ts

@@ -0,0 +1,136 @@
+import { serviceURL } from "@/services/request";
+import { message } from "ant-design-vue";
+import { ref } from "vue";
+import { FileInfo, FileItem } from "./interface";
+
+function getBase64(file: File) {
+    return new Promise((resolve, reject) => {
+        const reader = new FileReader();
+        reader.readAsDataURL(file);
+        reader.onload = () => resolve(reader.result);
+        reader.onerror = error => reject(error);
+    });
+}
+
+
+function getImg(imgURl: string) {
+    let result = '';
+    if (imgURl) {
+        result = serviceURL.uploadUrl.replace('/upload', '') + imgURl.replace('./', '/');
+    }
+    return result;
+}
+export function handleUplodImg(limitSize = 1) {
+    // 上传地址
+    const uploadUrl = ref<string>('')
+    // 图片列表
+    const uploadImgList = ref<FileItem[]>([])
+
+    /**
+     * 获取上传地址,记住此方法需要在初始化数据加载完成(initData)之后 调用
+     */
+    function getUploadUrl() {
+        uploadUrl.value = serviceURL.uploadUrl
+    }
+
+    /**
+     * 上传图片变更
+     * @param param0 
+     */
+    function uploadChange({ file, fileList }: FileInfo) {
+        let resFileList = [...fileList];
+        // 1. Limit the number of uploaded files
+        resFileList = resFileList.slice(-limitSize);
+
+        // 2. 处理上传异常
+        if (file.status !== 'uploading') {
+            if (file.xhr?.status !== 200) {
+                message.error(`服务器返回状态不为200: ${file.xhr?.statusText}`)
+            }
+
+        }
+        if (file.status === 'done') {
+            resFileList.forEach(el => {
+                if (el.response) {
+                    el.name = el.response[0].fileName
+                }
+            })
+        }
+        uploadImgList.value = resFileList;
+        return Promise.resolve(uploadImgList.value)
+    }
+    /**
+     * 获取图片的filePath
+     * @returns 
+     */
+    function getUploadResultUrl(): string[] {
+        const result: string[] = []
+        uploadImgList.value.forEach(el => {
+            if (Array.isArray(el.response)) {
+                el.response.forEach(e => {
+                    result.push(e.filePath)
+                })
+            } else {
+                console.warn('ant-design获取服务返回图片的数据发生变化,请在控制台查看')
+                console.log(el)
+            }
+        })
+        return result;
+    }
+
+    return { uploadUrl, uploadImgList, uploadChange, getUploadUrl, getUploadResultUrl, getImg }
+}
+
+/**
+ * 预览图片
+ */
+export function handlePreviewImg() {
+    // 是否查看附件
+    const previewVisible = ref<boolean>(false)
+    // 预览图片地址
+    const previewImage = ref<string | undefined>('');
+    /**
+     * 关闭查看图片
+     */
+    function cancelImg() {
+        previewVisible.value = false;
+    }
+    /**
+    * 预览图片
+    */
+    async function previewImg(file: FileItem) {
+        if (!file.url && !file.preview) {
+            file.preview = (await getBase64(file.originFileObj)) as string;
+        }
+        previewImage.value = file.url || file.preview;
+        previewVisible.value = true;
+
+    }
+    return { previewVisible, previewImage, cancelImg, previewImg }
+}
+
+/**
+ * 获取上传好的图片地址
+ * @returns 
+ */
+export function getUploadImg() {
+    const imgs = ref<string[]>([])
+    const uploadImgList = ref<FileItem[]>([])
+    function uploadImgAction(value: string[]) {
+        imgs.value = value
+    }
+    function handleImg(value: string) {
+        const arr = value.split(',')
+        return arr.map((e, i) => {
+            const str = JSON.parse(e);
+            const lastIndex = str.lastIndexOf('/') + 1;
+            return {
+                uid: i.toString(),
+                name: str.slice(lastIndex, str.length),
+                url: getImg(str),
+            };
+        });
+
+    }
+    return { imgs, uploadImgAction, uploadImgList, handleImg }
+}

+ 14 - 0
src/common/setup/upload/interface.ts

@@ -0,0 +1,14 @@
+export interface FileItem {
+    uid: string;
+    name?: string;
+    status?: string;
+    response?: any;
+    url?: string;
+    preview?: string;
+    originFileObj?: any;
+    xhr?: XMLHttpRequest
+}
+export interface FileInfo {
+    file: FileItem;
+    fileList: FileItem[];
+}

+ 4 - 0
src/services/request/serviceURL.ts

@@ -70,6 +70,10 @@ export const commonSearchUrl = (url: string): string => {
     return serviceURL.commSearchUrl + url;
 };
 
+export const getUplodaUrl = (): string => {
+    return serviceURL.uploadUrl
+}
+
 export const setServiceURL = (config: URL): void => {
     // console.log('URL', config);
     // 外网环境(175),外包同事使用

+ 1 - 1
src/utils/objHandle/index.ts

@@ -44,7 +44,7 @@ export function mergeTwoObj(a: any, b: any, callBack?: Function) {
  * @param data 
  * @returns 
  */
-export function objectToUint8Array(data: object) {
+export function objectToUint8Array(data: object | string) {
     const rawData: string = JSON.stringify(data);
     const outputArray = new Uint8Array(rawData.length);
     for (let i = 0; i < rawData.length; ++i) {

+ 13 - 13
src/views/information/spot-contract/components/add/index.vue

@@ -112,13 +112,8 @@
           <a-col :span="12">
             <a-form-item label="合同附件"
                          name="ContractAttachment">
-              <div class="upload">
-                <a-upload action="https://www.mocky.io/v2/5cc8019d300000980a055e76"
-                          :transform-file="transformFile">
-                  <a-button class="uploadBtn">上传</a-button>
-                </a-upload>
-                <div class="look">查看附件</div>
-              </div>
+              <UploadImg :visible="visible"
+                         @upload="uploadImgAction" />
             </a-form-item>
           </a-col>
         </a-row>
@@ -411,14 +406,12 @@
 </template>
 
 <script lang="ts">
-import { defineComponent, PropType, ref, toRaw, watchEffect } from 'vue';
+import { defineComponent, PropType, ref, watchEffect } from 'vue';
 import { closeModal } from '@/common/setup/modal/index';
-import { initData } from '@/common/methods';
 import { addContractReq } from './setup';
 import { getUserName, getUsrId } from '@/services/bus/user';
 import { getGoodsList } from '@/services/bus/goods';
 import { Goods } from '@/services/go/ermcp/goodsInfo/interface';
-import { ValidateErrorEntity } from 'ant-design-vue/lib/form/interface';
 import { FormState } from '../interface';
 import { formatTime } from '@/common/methods/format';
 import { Ermcp3ContractRsp } from '@/services/go/ermcp/spot-contract/interface';
@@ -427,10 +420,12 @@ import { handleFormRule, handleContract, handleDeliveryGoods, handleAmout, handl
 import { validateAction } from '@/common/setup/form';
 import { ErmcpLoginUser } from '@/services/go/ermcp/account/interface';
 import { handlerManagerList } from '@/common/setup/user';
+import { getUploadImg } from '@/common/setup/upload';
+import UploadImg from '@/common/components/uploadImg/index.vue';
 
 export default defineComponent({
     name: 'add-spot-contract',
-    components: {},
+    components: { UploadImg },
     props: {
         selectedRow: {
             type: Object as PropType<Ermcp3ContractRsp>,
@@ -466,10 +461,9 @@ export default defineComponent({
         const merchandiserList = ref<ErmcpLoginUser[]>([]);
         // 现货商品列表
         const goodsList = ref<Goods[]>([]);
+        const { imgs, uploadImgAction } = getUploadImg();
         watchEffect(() => {
             if (visible.value) {
-                console.log('merchandiserList', merchandiserList);
-
                 queryCustomList();
                 getDeliveryGoods();
                 queryTradeManager();
@@ -503,6 +497,10 @@ export default defineComponent({
                     const EndDate = fn(pDate[1]);
                     Object.assign(param, { StartDate, EndDate });
                 }
+                // 合同附件
+                if (imgs.value.length) {
+                    param.ContractAttachment = imgs.value[0];
+                }
                 sendReq(param, loading, OperateType)
                     .then((res) => {
                         context.emit('refresh');
@@ -511,6 +509,7 @@ export default defineComponent({
                     .catch((err) => {});
             });
         }
+
         function closeAction() {
             //清空添加成功后的数据,确保在此新增打开是个空数据
             Object.assign(formState, initFormData());
@@ -550,6 +549,7 @@ export default defineComponent({
             traderList,
             businesserList,
             merchandiserList,
+            uploadImgAction,
         };
     },
 });

+ 6 - 2
src/views/information/spot-contract/components/add/setup.ts

@@ -3,6 +3,7 @@ import {
     GldErmcpSpotContractOperateReq,
     GldSpotContractInfo
 } from "@/services/proto/spotcontract/interface";
+import { objectToUint8Array } from "@/utils/objHandle";
 import { orderContractControl } from "@/views/information/spot-contract/components/setup";
 import moment from 'moment';
 import { Ref } from 'vue';
@@ -40,7 +41,6 @@ export function addContractReq() {
             // 以下选填
             BizType: form.BizType, //                       业务类型 - 1:套保 2:套利
             Remark: form.Remark,  //       合同备注
-            // ContractAttachment: ,  // 合同附件
             ContractMargin: form.ContractMargin ? Number(form.ContractMargin) : 0, //         合同保证金
 
             Amount: [1, 3].includes(form.PriceType) ? Number(form.Price) * Number(form.Qty) : 0, //    金额
@@ -57,12 +57,16 @@ export function addContractReq() {
             TradeUserID: form.TradeUserID || 0, //           交易员ID
             SaleUserID: form.SaleUserID || 0,//             业务员id
         }
+        // 合同附件
+        info.ContractAttachment = form.ContractAttachment ? objectToUint8Array(form.ContractAttachment) : new Uint8Array()
+
         const params: GldErmcpSpotContractOperateReq = {
             SpotContractID: '0',
             OperateType,
             Remark: '',
             Info: info,
         }
+
         return orderContractControl(params, loading)
             .then(res => {
                 return Promise.resolve(res);
@@ -73,4 +77,4 @@ export function addContractReq() {
     }
 
     return { sendReq }
-}
+}

+ 1 - 1
src/views/information/spot-contract/components/interface.ts

@@ -6,7 +6,7 @@ export interface FormState {
     BuyUserID: number | undefined// uint64 采购方ID
     SellUserID: number | undefined// uint64 客户ID
     // SignDate: string // string 签订日期
-    ContractAttachment: Uint8Array // bytes 合同附件
+    ContractAttachment: string // bytes 合同附件
     ContractMargin: number | null // double 合同保证金
     DeliveryGoodsID: number | undefined  // uint64 现货品种ID
     WrStandardID: number | undefined   // uint64 现货商品ID

+ 24 - 12
src/views/information/spot-contract/components/modify/index.vue

@@ -109,13 +109,9 @@
           <a-col :span="12">
             <a-form-item label="合同附件"
                          name="ContractAttachment">
-              <div class="upload">
-                <a-upload action="https://www.mocky.io/v2/5cc8019d300000980a055e76"
-                          :transform-file="transformFile">
-                  <a-button class="uploadBtn">上传</a-button>
-                </a-upload>
-                <div class="look">查看附件</div>
-              </div>
+              <UploadImg :visible="visible"
+                         :imgList="uploadImgList"
+                         @upload="uploadImgAction" />
             </a-form-item>
           </a-col>
         </a-row>
@@ -404,6 +400,13 @@
         </a-row>
       </fieldset>
     </a-form>
+    <a-modal :visible="previewVisible"
+             :footer="null"
+             @cancel="cancelImg">
+      <img alt="预览附件"
+           style="width: 100%"
+           :src="previewImage" />
+    </a-modal>
   </a-modal>
 </template>
 
@@ -423,6 +426,8 @@ import { mergeTwoObj } from '@/utils/objHandle';
 import { validateAction } from '@/common/setup/form';
 import { ErmcpLoginUser } from '@/services/go/ermcp/account/interface';
 import { handlerManagerList } from '@/common/setup/user';
+import { getUploadImg } from '@/common/setup/upload';
+import UploadImg from '@/common/components/uploadImg/index.vue';
 
 export default defineComponent({
     name: 'spot_contract_btn_modify',
@@ -432,7 +437,7 @@ export default defineComponent({
             default: {},
         },
     },
-    components: {},
+    components: { UploadImg },
     setup(props, context) {
         const { visible, cancel } = closeModal('spot_contract_btn_modify');
         const loading = ref<boolean>(false);
@@ -462,10 +467,10 @@ export default defineComponent({
         const merchandiserList = ref<ErmcpLoginUser[]>([]);
         // 现货商品列表
         const goodsList = ref<Goods[]>([]);
+        const { imgs, uploadImgAction, uploadImgList, handleImg } = getUploadImg();
         watchEffect(() => {
-            // // formState.ContractAttachment = props.selectedRow.attachment
-            // formState.ContractAttachment = new Uint8Array()
             if (visible.value) {
+                console.log('selectedRow', props.selectedRow);
                 queryCustomList();
                 getDeliveryGoods();
                 goodsList.value = getGoodsList();
@@ -476,7 +481,7 @@ export default defineComponent({
                 queryTradeManager();
                 mergeTwoObj(formState, props.selectedRow);
                 isSell.value = formState.ContractType === 1 ? false : true;
-                const { deliverygoodsid, qty, price, wrstandardid, spotgoodsbrandid } = props.selectedRow;
+                const { deliverygoodsid, qty, price, wrstandardid, spotgoodsbrandid, currencyid, attachment } = props.selectedRow;
                 if (deliverygoodsid) {
                     deliveryGoodsChange(deliverygoodsid);
                     if (wrstandardid) {
@@ -487,7 +492,11 @@ export default defineComponent({
                 }
                 formState.Qty = qty.toString();
                 formState.Price = price.toString();
-                formState.CurrencyID = props.selectedRow.currencyid;
+                formState.CurrencyID = currencyid;
+                formState.ContractAttachment = attachment;
+                if (attachment) {
+                    uploadImgList.value = handleImg(attachment);
+                }
             }
         });
         function submit() {
@@ -555,6 +564,9 @@ export default defineComponent({
             traderList,
             businesserList,
             merchandiserList,
+            imgs,
+            uploadImgAction,
+            uploadImgList,
         };
     },
 });

+ 1 - 1
src/views/information/spot-contract/components/setup.ts

@@ -76,7 +76,7 @@ export function handleFromState() {
             BizType: 1, // uint32 业务类型 - 1:套保 2:套利
             BuyUserID: undefined, // uint64 采购方ID
             SellUserID: undefined,// uint64 客户ID
-            ContractAttachment: new Uint8Array(),// bytes 合同附件
+            ContractAttachment: '',// bytes 合同附件
             DeliveryGoodsID: undefined, // 现货品种ID
             WrStandardID: undefined,  // uint64 现货商品ID
             SpotGoodsBrandID: undefined, // uint64 现货品牌ID