TrackEdit.vue 16.2 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 479 480 481 482 483 484
<template>
  <template>
    <BasicDrawer
      @register="register"
      v-bind="$attrs"
      title="收入款单"
      width="30%"
      :isDetail="true"
      @ok="handleSubmit"
      @visible-change="handleShow"
      :showDetailBack="false"
      okText="保存"
      showFooter
      :destroyOnClose="true"
    >
      <div>
        <div style="font-size: 15px">客户扣款金额$</div>
        <a-input 
          v-model:value="input1" 
          placeholder="请输入" 
          :disabled="status === 10 || status === 40" 
          auto-size 
          :status="amountMismatch ? 'error' : ''"
        />
        <div v-if="amountMismatch" style="color: #ff4d4f; font-size: 19px; margin-top: 4px">
          金额不匹配!扣款原因金额为: {{ bindedDeductAmount }}
        </div>
        <div style="margin: 16px 0"></div>
        <div>上传扣款单</div
        ><a-space direction="vertical" style="width: 100%" size="large">
          <a-upload
            v-model:file-list="fileList"
            :beforeUpload="beforeUpload"
            list-type="picture"
            :max-count="1"
            :action="updateDeductUrl"
            @change="handleChange"
            :disabled="status === 10 || status === 40"
          >
            <a-button> 上传扣款单 </a-button>
          </a-upload>
        </a-space>
        
        <div style="margin: 16px 0"></div>
        <div>扣款原因(可选)</div>
        <a-select
          v-model:value="selectedTitle"
          placeholder="请选择或输入扣款原因"
          style="width: 100%"
          :filter-option="false"
          show-search
          :disabled="status === 10 || status === 40"
          @search="handleSearch"
          @change="handleTitleChange"
          :loading="titleLoading"
          :options="formattedOptions"
          :not-found-content="titleLoading ? '加载中...' : (titleOptions.length === 0 ? '未找到匹配项' : null)"
          allow-clear
          @clear="handleClear"
          :auto-focus="true"
          :default-open="false"
          :drop-down-style="{ maxHeight: '400px', overflow: 'auto' }"
        >
        </a-select>
        <!-- 调试信息 -->
        <div v-if="debug" style="margin-top: 8px; color: #999; font-size: 12px;">
          选项数量: {{ titleOptions.length }}
          <div v-if="titleOptions.length > 0">
            第一个选项: {{ titleOptions[0].title }} (ID: {{ titleOptions[0].id }})
          </div>
          <div>
            绑定金额: {{ bindedDeductAmount }}
            当前输入: {{ input1 }}
            是否不匹配: {{ amountMismatch }}
          </div>
        </div>
      </div>
      <!-- <template #titleToolbar> <a-button type="primary"> 申请编辑权限 </a-button></template> -->
      <template #appendFooter>
        <!-- <a-button type="primary" @click="onGoCheckDetail"> 申请权限</a-button> -->
      </template>
    </BasicDrawer>
  </template>
