SealStampDrawer.vue 15.1 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478
<template>
    <BasicDrawer
      v-bind="$attrs"
      @register="registerDrawer"
      :title="'印章管理'"
      width="800px"
      :showFooter="false"
    >
      <!-- 新增印章区域 -->
      <div class="mb-4 p-4 border border-gray-200 rounded bg-gray-50">
        <h4 class="text-gray-600 font-medium mb-3">新增印章</h4>
        <div class="flex flex-col gap-3">
          <div class="flex gap-2">
            <a-input v-model:value="stampName" placeholder="请输入印章名称" class="flex-1" />
          </div>
          <div class="flex gap-2">
            <div class="flex-1">
              <input 
                type="file" 
                ref="fileInput"
                accept="image/*"
                style="display: none;"
                @change="handleImageUpload"
              />
              <a-button @click="selectImage" :loading="uploading">选择印章图片</a-button>
              <span v-if="uploadedImageUrl" class="ml-2 text-green-600">✓ 图片已上传</span>
            </div>
            <a-button 
              type="primary" 
              :disabled="isButtonDisabled"
              @click="handleCreate"
              style="margin-left: 8px;"
            >
              新增印章
            </a-button>
          </div>
        </div>
      </div>
      
      <!-- 编辑印章区域 -->
      <div v-if="editingRecord" class="mb-4 p-4 border border-blue-300 rounded bg-blue-50">
        <div class="flex items-center justify-between mb-2">
          <h4 class="text-blue-600 font-medium">编辑印章</h4>
          <a-button size="small" @click="cancelEdit">取消</a-button>
        </div>
        <div class="flex flex-col gap-3">
          <div class="flex gap-2">
            <a-input v-model:value="editForm.settingValue" placeholder="请输入印章名称" class="flex-1" />
          </div>
          <div class="flex gap-2">
            <div class="flex-1">
              <input 
                type="file" 
                ref="editFileInput"
                accept="image/*"
                style="display: none;"
                @change="handleEditImageUpload"
              />
              <a-button @click="selectEditImage" :loading="editUploading">重新选择图片</a-button>
              <span v-if="editForm.relationValue" class="ml-2 text-green-600">✓ 当前有图片</span>
            </div>
            <a-button type="primary" @click="handleEditSubmit">保存</a-button>
          </div>
        </div>
      </div>
      
      <BasicTable @register="registerTable">
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'stampImage'">
            <div class="stamp-image-container">
              <img 
                :src="record.relationValue" 
                alt="印章"
                class="stamp-preview-image"
                @click="previewImage(record.relationValue)"
                @error="handleImageError"
              />
            </div>
          </template>
          <template v-if="column.key === 'action'">
            <TableAction
              :actions="[
                {
                  icon: 'clarity:note-edit-line',
                  tooltip: '编辑印章',
                  onClick: handleEdit.bind(null, record),
                },
              ]"
            />
          </template>
        </template>
      </BasicTable>
      
      <!-- 图片预览模态框 -->
      <a-modal 
        v-model:visible="previewVisible" 
        :footer="null" 
        :width="800"
        :centered="true"
        title="印章预览"
      >
        <div class="text-center">
          <img :src="previewImageUrl" alt="印章预览" style="max-width: 100%; max-height: 600px;" />
        </div>
      </a-modal>
    </BasicDrawer>
  </template>
  
  <script lang="ts">
    import { defineComponent, ref, computed } from 'vue';
    import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
    import { BasicTable, useTable, TableAction } from '/@/components/Table';
    import { useMessage } from '/@/hooks/web/useMessage';
    import { defHttp } from '/@/utils/http/axios';
  
    const columns = [
      {
        title: '印章名称',
        dataIndex: 'settingValue',
        width: 200,
      },
      {
        title: '印章',
        dataIndex: 'stampImage',
        key: 'stampImage',
        width: 120,
      },
      {
        title: '操作',
        key: 'action',
        width: 100,
      },
    ];
  
    // 查询印章列表
    const getStampList = () => {
      return defHttp.post({
        url: '/order/erp/system_setting/query_list',
        data: { settingType: [80] },
      });
    };
  
    // 新增印章
    const addStamp = (data: any) => {
      return defHttp.post({
        url: '/order/erp/system_setting/add',
        data,
      });
    };
  
    // 编辑印章
    const editStamp = (data: any) => {
      return defHttp.post({
        url: '/order/erp/system_setting/edit',
        data,
      });
    };
  
    export default defineComponent({
      name: 'SealStampDrawer',
      components: { BasicDrawer, BasicTable, TableAction },
      emits: ['success', 'register'],
      setup(_, { emit }) {
        const { createMessage } = useMessage();
        const stampName = ref('');
        const uploadedImageUrl = ref('');
        const uploading = ref(false);
        const editUploading = ref(false);
        const fileInput = ref<HTMLInputElement>();
        const editFileInput = ref<HTMLInputElement>();
        
        // 编辑相关
        const editingRecord = ref<any>(null);
        const editForm = ref({
          id: '',
          settingValue: '',
          relationValue: '',
        });
        
        // 图片预览相关
        const previewVisible = ref(false);
        const previewImageUrl = ref('');
        
        const uploadUrl = 'http://47.104.8.35:80/api/localStorage/upload_file_oss?name=';
  
        const [registerTable, { reload }] = useTable({
          api: getStampList,
          columns,
          pagination: false,
          striped: false,
          useSearchForm: false,
          showTableSetting: false,
          bordered: true,
          showIndexColumn: false,
          canResize: false,
          rowKey: 'id',
        });
  
        const [registerDrawer] = useDrawerInner(async () => {
          // 重置新增状态
          stampName.value = '';
          uploadedImageUrl.value = '';
          // 重置编辑状态
          editingRecord.value = null;
          editForm.value = { id: '', settingValue: '', relationValue: '' };
          // 重新加载表格数据
          reload();
        });
  
        // 选择图片
        const selectImage = () => {
          fileInput.value?.click();
        };
  
        const selectEditImage = () => {
          editFileInput.value?.click();
        };
  
        // 上传图片
        const handleImageUpload = async (e: Event) => {
          const target = e.target as HTMLInputElement;
          if (!target.files || target.files.length === 0) return;
          
          const file = target.files[0];
          
          // 验证文件类型
          if (!file.type.startsWith('image/')) {
            createMessage.error('请选择图片文件');
            return;
          }
          
          // 验证文件大小 (5MB)
          if (file.size > 5 * 1024 * 1024) {
            createMessage.error('图片大小不能超过5MB');
            return;
          }
          
          uploading.value = true;
          
          try {
            const formData = new FormData();
            formData.append('file', file);
            
            const response = await fetch(uploadUrl + file.name, {
              method: 'POST',
              body: formData,
            });
            
            if (!response.ok) {
              throw new Error(`上传失败: ${response.statusText}`);
            }
            
            const data = await response.json();
            
            if (data.data && data.data.fileUrl) {
              const fileUrl = data.data.fileUrl;
              uploadedImageUrl.value = fileUrl.startsWith('http') ? fileUrl : `http://47.104.8.35:80${fileUrl}`;
              createMessage.success('图片上传成功');
            } else {
              throw new Error('无法获取图片URL');
            }
          } catch (error) {
            console.error('图片上传失败:', error);
            createMessage.error(`图片上传失败: ${error.message || '未知错误'}`);
          } finally {
            uploading.value = false;
            // 清空input
            if (fileInput.value) {
              fileInput.value.value = '';
            }
          }
        };
  
        // 编辑时的图片上传
        const handleEditImageUpload = async (e: Event) => {
          const target = e.target as HTMLInputElement;
          if (!target.files || target.files.length === 0) return;
          
          const file = target.files[0];
          
          // 验证文件类型
          if (!file.type.startsWith('image/')) {
            createMessage.error('请选择图片文件');
            return;
          }
          
          // 验证文件大小 (5MB)
          if (file.size > 5 * 1024 * 1024) {
            createMessage.error('图片大小不能超过5MB');
            return;
          }
          
          editUploading.value = true;
          
          try {
            const formData = new FormData();
            formData.append('file', file);
            
            const response = await fetch(uploadUrl + file.name, {
              method: 'POST',
              body: formData,
            });
            
            if (!response.ok) {
              throw new Error(`上传失败: ${response.statusText}`);
            }
            
            const data = await response.json();
            
            if (data.data && data.data.fileUrl) {
              const fileUrl = data.data.fileUrl;
              editForm.value.relationValue = fileUrl.startsWith('http') ? fileUrl : `http://47.104.8.35:80${fileUrl}`;
              createMessage.success('图片上传成功');
            } else {
              throw new Error('无法获取图片URL');
            }
          } catch (error) {
            console.error('图片上传失败:', error);
            createMessage.error(`图片上传失败: ${error.message || '未知错误'}`);
          } finally {
            editUploading.value = false;
            // 清空input
            if (editFileInput.value) {
              editFileInput.value.value = '';
            }
          }
        };
  
        // 预览图片
        const previewImage = (imageUrl: string) => {
          previewImageUrl.value = imageUrl;
          previewVisible.value = true;
        };
  
        // 图片加载错误处理
        const handleImageError = (e: Event) => {
          const img = e.target as HTMLImageElement;
          img.src = 'data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNjQiIGhlaWdodD0iNjQiIHZpZXdCb3g9IjAgMCA2NCA2NCIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHJlY3Qgd2lkdGg9IjY0IiBoZWlnaHQ9IjY0IiBmaWxsPSIjRjVGNUY1Ii8+CjxwYXRoIGQ9Ik0yMCAyMEg0NFY0NEgyMFYyMFoiIGZpbGw9IiNEOUQ5RDkiLz4KPHBhdGggZD0iTTI4IDI4TDM2IDM2TDI4IDQ0VjI4WiIgZmlsbD0iI0JGQkZCRiIvPgo8L3N2Zz4K';
        };
  
        function handleEdit(record: any) {
          editingRecord.value = record;
          editForm.value = {
            id: record.id,
            settingValue: record.settingValue,
            relationValue: record.relationValue,
          };
        }
  
        function cancelEdit() {
          editingRecord.value = null;
          editForm.value = { id: '', settingValue: '', relationValue: '' };
        }
  
        async function handleEditSubmit() {
          if (!editForm.value.settingValue) {
            createMessage.warning('印章名称不能为空');
            return;
          }
          
          if (!editForm.value.relationValue) {
            createMessage.warning('请上传印章图片');
            return;
          }
          
          try {
            await editStamp({
              id: editForm.value.id,
              settingCode: "stampedImage",
              settingName: "盖章图片",
              settingValue: editForm.value.settingValue,
              settingType: 80,
              relationCode: "stampedImageDeatil",
              relationName: editForm.value.settingValue,
              relationValue: editForm.value.relationValue,
            });
            
            createMessage.success('编辑成功');
            cancelEdit();
            reload();
            emit('success');
          } catch (error) {
            console.error('编辑印章失败:', error);
            createMessage.error('编辑失败,请重试');
          }
        }
  
        async function handleCreate() {
          if (!stampName.value || stampName.value.trim() === '') {
            createMessage.warning('印章名称不能为空');
            return;
          }
          
          if (!uploadedImageUrl.value || uploadedImageUrl.value.trim() === '') {
            createMessage.warning('请上传印章图片');
            return;
          }
          
          try {
            const requestData = {
              settingCode: "stampedImage",
              settingName: "盖章图片",
              settingValue: stampName.value.trim(),
              settingType: 80,
              relationCode: "stampedImageDeatil",
              relationName: stampName.value.trim(),
              relationValue: uploadedImageUrl.value.trim(),
            };
            
            await addStamp(requestData);
            
            createMessage.success('添加成功');
            stampName.value = '';
            uploadedImageUrl.value = '';
            reload();
            emit('success');
          } catch (error) {
            console.error('新增印章失败:', error);
            createMessage.error('新增失败,请重试');
          }
        }
  
        // 计算属性来检查按钮状态
        const isButtonDisabled = computed(() => {
          return !stampName.value || !uploadedImageUrl.value;
        });
  
        return {
          registerDrawer,
          registerTable,
          stampName,
          uploadedImageUrl,
          uploading,
          editUploading,
          fileInput,
          editFileInput,
          editingRecord,
          editForm,
          previewVisible,
          previewImageUrl,
          selectImage,
          selectEditImage,
          handleImageUpload,
          handleEditImageUpload,
          previewImage,
          handleImageError,
          handleCreate,
          handleEdit,
          handleEditSubmit,
          cancelEdit,
          isButtonDisabled,
        };
      },
    });
  </script>
  
  <style lang="less" scoped>
    .stamp-image-container {
      display: flex;
      justify-content: center;
      align-items: center;
      
      .stamp-preview-image {
        width: 60px;
        height: 60px;
        object-fit: cover;
        border-radius: 4px;
        border: 1px solid #d9d9d9;
        cursor: pointer;
        transition: all 0.3s;
        
        &:hover {
          border-color: #1890ff;
          transform: scale(1.05);
        }
      }
    }
  </style>