createOrderCarQuotationSimple.js 35.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 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170
// packageEquity/pages/carEquity/serviceInfo/serviceInfo.js quotationGoods
import {
  // quotationPicture,
  quotationAdd,
  updateQuotation,
  quotationUpgrade,
  getQuotationInfoById,
  quotationGoodsList,
  quotationRecording,
  errorOrderById,
  staffDailyReportMerchantValid,
  updateOrderStatus,
  orderSettingList,
  checkRecord
} from "../../../api";
import { quotedImgUrl } from "~/config";
import dataForm from '../components/constant/stepData'
import NP from "number-precision";
Page({
  /**
   * 页面的初始数据
   */
  data: {
    showTips: true,
    showPopup: false,
    owner: {
      owner: "",
      phone: "",
      certificateNo: "",
      carVin: "",
      seat: "5",
      price: "",
      confirmStatus: false,
      saveStatus: false,
      ownerGender: "男",
      city: "",
      ageRange: "",
      hobby: "",
      companion: "",
      carColor: "",
      carBrandId: "",
      carBrand: "",
      carChildsBrandId: "",
      carChildsBrandName: "",
      carSeriesId: "",
      carSeriesName: "",
      salesType: "售前",
    },
    mode: 1,
    quotationGoodsList: [], //权益商品列表
    // owner: {
    //   owner: 'test2',
    //   phone: 15816539334,
    //   certificateNo: '230182198012251659',
    //   carVin: '12345678912345678',
    //   seat: 5,
    //   price: 230000
    // },
    orderInfo: {
      mode: 1,
      payType: 1,
      insurancePrice: "",
      vdQuotationGoodsList: [],
      // 0-商业,1-交强,2-车船,3-增值车损,4-other 对应下面字段名字
      // owner
      // business: {
      //   type: 0,
      //   three: '100万',
      //   driver: '1万',
      //   passenger: '1万'
      // },
      // mutualStrength: {
      //   type: 1,
      //   compensation: '20万'
      // },
      // vehiclesAndVessels: {
      //   type: 2,
      //   compensation: new Date().getFullYear() + '年'
      // },
      // valueAddedVehicleLoss: {
      //   type: 3
      // },
      // otherInsuranceList: []
    },
    // 页面存放表单对象的对象名
    dataAttrName: "owner",
    // step: 'first',
    step: "second", // 非融合不要第一步
    needChangeList: [
      "price",
      "base",
      "threePremium",
      "carInsidePremium",
      "passengerPremium",
      "payPrice",
      "insurancePrice",
      "quotedPriceUpdate",
      "minEquityPrice",
    ],
    firstEnter: true,
    // vin二次确认弹窗
    showVinDialog: false,
    secFormData: {},
    tempVin: '',
    showZyPopup: false // 上传延保协议弹窗
  },
  closeTips() {
    this.setData({
      showTips: false,
    });
  },
  secondChange() {
    let { showVinDialog } = this.data
    this.setData({
      showVinDialog: !showVinDialog
    })
  },
  handleSecClose() {
    let { tempVin } = this.data
    this.setData({
      secFormData: {
        carVin: ''
      },
    })
    if (tempVin) {
      this.setData({
        'owner.carVin': tempVin,
        tempVin: ''
      })
    }
    this.secondChange()
  },
  handleSecConfirm(e) {
    let { detail } = e
    this.setData({
      ['owner.carVin']: detail.carVin,
      tempVin: detail.carVin
    })
  },
  reWrite(type, data) {
    console.log(type, data);
    let { owner } = this.data;
    if (type == "vehicleCertificate") {
      this.setData({
        tempVin: this.data.owner.carVin
      })
      let {
        vinNo: carVin,
        seatingCapacity: seat,
        engineNo: engineNumber,
        carColor,
      } = data;
      owner = Object.assign(owner, {
        carVin,
        seat,
        engineNumber,
        carColor,
      });
      owner.carVin = ''
      if (carVin) {
        this.setData({
          secFormData: {
            carVin: carVin
          }
        })
        this.secondChange(carVin)
      }
    }
    if (type == "idCard") {
      let {
        name,
        sex: ownerGender,
        address: addr,
        cardNo: certificateNo,
      } = data;
      owner = Object.assign(owner, {
        owner: name,
        ownerGender,
        addr,
        certificateNo,
      });
      console.log(owner, "owner");
    }
    this.setData({
      owner,
    });
  },
  handleFirstConfirm(e) {
    // let { formData } = e.detail
    this.setData({
      // ['orderInfo.owner']: formData,
      step: "second",
    });
  },
  createWithPay(id) {
    return new Promise((resolve, reject) => {
      let para = {
        id,
        customerNameUrl: "",
        orderStatus: 2,
      };
      quotationUpgrade(para).then((res) => {
        console.log(res, "res");
        resolve(res);
      });
    });
  },
  setQuotationRecording() {
    // 获取保险信息
    let { outTradeNo } = this.data;
    let orderInfo = this.getInsurance();
    let owner = this.getOwnerInfo();
    owner.salesType = owner.salesType == "售后" ? 1 : 0;
    orderInfo.owner = owner;
    orderInfo.check = true;
    orderInfo.outTradeNo = outTradeNo;
    wx.showLoading("提交中...");
    quotationRecording(orderInfo)
      .then((result) => {
        wx.hideLoading();
        console.log(result);
        let { code, data, message } = result;
        if (code == 0 && data) {
          this.setData({
            confirmStatus: false,
          });
          wx.showToast({
            title: "补录订单成功",
            icon: "success",
          });
          setTimeout(() => {
            wx.$router.reLaunch("packageEquity.equityPage", {
              tabIndex: 1,
            });
          }, 1000);
        } else {
          this.setData({
            confirmStatus: false,
          });
          wx.$util.showToast(message);
        }
      })
      .catch((err) => {
        console.log(err);
      });
  },
  staffDailyReportMerchantValid(userInfo) {
    // let { userInfo } = this.data
    return new Promise((resolve, reject) => {
      staffDailyReportMerchantValid({
        merchantId: userInfo.shopMerchantId,
        yqMerchantId: userInfo.merchantId,
        staffUuid: userInfo.uuid,
        sceneType: 0,
      })
        .then((res) => {
          // console.log(res, 'staffDailyReportMerchantValid')
          // 需要填写日报
          if (res.data) {
            // 获取当前日期
            let currentDate = new Date();

            // 获取上一天的日期
            let previousDate = new Date(currentDate);
            previousDate.setDate(currentDate.getDate() - 1);
            // toISOString 方法会丢失时区 导致与北京时间差八小时
            let hour = previousDate.getHours() + 8
            previousDate.setHours(hour)
            // 格式化日期为"yyyy-mm-dd"
            let formattedDate = previousDate.toISOString().split("T")[0];
            if (wx.__HAS_NOREPORT_MODAL || wx.__HAS_NOTLOGIN_MODAL)
              return false;
            wx.__HAS_NOREPORT_MODAL = true;
            wx.showModal({
              title: "日报提醒",
              content: "您有未填写的日报,请点击前往。",
              showCancel: false,
              // cancelText: '取消', // '取消
              cancelColor: "#292D33",
              confirmText: "前往填写",
              confirmColor: "#347BFF",
              success(res) {
                if (res.confirm) {
                  wx.$router.go("tabWorkOrder.staffDaily", {
                    // reportDate: hasNeedReport.date
                    reportDate: formattedDate,
                  });
                }
              },
              complete: () => {
                // 这个延迟的目的是为了避免短时间内重复弹出
                // 你要是没有这个需要也可以去掉,直接把标志位改成 false 就行
                setTimeout(() => {
                  wx.__HAS_NOREPORT_MODAL = false;
                }, 2000);
              },
            });
            // return false
            resolve(res.data);
          } else {
            resolve(res.data);
          }
        })
        .catch((err) => {
          console.log(err);
        });
    });
  },

  async handleSecondConfirm(e) {
    // debugger
    let { orderInfo, outTradeNo, confirmStatus, userInfo, carBrandList } = this.data;
    let staffCheck = await this.staffDailyReportMerchantValid(userInfo);
    if (staffCheck) return false;;

    // 先校验
    let status = this.selectComponent(`#FirstStep`).handleConfirm();
    if (!status) return false;

    if (!orderInfo.vdQuotationGoodsList.length)
      return wx.$util.showToast("请选择增值车损险商品");
    // 非标记错误,门店收款
    if (!orderInfo.pay2Time && (orderInfo.payType == 2 || orderInfo.payType == 5) && !orderInfo.resetOrder)
      return wx.$util.showToast(orderInfo.payType == 2 ? "请选择门店收款时间" : "请选择嘀加收款时间");
    // 修改权益报价逻辑
    if (confirmStatus) return false;
    this.setData({
      confirmStatus: true,
    });

    // 是订单补录直接走另外的补录逻辑
    console.log(outTradeNo, "是订单补录直接走另外的补录逻辑");
    // if (!orderInfo.pay2Time&&orderInfo.payType==1&&!orderInfo.resetOrder&&outTradeNo) return wx.$util.showToast('请选择门店收款时间')
    if (outTradeNo && !orderInfo.resetOrder)
      return this.setQuotationRecording();
    // debugger
    // 如果是门店收款 并且付款凭证没有填
    orderInfo.paymentDocList = orderInfo.paymentDocList || [];
    if (
      (orderInfo.payType == 2 || orderInfo.payType == 5) &&
      !(orderInfo.transactionNo && orderInfo.paymentDocList.length)
    )
      return this.setData({
        showPopup: true,
        confirmStatus: false,
      });
    if (orderInfo.paymentDocList.length) {
      let _tempMap = orderInfo.paymentDocList.map(el => {
        let obj = {
          paymentDocUrl: '',
          type: 1
        }
        if (!el.type) {
          // 上传凭证弹窗返回的是[string,string]
          obj.paymentDocUrl = el
        } else {
          // 详情返回的是[{}]
          obj.paymentDocUrl = el.paymentDocUrl
        }

        return obj
      })

      orderInfo.paymentDocList = _tempMap
    }

    // -------
    wx.showLoading("报价中...");
    let result = await this.handleSecondConfirmCheck(true, e);
    let { code, data: id, message } = result;

    console.log(result);
    // 校验生成告知书是否成功
    if (id) {
      // 门店付款就直接返回列表
      if (orderInfo.payType == 2 || orderInfo.payType == 5)
        return wx.$router.reLaunch("packageEquity.equityPage", {
          tabIndex: 1,
        });
      let status = await this.createWithPay(id);
      wx.hideLoading();
      let that = this;
      setTimeout(() => {
        that.setData({
          confirmStatus: false,
        });
      });
      console.log("id", id);
      // { orderId:data.orderId, id }
      // return
      status.code == 0
        ? this.navigatorNext({
          id,
          orderId: status.data.orderId,
        })
        : wx.$util.showToast(status.message || "报价失败");
    } else {
      console.log(message);
      wx.hideLoading();
      // 将延保协议弹窗关闭 清空延保协议上传内容,支付凭证内容清空
      let owner = this.getOwnerInfo();
      if (orderInfo.payType == 2 && carBrandList?.includes(owner?.carChildsBrandId)) {
        this.setData({
          showZyPopup: false,
          ['orderInfo.zyPayUrl']: '',
          ['orderInfo.transactionNo']: '',
          ['orderInfo.paymentDocList']: []
        })
      }
      this.setData({
        confirmStatus: false
      });
      wx.$util.showToast(message || "报价失败");
    }
  },
  getInsurance() {
    let { orderInfo } = this.data;
    orderInfo = wx.$util.deepClone(orderInfo);
    let { default4SStoreInfo } = wx.$util.getUserInfo();
    orderInfo.merchantId4s = default4SStoreInfo?.merchantId;
    orderInfo.merchantName4s = default4SStoreInfo?.merchantName;

    orderInfo.insurancePrice = this.multipliedByHundred(
      orderInfo.insurancePrice
    );
    orderInfo.quotedPriceUpdate = this.multipliedByHundred(
      orderInfo.quotedPriceUpdate
    );
    // console.log(orderInfo.quotedPriceUpdate );
    // debugger
    orderInfo.minEquityPrice = this.multipliedByHundred(
      orderInfo.minEquityPrice
    );
    // var reg = getRegExp(';~;', 'g')
    orderInfo.vdQuotationGoodsList = orderInfo.vdQuotationGoodsList.reduce(
      (pre, item) => {
        if (item.goods) {
          item = item.goods;
          const obj = {
            goodsId: item.merchantGoodsId,
            goodsName: item.goodsName,
            goodsNameAlias: item.goodsAlias || item.goodsNameAlias,
            specificationsName: item.specificationNameSequence,
            specificationsValue: item.specificationData ? item.specificationData.replace(/;~;/g, '/') : '',
            goodsPrice: this.multipliedByHundred(item.price),
          };
          pre.push(obj);
        }

        if (item.packageGoods) {
          item = item.packageGoods;
          item.goodsList.map((ele) => {
            // console.log(ele, '2222');
            let obj = {
              packageId: item.packageCode,
              packageName: item.packageName,
              packageNameAlias: item.packageAlias || item.packageNameAlias,
              goodsId: ele.merchantGoodsId || ele.upgradeGoodsId,
              goodsName: ele.upgradeGoodsName || ele.goodsName,
              goodsNameAlias: ele.goodsAlias || ele.goodsNameAlias,
              specificationsName: ele.specificationNameSequence,
              specificationsValue: ele.specificationData ? ele.specificationData.replace(/;~;/g, '/') : '',
              // specificationsValue: item.specificationData ? item.specificationData.replace(reg, ' ') : '',
              goodsPrice: this.multipliedByHundred(ele.price),
            };
            pre.push(obj);
          });
        }
        return pre;
      },
      []
    );
    return orderInfo;
  },
  getOwnerInfo() {
    let { owner } = this.data;

    owner = wx.$util.deepClone(owner);
    owner.price =
      parseFloat(owner?.price).toString() != "NaN"
        ? this.multipliedByHundred(owner?.price)
        : "";
    // orderInfo.owner = owner
    if (owner) {
      delete owner?.buyCarTime;
    }
    return owner;
  },
  handleSecondConfirmCheck(check, detail) {
    let { carBrandList } = this.data
    // 获取保险信息
    let orderInfo = this.getInsurance();
    let owner = this.getOwnerInfo();
    owner.salesType = owner.salesType == "售后" ? 1 : 0;
    orderInfo.owner = owner;
    orderInfo.check = check;
    orderInfo.paymentDocList = orderInfo.paymentDocList || [];
    console.log("orderInfo", orderInfo);
    // 门店收款且是智界/享界车型 弹出上传延保协议
    try {
      return new Promise(async (resolve, reject) => {
        // 当延保协议弹窗点击稍后补录会传值detail:cancel, 提交表单时不会重复弹出延保协议弹出 标记错误订单的补录时无需上传延保协议
        if (check && orderInfo.payType == 2 && carBrandList?.includes(orderInfo?.owner?.carChildsBrandId) && detail != 'cancel' && !orderInfo?.zyPayUrl && !orderInfo.resetOrder) {
          // 添加流水号校验
          wx.hideLoading()
          let result = await checkRecord({ transactionNo: orderInfo.transactionNo })
          let { code, message } = result
          if (code == 0) {
            this.setData({
              showPopup: false
            })
            reject()
            return this.setData({ showZyPopup: true })
          } else {
            reject()
            this.setData({
              confirmStatus: false
            })
            return wx.$util.showToast(message)
          }
        }
        // let { orderInfo } = this.data
        console.log("调接口---");
        // 标记错误--补录订单
        if (orderInfo.resetOrder && orderInfo.id) {
          orderInfo.oldQuotationId = orderInfo.id;
          orderInfo.transactionNo =
            orderInfo.transactionNo || orderInfo.outTradeNo;
          orderInfo.transactionNo = orderInfo.transactionNo + ",";
          let result = await errorOrderById(orderInfo);
          return resolve(result);
        }
        // 编辑后重新提交
        if (orderInfo.id) {
          let result = await updateQuotation(orderInfo);
          console.log("result", result);
          // let { code, data } = result
          return resolve(result);
        } else {
          // 新增提交
          let result = await quotationAdd(orderInfo);
          let { code, data } = result;
          // console.log('result', result)
          return resolve(result);
        }
      });
    } catch (error) {
      console.log(error);
    }
  },
  navigatorNext(obj) {
    wx.$router.redirectTo("CarQuotationPay", obj);
  },
  getOrderInfo() {
    wx.$util.showLoading("加载中...");
    let { id, orderInfo, quotationGoodsList } = this.data;

    // 先写死调试
    getQuotationInfoById({
      id,
    })
      .then((result) => {
        console.log("result", result);
        let { code, data: tableInfo } = result;
        tableInfo.owner.price = this.divideByHundred(tableInfo.owner.price);
        // tableInfo.quotedPrice = this.divideByHundred(tableInfo.quotedPrice)
        tableInfo.insurancePrice = this.divideByHundred(
          tableInfo.insurancePrice
        );
        tableInfo.quotedPriceUpdate = this.divideByHundred(
          tableInfo.quotedPriceUpdate
        );
        tableInfo.vdQuotationGoodsList = tableInfo.vdQuotationGoodsList.map(
          (item) => {
            item.price = this.divideByHundred(item.goodsPrice);
            return item;
          }
        );
        wx.hideLoading();
        if (code == 0) {
          tableInfo.vdQuotationGoodsList =
            tableInfo.vdQuotationGoodsList.reduce((pre, item) => {
              // 是普通商品
              if (!item.packageName) {
                let obj = {
                  ...item,
                  upgradeGoodsId: item.goodsId,
                  merchantGoodsId: item.goodsId,
                  price: this.divideByHundred(item.goodsPrice),
                  minSellPrice: quotationGoodsList?.find(
                    (val) => val?.goods?.merchantGoodsId == item.goodsId
                  )?.goods?.minSellPrice, // 按商品数据对比补充详情商品最低价
                  validMinSellPrice: quotationGoodsList?.find(
                    (val) => val?.goods?.merchantGoodsId == item.goodsId
                  )?.goods?.validMinSellPrice, // 按商品数据对比补充详情商品校验最低价字段
                };
                pre.push({ goods: obj, packageGoods: null });
              }
              if (item.packageName) {
                let obj = {
                  ...item,
                  merchantGoodsId: item.goodsId,
                  upgradeGoodsId: item.goodsId,
                  price: this.divideByHundred(item.goodsPrice),
                  minSellPrice: quotationGoodsList
                    ?.find(
                      (val) =>
                        val.packageGoods?.goodsList?.length &&
                        val.packageGoods?.packageCode == item?.packageId
                    )
                    ?.packageGoods?.goodsList?.find(
                      (subV) => subV.merchantGoodsId == item.goodsId
                    )?.minSellPrice, // 按商品数据对比补充详情商品最低价
                  validMinSellPrice: quotationGoodsList
                    ?.find(
                      (val) =>
                        val.packageGoods?.goodsList?.length &&
                        val.packageGoods?.packageCode == item?.packageId
                    )
                    ?.packageGoods?.goodsList?.find(
                      (subV) => subV.merchantGoodsId == item.goodsId
                    )?.validMinSellPrice, // 按商品数据对比补充详情商品校验最低价字段
                };
                let index = pre.findIndex((ele) => {
                  if (ele.packageGoods) {
                    return ele.packageGoods.packageId == item.packageId;
                  }
                });
                // console.log(index, 'index');
                if (index != -1) {
                  pre[index].packageGoods.goodsList.push(obj);
                  pre[index].price = NP.plus(pre[index].price, obj.price);
                } else {
                  pre.push({
                    goods: null,
                    price: item.price,
                    packageGoods: {
                      ...item,
                      packageCode: item.packageId,
                      goodsList: [{ ...obj }],
                    },
                  });
                }
              }
              // item.price =
              return pre;
            }, []);
          //  标识为补录工单
          if (this.resetOrder) {
            orderInfo.resetOrder = this.resetOrder;
            tableInfo.payType = 2;
          }
          tableInfo.owner.salesType =
            tableInfo.owner.salesType == 1 ? "售后" : "售前";
          tableInfo.owner.ownerGender =
            tableInfo.owner.ownerGender || '男'
          this.setData({
            orderInfo: Object.assign(orderInfo, tableInfo, {
              insureList: [],
            }),
            owner: tableInfo.owner,
            // ...insuranceTypeObj
          });
          // this.getQuotationInfo()
          // 判断有没有勾选商品,有的话调用一下
          orderInfo.vdQuotationGoodsList.length && this.totalFee();
        }
      })
      .catch((err) => { });
  },
  totalFee() {
    let { orderInfo } = this.data;
    console.log(orderInfo, "orderInfo");

    let total = 0;
    // orderInfo.vdQuotationGoodsList.map(i => (total += parseFloat(i?.count || 1) * parseFloat(i.price)))
    orderInfo.vdQuotationGoodsList.map((i) => {
      if (i.goods) {
        // total += parseFloat(i.goods.count || 1) * parseFloat(i.goods.price)
        total = NP.plus(
          total,
          NP.times(parseFloat(i.goods.count || 1), parseFloat(i.goods.price))
        );
      }
      if (i.packageGoods) {
        console.log(i.packageGoods, "i.packageGoods");
        i.packageGoods.goodsList.map((ele) => {
          total = NP.plus(
            total,
            NP.times(parseFloat(ele.count || 1), parseFloat(ele.price))
          );
          // total += parseFloat(ele.count || 1) * parseFloat(ele.price)
        });
      }
    });
    this.setData({
      ["orderInfo.total"]: wx.$util.decimal(total, 2),
    });
  },
  // 缩小100
  divideByHundredObj(obj) {
    let { needChangeList } = this.data;
    for (const key in obj) {
      if (needChangeList.includes(key)) {
        obj[key] = this.divideByHundred(obj[key]);
      }
    }
    return obj;
  },
  // 放大100
  multipliedByHundredObj(obj) {
    console.log(obj, "obj");
    let { needChangeList } = this.data;
    for (const key in obj) {
      if (needChangeList.includes(key)) {
        obj[key] = this.multipliedByHundred(obj[key]);
      }
    }
    return obj;
  },
  updateOrderStatus() {
    return new Promise((resolve, reject) => {
      let { orderInfo } = this.data;
      updateOrderStatus({
        id: orderInfo.id,
        orderStatus: 0,
      }).then((res) => {
        let { code, message } = res;
        if (code == 0) {
          resolve(true);
          // wx.$util.showToast('提交成功')
          // this.onLoad()
        } else {
          wx.$util.showToast(message);
        }
      });
    });
  },
  // 获取智界、享界车系id
  async getCarBrandList() {
    const {
      carBrandList
    } = await wx.$util.getMockData()
    this.setData({
      carBrandList
    })
  },

  // 不需要检验 存草稿
  async handleEditSave() {
    let { owner, orderInfo, saveStatus } = this.data;
    // 补单点放弃
    if (orderInfo.outTradeNo || orderInfo.resetOrder) {
      return wx.$router.reLaunch("packageEquity.equityPage", {
        tabIndex: 1,
      });
    }
    if (saveStatus) return false;
    wx.showLoading("保存中...");
    this.setData({
      saveStatus: true,
    });
    orderInfo.check = false;
    orderInfo.owner = owner;
    this.setData({
      orderInfo,
    });

    // if (orderInfo.orderStatus == -1) {
    //   await this.updateOrderStatus()
    // }

    let res = await this.handleSecondConfirmCheck(false);
    this.setData({
      saveStatus: false,
    });
    console.log("id", res);
    let { code, data, message } = res;
    if (code == 0) {
      wx.$router.reLaunch("packageEquity.equityPage", {
        tabIndex: 1,
      });
    } else {
      return wx.$util.showToast(res.message || "保存错误");
    }
  },
  resetGoods() {
    this.setData({
      ["orderInfo.vdQuotationGoodsList"]: [],
      ["orderInfo.quotationGoodsInfoList"]: [],
    });
    this.getQuotationInfo(true); // 不重新调用详情接口 避免修改车辆价格导致重新获取详情 把数据重置了
  },
  getQuotationInfo(getOrderInfo, timeNum = 0) {
    let { default4SStoreInfo } = wx.$util.getUserInfo();
    let {
      owner: { price, carSeriesId },
      orderInfo,
      id,
    } = this.data;
    // if (!price) {
    //   wx.$util.showLoading("加载中...");
    // }
    wx.$util.showLoading("加载中...");
    // debugger
    quotationGoodsList({
      merchantId: default4SStoreInfo.merchantId,
      suitCarPrice: price ? parseFloat((price / 10000).toFixed(4)) : "",
      seriesId: carSeriesId
    })
      .then((result) => {

        console.log(result, "result");
        // debugger
        let { data } = result;
        data = data.map((ele) => {
          // console.log(item.upgradeGoodsServiceItemsList,'item.upgradeGoodsServiceItemsList');
          if (ele.goods) {
            let item = ele.goods;
            let serveName;
            if (
              item?.upgradeGoodsServiceItemsList &&
              item.upgradeGoodsServiceItemsList.length
            ) {
              serveName = item.upgradeGoodsServiceItemsList.reduce(
                (label, ele, index) => {
                  let unit = index == 0 ? "" : "/";
                  label = label + unit + ele?.serviceName;
                  return label;
                },
                ""
              );
            }
            if (item.position) {
              const fieldMap = {
                "4大件": "燃油车4大件服务",
                "3电": "新能源3电服务",
                "6大件": "新能源6大件服务",
                // 在这里可以添加更多的替换规则
              };
              // 如果输入字段在字段映射中有匹配项,则进行替换,否则保持不变
              fieldMap[item.position] && (serveName = fieldMap[item.position]);
            }
            ele.goods = {
              ...item,
              goodsId: item.merchantGoodsId,
              serveName,
              goodsNameAlias: item.upgradeGoodsAlias,
              appreciation: item?.appreciation,
              goodsName: item?.upgradeGoodsName,
              specificationData: item.specificationData ? item.specificationData.replace(/;~;/g, '/') : '',
              quotationGoodsServiceItemsRelationDTOList:
                item?.upgradeGoodsServiceItemsList,
              titlePictureUrl: item.goodsInfo?.thumbUrl,
            };
          }
          if (ele.packageGoods) {
            let item = ele.packageGoods;
            ele.packageGoods.sellPrice = item.goodsList.reduce((pre, item) => {
              // pre = pre + item.sellPrice
              pre = NP.plus(pre, item.sellPrice);
              return pre;
            }, 0);
          }
          return ele;
        });
        this.setData({
          quotationGoodsList: data,
        });
        // debugger
        setTimeout(() => {
          wx.hideLoading();
        }, timeNum)
        // 判断有没有勾选商品,有的话调用一下
        orderInfo.vdQuotationGoodsList.length && this.totalFee();
        // 获取订单详情
        if (id && !getOrderInfo) {
          this.getOrderInfo();
        }
      })
      .catch((err) => {
        // 获取订单详情
        if (id && !getOrderInfo) {
          this.getOrderInfo();
        }
      });
  },
  // 后面改成全局方法
  // 除以100保留两位小数点
  divideByHundred: (str) => {
    let floatVal = parseFloat(str);
    if (isNaN(floatVal)) {
      return 0;
    }
    floatVal = Math.round(str * 100) / 10000;
    let strVal = floatVal.toString();
    let searchVal = strVal.indexOf(".");
    if (searchVal < 0) {
      searchVal = strVal.length;
      strVal += ".";
    }
    while (strVal.length <= searchVal + 2) {
      strVal += "0";
    }
    return parseFloat(strVal);
  },
  // 乘以100保留两位小数点
  multipliedByHundred: (str) => {
    let floatVal = parseFloat(str);
    if (isNaN(floatVal)) {
      return 0;
    }
    floatVal = Math.round(str * 10000) / 100;
    let strVal = floatVal.toString();
    let searchVal = strVal.indexOf(".");
    if (searchVal < 0) {
      searchVal = strVal.length;
      strVal += ".";
    }
    while (strVal.length <= searchVal + 2) {
      strVal += "0";
    }
    return parseFloat(strVal);
  },
  back() {
    console.log("back");
    let { step, isClue } = this.data;
    console.log("step", step);
    // return wx.$router.go('packageEquity.equityPage', { tabIndex: 1 })
    if (isClue) return wx.$router.back();
    if (step == "first") {
      wx.$router.reLaunch("packageEquity.equityPage");
    } else {
      this.setData({
        step: "first",
      });
    }
  },
  navbarReady(e) {
    let navBarHeight = e.detail.height;
    this.setData({
      navBarHeight,
    });
  },
  init() { },
  onRoute(options) {
    // console.log(options, "options");
    // options.id = 258
    let { firstEnter } = this.data
    // 判断是编辑还是新增
    let {
      outTradeNo,
      totalFee,
      accountDate,
      id,
      resetOrder,
      isClue,
      customerInfo,
    } = options;
    // outTradeNo
    if (outTradeNo) {
      this.setData({
        outTradeNo,
        totalFee: totalFee,
        ["orderInfo.outTradeNo"]: outTradeNo,
        accountDate,
      });
    }
    if (resetOrder) this.resetOrder = resetOrder;
    if (id) {
      this.setData({
        id,
      });
    }
    // 只在第一次进入调用商品查询接口
    firstEnter && this.getQuotationInfo();
    //客户线索回显客户信息
    if (customerInfo) this.setCustomerInfo(customerInfo);
    this.setData({
      isClue,
      firstEnter: false
    });
    this.orderSettingList()
    this.getCarBrandList()
  },
  setCustomerInfo(customerInfo) {
    let { owner, orderInfo } = this.data;
    owner.owner = customerInfo.customerName;
    owner.phone = customerInfo.customerPhone;
    owner.ownerGender = customerInfo.customerSex != 2 ? "男" : "女";
    owner.seat = customerInfo.carSeat || 5;
    if (customerInfo.carPrice)
      owner.price = NP.times(customerInfo.carPrice, 0.01);
    owner.city = customerInfo.customerCity;
    owner.ageRange = customerInfo.customerAgeRange;
    owner.hobby = customerInfo.customerHobby;
    owner.companion = customerInfo.customerCompanion;
    owner.certificateNo = customerInfo.customerCertificateNo || "";
    owner = {
      ...owner,
      ...customerInfo,
    };
    if (customerInfo.salesUuid) {
      orderInfo.referrerId = customerInfo.salesUuid;
      orderInfo.referrer = customerInfo.salesName;
    }
    if (customerInfo.salesType) {
      owner.salesType = "售后";
    } else {
      owner.salesType = "售前";
    }
    this.setData({
      owner,
      orderInfo,
    });
  },
  orderSettingList() {
    let userInfo = wx.$util.getStorageSync('dj_boutique_user_info')
    let params = {
      scene: 0,
      isRequired: 1,
      merchantId: userInfo.default4SStoreInfo.merchantId
    }
    orderSettingList(params).then((result) => {
      console.log(result, 'result');
      let { code, data } = result
      if (code == 0) {
        let required = data.reduce((pre, item) => {
          if (item.isRequired) {
            pre.push(item.fieldKey)
          }
          return pre
        }, [])

        let firstCom = this.selectComponent(`#FirstStep`)
        let firstData = wx.$util.deepClone(dataForm)
        let first = firstData.firstObjSimple
        let formRule = firstData.formRuleSimple
        // console.log(firstData = this.selectComponent(`#FirstStep`).data);
        // let secondData = this.selectComponent(`#SecondStep`).data
        // 没有才走获取档案接口逻辑修改配置,有是必填优先及更高
        if (!required.length) {
          firstCom.getYqStoreConfig()
        }
        console.log(required, firstData, 'required');
        if (required.includes('carBrand')) {
          first.carFormList[0] = {
            configItem: true,
            label: "车型",
            name: "brands",
            type: "slot",
            required: true,
            requiredAfter: true
          }
          formRule.carSeriesName = [
            {
              required: true,
              message: "车型不能为空",
            },
          ]
        }
        if (required.includes('carNo')) {
          first.carFormList[2] = {
            label: "车架号",
            maxlength: "17",
            name: "carVin",
            type: "input",
            required: true,
            requiredAfter: true
          }
          formRule.carVin = [
            {
              required: true,
              message: "车架号不能为空",
            },
            {
              validator: (rule, value) => {
                return value.length != 17
                  ? {
                    message: "请输入正确的17位车架号",
                  }
                  : null;
              },
            },
          ]
        }
        if (required.includes('idNumber')) {
          first.customerFormList[6] = {
            label: "证件号码",
            maxlength: "18",
            name: "certificateNo",
            placeholder: "请输入(必填)",
            type: "input",
            required: true,
            requiredAfter: true
          }
          formRule.certificateNo = [
            {
              required: true,
              message: "证件号码不能为空",
            },
            {
              validator: (rule, value) => {
                if (value) {
                  return value.length != 18
                    ? {
                      message: "请输入正确的18位证件号",
                    }
                    : null;
                }
              },
            },
          ]
        }
        console.log(first, formRule, 'firstData');
        firstCom.setData({
          first,
          formRule
        })
      }
    }).catch((err) => {

    });
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    const that = this;
    wx.$eventbus.on("set_car_info", (res) => {
      that.setData({
        ["owner.carBrandId"]: res.vehicleBrandId,
        ["owner.carBrand"]: res.vehicleBrandName,
        ["owner.carChildsBrandId"]: res.vehicleSubBrandId,
        ["owner.carChildsBrandName"]: res.vehicleSubBrandName,
        ["owner.carSeriesId"]: res.vehicleSeriesId,
        ["owner.carSeriesName"]: res.vehicleSeriesName,
      });
    });

  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() { },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow() { },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() { },
  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() { },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() { },
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() { },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() { },
});