</template>
<script lang="ts" setup>
  import { BasicDrawer, useDrawerInner } from '@/components/Drawer';
  import { ref, onMounted, computed, watch } from 'vue';
  import type { UploadProps } from 'ant-design-vue';
  import { updateDeduct } from '@/api/project/invoice';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { getAllQuests, queryQuestTitle } from '@/api/project/quest';
  import { handleViewRichText } from '../financeList/finance.data';

  const emit = defineEmits(['success']);
  const fileList = ref<UploadProps['fileList']>([]);

  const input1 = ref(0);
  const deductUrl = ref();
  const id = ref();
  const invoiceNo = ref();
  const uploadUrl = ref('http://47.104.8.35:80/api/localStorage/upload_file_oss?name=');
  // const uploadUrl = ref('');
  const updateDeductUrl = ref('http://47.104.8.35:80/api/localStorage/upload_file_oss?name=');
  // const updateDeductUrl = ref('');
  const deductUrlOld = ref();
  const { createMessage } = useMessage();
  const { error } = createMessage;
  const status = ref();
  
  // 扣款原因相关状态
  const titleOptions = ref<any[]>([]);
  const selectedTitle = ref<number | undefined>(undefined);
  const selectedTitleText = ref('');
  const titleLoading = ref(false);
  const debug = ref(false); // 关闭调试模式
  
  // 添加绑定的deductAmount变量
  const bindedDeductAmount = ref<number | undefined>(undefined);
  // 添加金额不一致的提示状态
  const amountMismatch = ref(false);
   // 添加是否为模板的标志
   const isSelectedTemplate = ref(false);
  
  // 转换为antd需要的options格式
  const formattedOptions = computed(() => {
    return titleOptions.value.map(item => ({
      value: item.id,
      label: item.title,
    }));
  });

  
  // 添加完全重置状态的函数
  function resetAllStates() {
    // 重置扣款金额相关状态
    bindedDeductAmount.value = undefined;
    amountMismatch.value = false;
    isSelectedTemplate.value = false;
    
    // 重置选择状态
    selectedTitle.value = undefined;
    selectedTitleText.value = '';
    
    // 重置选项
    titleOptions.value = [];
    
    // 重置文件上传
    fileList.value = [];
  }

  const [register, { closeDrawer }] = useDrawerInner((data) => {
      // 每次打开抽屉时先重置所有状态
      resetAllStates();
    
    // 然后初始化新的状态
    status.value = data.data.invoiceStatus;
    id.value = data.data.invoiceId;
    invoiceNo.value = data.data.invoiceNo;
    input1.value = data.data.invoiceDeductAmount;
    deductUrl.value = data.data.invoiceDeductUrl;
    deductUrlOld.value = data.data.invoiceDeductUrl;
    
    // 优先使用questId,如果没有则尝试使用invoiceRichTextId
    selectedTitle.value = data.data.questId || data.data.invoiceRichTextId;
    
    // 加载扣款原因选项
    loadQuestOptions();
  });

  // 处理API返回的数据,统一格式
  function normalizeData(data: any[]): { id: number; title: string; deductAmount?: number; isTemplate?: boolean  }[] {
    
    if (!data || !Array.isArray(data) || data.length === 0) {
      return [];
    }
    
    const result = data.map(item => {
      // 处理可能的不同字段名称
      const id = item.id !== undefined ? item.id : 
                (item.questId !== undefined ? item.questId : null);
      
      const title = item.title !== undefined ? item.title : 
                   (item.questTitle !== undefined ? item.questTitle : 
                   (item.name !== undefined ? item.name : '未知标题'));
      
      // 添加新的deductAmount字段处理
      const deductAmount = item.deductAmount !== undefined ? Number(item.deductAmount) : undefined;
      // 正确处理isTemplate字段,确保它是布尔值
      const isTemplate = item.isTemplate !== undefined ? Boolean(item.isTemplate) : undefined;
      return { id, title, deductAmount, isTemplate  };
    }).filter(item => item.id !== null); // 过滤掉无效项
    return result;
  }

  // 加载所有扣款原因选项
  async function loadQuestOptions() {
    titleLoading.value = true;
    try {
      // 如果已有选中ID但没有选项,先尝试直接获取该ID的详情
      if (selectedTitle.value && (!titleOptions.value || titleOptions.value.length === 0)) {
        try {
          // 使用finance.data.ts中的handleViewRichText方法获取富文本详情
          const richTextDetail = await handleViewRichText(String(selectedTitle.value));
          if (richTextDetail) {
            // 设置选项
            titleOptions.value = [{ 
              id: richTextDetail.id, 
              title: richTextDetail.title || '扣款原因详情',
              deductAmount: richTextDetail.deductAmount, // 确保获取deductAmount
              isTemplate: richTextDetail.isTemplate === true // 确保是布尔值
            }];
            selectedTitleText.value = richTextDetail.title || '扣款原因详情';
            // 保存是否为模板的标志
            isSelectedTemplate.value = richTextDetail.isTemplate === true;
            
            // 绑定deductAmount如果存在
            if (richTextDetail.deductAmount !== undefined) {
              bindedDeductAmount.value = Number(richTextDetail.deductAmount);
              checkAmountMatch();
            }
            titleLoading.value = false;
            return;
          }
        } catch (err) {
          console.error('获取单个扣款原因详情失败:', err);
        }
      }

      const res = await getAllQuests();
      
      // 处理不同格式的返回数据
      let tempData: any[] = [];
      
      if (Array.isArray(res)) {
        tempData = res;
      } else if (res && Array.isArray(res.records)) {
        tempData = res.records;
      } else if (res && Array.isArray(res.items)) {
        tempData = res.items;
      } else if (res && typeof res === 'object') {
        tempData = [res];
      }
      
      // 标准化数据格式
      titleOptions.value = normalizeData(tempData);
      
      // 如果有已选择的ID,查找对应的title用于显示
      if (selectedTitle.value && titleOptions.value.length > 0) {
        const found = titleOptions.value.find(item => item.id === selectedTitle.value);
        if (found) {
          selectedTitleText.value = found.title;
           // 保存是否为模板的标志
           isSelectedTemplate.value = !!found.isTemplate;
          // 绑定deductAmount如果存在
          if (found.deductAmount !== undefined) {
            bindedDeductAmount.value = Number(found.deductAmount);
            checkAmountMatch();
          }
        } else {
          // 如果在选项中找不到对应ID,可以尝试单独请求这个ID的详情
          try {
            const richTextDetail = await handleViewRichText(String(selectedTitle.value));
            if (richTextDetail) {
              // 添加到选项中
              titleOptions.value.push({ 
                id: richTextDetail.id, 
                title: richTextDetail.title || '扣款原因详情',
                deductAmount: richTextDetail.deductAmount, // 确保获取deductAmount
                isTemplate: richTextDetail.isTemplate === true // 确保是布尔值
              });
              selectedTitleText.value = richTextDetail.title || '扣款原因详情';
               // 保存是否为模板的标志
               isSelectedTemplate.value = richTextDetail.isTemplate === true;
              
              // 绑定deductAmount如果存在
              if (richTextDetail.deductAmount !== undefined) {
                bindedDeductAmount.value = Number(richTextDetail.deductAmount);
                checkAmountMatch();
              }
            }
          } catch (err) {
            console.error('获取缺失的扣款原因详情失败:', err);
          }
        }
      }
      
    } catch (err) {
      error('获取扣款原因列表失败');
      console.error('获取扣款原因列表失败:', err);
      titleOptions.value = [];
    } finally {
      titleLoading.value = false;
    }
  }
  
  // 搜索扣款原因
  async function handleSearch(value: string) {
    if (!value || value.trim() === '') {
      await loadQuestOptions();
      return;
    }
    
    titleLoading.value = true;
    try {
      const res = await queryQuestTitle(value);

      // 确保res不为null或undefined
      if (!res) {
        titleOptions.value = [];
        return;
      }
      
      // 处理不同格式的返回数据
      let tempData: any[] = [];
      
      if (Array.isArray(res)) {
        tempData = res;
      } else if (res && Array.isArray(res.records)) {
        tempData = res.records;
      } else if (res && Array.isArray(res.items)) {
        tempData = res.items;
      } else if (res && typeof res === 'object') {
        tempData = [res];
      }
      
      // 标准化数据格式
      titleOptions.value = normalizeData(tempData);
    } catch (err) {
      error('搜索扣款原因失败');
      console.error('搜索扣款原因失败:', err);
      titleOptions.value = [];
    } finally {
      titleLoading.value = false;
    }
  }
  
  // 选择扣款原因时触发
  function handleTitleChange(value: number, option: any) {
    // 检查是否为空值(用户点击了清除按钮)
    if (value === undefined || value === null) {
      handleClear();
      return;
    }
    
    selectedTitle.value = value;
    
    // 当使用options属性时,option为选中的选项对象
    if (option && typeof option === 'object') {
      if (option.label) {
        // 新版本Ant Design Vue返回的选项格式
        selectedTitleText.value = option.label;
      } else if (option.children) {
        // 旧版本Ant Design Vue返回的选项格式
        selectedTitleText.value = option.children;
      }
    }
    
    // 直接从选项列表中查找
    const found = titleOptions.value.find(item => item.id === value);
    if (found) {
      selectedTitleText.value = found.title;
       // 保存是否为模板的标志 - 确保它是布尔值
       isSelectedTemplate.value = found.isTemplate === true;
      
      // 绑定deductAmount
      bindedDeductAmount.value = found.deductAmount;
      // 检查金额是否一致
      checkAmountMatch();
    }
  }

  // 清除选择
  function handleClear() {
    selectedTitle.value = undefined;
    selectedTitleText.value = '';
    // 清除绑定的deductAmount
    bindedDeductAmount.value = undefined;
    // 重置金额不匹配状态
    amountMismatch.value = false;
     // 重置是否为模板的标志
     isSelectedTemplate.value = false;
    // 重新加载所有选项
    loadQuestOptions();
  }

  // 检查金额是否匹配
  function checkAmountMatch() {
      // 如果是模板类型,不进行金额校验
      if (isSelectedTemplate.value === true) {
      amountMismatch.value = false;
      return;
    }
    
    if (bindedDeductAmount.value !== undefined && input1.value !== undefined) {
      try {
        // 确保转换为数字进行比较,处理可能的字符串转换问题
        const boundAmount = typeof bindedDeductAmount.value === 'string' 
          ? parseFloat(bindedDeductAmount.value) 
          : Number(bindedDeductAmount.value);
          
        const inputAmount = typeof input1.value === 'string' 
          ? parseFloat(input1.value) 
          : Number(input1.value);
        
        // 比较金额是否一致,使用差值小于极小值来处理浮点数误差
        amountMismatch.value = Math.abs(boundAmount - inputAmount) > 0.001;
      } catch (err) {
        console.error('金额比较出错:', err);
      }
    }
  }

  function handleChange(info) {
    if (info.file.status == 'done') {
      updateDeductUrl.value = info.file.response.data.fileUrl;
      deductUrl.value = updateDeductUrl.value;
    }
    if (info.fileList.length == 0) {
      info.file = null;
      deductUrl.value = '';
    }
  }
  function beforeUpload(info) {
    updateDeductUrl.value = uploadUrl.value + info.name;
  }
  function handleShow(visible) {
    if (visible) {
      // 抽屉打开时加载扣款原因选项
      // loadQuestOptions();
    } else {
      // 抽屉关闭时重置状态,确保下次打开时不会保留旧状态
      resetAllStates();
    }
  }

  // 页面加载时获取扣款原因列表
  onMounted(() => {
    // loadQuestOptions();
  });

  // 监听客户扣款金额变化
  function handleInputChange() {
    // 检查金额是否匹配
    checkAmountMatch();
  }

  // 监听input1的变化
  watch(input1, () => {
    handleInputChange();
  }, { immediate: true }); // 确保首次加载也会触发

  //完成编辑
  async function handleSubmit() {
    if (!input1.value) {
      error('客户扣款金额不能为空');
      return;
    }
    
     // 添加金额不一致的检查,但模板类型跳过检查
    if (amountMismatch.value  && !isSelectedTemplate.value) {
      error(`客户扣款金额与选择的扣款原因金额不一致!扣款原因金额为: ${bindedDeductAmount.value}`);
      return;
    }
    
    try {
      await updateDeduct({
        id: id.value,
        invoiceNo: invoiceNo.value,
        deductAmount: input1.value,
        deductUrl: deductUrl.value,
        questId: selectedTitle.value, // 传递选中的扣款原因ID
      });
          
      // 成功提交后重置状态
      resetAllStates();
      
      emit('success');
      closeDrawer();
    } catch (err) {
      error('保存失败');
      console.error('保存失败:', err);
    }
  }
</script>