valuationModelCreate.vue 30.4 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
<script lang="ts" setup name="valuationModelCreate">
import {
  getAssetCatalog,
  saveValuationMode,
  updateValuationMode,
  getValuationModelDetail
} from "@/api/modules/dataEntry";
import { useValidator } from '@/hooks/useValidator';
import useUserStore from "@/store/modules/user";
import {
  changeNum,
} from "@/utils/common";
import moment from "moment";
import useEntryStore from "@/store/modules/dataEntry";

const userStore = useUserStore();
const entryStore = useEntryStore();
const { required } = useValidator();
const { proxy } = getCurrentInstance() as any;
const router = useRouter();
const route = useRoute();
const fullPath = route.fullPath;
const fullscreenLoading = ref(false);

/** 获取当月的最后一天。 */
const getLastDayOfMonth = (month) => {
  const year = parseInt(month.split('-')[0], 10);
  const monthIndex = parseInt(month.split('-')[1], 10) - 1; // JavaScript 的月份是从0开始计数的
  const date = new Date(year, monthIndex + 1, 0); // 使用0可以得到前一个月的最后一天
  const yearString = date.getFullYear();
  const monthString = String(date.getMonth() + 1).padStart(2, '0'); // JavaScript 的月份是从0开始计数的
  const dayString = String(date.getDate()).padStart(2, '0');
  return `${yearString}-${monthString}-${dayString}`;
}

/** 数据产品列表 */
const damProductList: any = ref([]);

const formRef = ref();
const valuateFormItems: any = ref([
  {
    label: "数据产品名称",
    type: "select",
    placeholder: "请选择,来自数据产品目录",
    field: "damGuid",
    default: '',
    options: damProductList.value,
    props: {
      label: 'damName',
      value: 'guid'
    },
    disabled: false,
    filterable: true,
    clearable: true,
    required: true,
  },
  {
    label: "基准日",
    type: "date-month",
    field: "evaluateBaseDate",
    default: getLastDayOfMonth(moment(new Date()).format('YYYY-MM')),
    placeholder: "请选择",
    format: 'YYYY-MM-DD',
    valueFormat: 'YYYY-MM-DD',
    clearable: false,
    required: true,
    style: { width: 'calc(33.33% - 70px)', 'margin-right': '8px' },
    popperClass: 'date-month-popper',
    disabledDate: (date) => {
      const curr = new Date();
      return date.getFullYear() == curr.getFullYear() ? date.getMonth() > curr.getMonth() : false;
    },
  },
  {
    type: "select",
    field: "evaluateMethod",
    default: "1",
    label: "评估方法",
    placeholder: "请选择",
    required: true,
    options: [
      { label: "成本法", value: "1" },
      { label: "收益法", value: "2" },
    ]
  },
  {
    type: "select",
    label: "使用年限(1~10)",
    field: "useYears",
    default: 1,
    options: [{
      value: 1,
      label: '1'
    }, {
      value: 2,
      label: '2'
    }, {
      value: 3,
      label: '3'
    }, {
      value: 4,
      label: '4'
    }, {
      value: 5,
      label: '5'
    }, {
      value: 6,
      label: '6'
    }, {
      value: 7,
      label: '7'
    }, {
      value: 8,
      label: '8'
    }, {
      value: 9,
      label: '9'
    }, {
      value: 10,
      label: '10'
    }],
    placeholder: "年限1~10",
    clearable: false,
    filterable: true,
    required: true,
    visible: false
  },
]);

const valuateFormRules = ref({
  damGuid: [required('请选择数据产品名称')],
  evaluateBaseDate: [required('请选择基准日')],
  evaluateMethod: [required('请选择评估方法')],
  useYears: [{ type: 'number', min: 1, max: 10, message: "请填写年限1~10", trigger: "change", },]
});

const handleValudateFormChange = (val, row, info) => {
  if (row.field == 'evaluateMethod') {
    valuateFormItems.value.forEach(item => {
      item.default = info[item.field];
      if (item.field == 'useYears') {
        item.visible = val != '1';
        item.default = info.useYears ? info.useYears : 1;
      }
    })
  }
}

const handleInputChange = (val, row, info) => {
  if (row.field == 'evaluateBaseDate') {
    valuateFormItems.value.forEach(item => {
      item.default = info[item.field];
      if (item.field == 'useYears') {
        item.visible = info.evaluateMethod != '1';
      } else if (item.field == 'evaluateBaseDate') {
        item.default = getLastDayOfMonth(val);
      }
    })
  }
}

const costTableField: any = ref([
  { label: "环节", field: "link", width: 160 },
  { label: "一级指标", field: "primaryIndex", width: 160 },
  { label: "二级指标", field: "secondIndex", width: 160 },
  { label: '金额(元)', align: 'right', field: 'amount', type: 'input', width: 150, columClass: 'edit_cell' },
  { label: "通常包含的成本输入项", field: "costInput", width: 380 },
  { label: "费用科目", field: "expenseAccount", width: 220 },
]);

const costTableData = ref([{
  orderNum: 1,
  link: '顺序性环节',
  primaryIndex: '数据规划',
  secondIndex: '数据规划',
  amount: '',
  costInput: '包含数据生存周期整体规划所投入的人员薪资、咨询费用及相关资源成本等',
  expenseAccount: '咨询费/会议费/人工费(拆分)'
}, {
  orderNum: 2,
  link: '顺序性环节',
  primaryIndex: '数据采集',
  secondIndex: '人工采集',
  amount: '',
  costInput: '向数据持有人购买数据的价款、注册费、手续费、服务费等',
  expenseAccount: '人工费、劳保费、劳务费、运输费'
}, {
  orderNum: 3,
  link: '顺序性环节',
  primaryIndex: '数据采集',
  secondIndex: '自动化采集',
  amount: '',
  costInput: '在数据采集阶段发生的人员薪酬、打印费、网络费等相关费用',
  expenseAccount: '人工费、设备费、材料费'
}, {
  orderNum: 4,
  link: '顺序性环节',
  primaryIndex: '数据汇聚',
  secondIndex: '数据传输',
  amount: '',
  costInput: '',
  expenseAccount: ''
}, {
  orderNum: 5,
  link: '顺序性环节',
  primaryIndex: '数据汇聚',
  secondIndex: '网络通讯',
  amount: '',
  costInput: '传输数据发生的管道成本',
  expenseAccount: '网络费用'
}, {
  orderNum: 6,
  link: '顺序性环节',
  primaryIndex: '数据加工',
  secondIndex: '数据脱敏',
  amount: '',
  costInput: '对敏感数据进行变形处理所发生的人力成本、技术成本等',
  expenseAccount: '人工费'
}, {
  orderNum: 7,
  link: '顺序性环节',
  primaryIndex: '数据加工',
  secondIndex: '数据清洗',
  amount: '',
  costInput: '去除重复数据、填补缺失值、处理异常值和转换数据格式等投入',
  expenseAccount: '人工费'
}, {
  orderNum: 8,
  link: '顺序性环节',
  primaryIndex: '数据加工',
  secondIndex: '数据标注',
  amount: '',
  costInput: '对数据进行添加标签处理所发生的费用,人工或AI标注',
  expenseAccount: '人工费、无形资产分摊'
}, {
  orderNum: 9,
  link: '顺序性环节',
  primaryIndex: '数据加工',
  secondIndex: '数据整合',
  amount: '',
  costInput: '数据整合成本是指合并整理来自不同数据源的数据所发生的成本',
  expenseAccount: '人工费、材料费等'
}, {
  orderNum: 10,
  link: '顺序性环节',
  primaryIndex: '数据分析',
  secondIndex: '数据分析',
  amount: '',
  costInput: '采用适当的方法对数据进行分析整理所发生的成本费用',
  expenseAccount: '人工费'
}, {
  orderNum: 11,
  link: '顺序性环节',
  primaryIndex: '数据分析',
  secondIndex: '数据可视化',
  amount: '',
  costInput: '通过图形化手段清晰有效地传达信息所发生的成本费用',
  expenseAccount: '人工费'
}, {
  orderNum: 12,
  link: '顺序性环节',
  primaryIndex: '数据产品开发',
  secondIndex: '数据产品开发',
  amount: '',
  costInput: '面向数据应用和服务,开发、封装数据产品所产生的费用',
  expenseAccount: '人工费,股份支付,生产成本外协技术费'
}, {
  orderNum: 13,
  link: '全流程环节',
  primaryIndex: '计算与存储',
  secondIndex: '数据存储',
  amount: '',
  costInput: '存储库的构建、优化等费用',
  expenseAccount: '云存储资源使用费,数据库使用费'
}, {
  orderNum: 14,
  link: '全流程环节',
  primaryIndex: '计算与存储',
  secondIndex: '计算资源',
  amount: '',
  costInput: '按流量计费、云服务分摊',
  expenseAccount: '计算资源采购费用'
}, {
  orderNum: 15,
  link: '全流程环节',
  primaryIndex: '数据维护',
  secondIndex: '数据维护',
  amount: '',
  costInput: '数据权属鉴证、质量评估、登记、交易成本、数据合规费用',
  expenseAccount: '人工费、技术服务费'
}, {
  orderNum: 16,
  link: '全流程环节',
  primaryIndex: '数据维护',
  secondIndex: '数据维护',
  amount: '',
  costInput: '数据加工费用,包括数据调整、补全、标注、更新和脱敏等费用',
  expenseAccount: '人工费、技术服务费'
}, {
  orderNum: 17,
  link: '全流程环节',
  primaryIndex: '数据维护',
  secondIndex: '数据维护',
  amount: '',
  costInput: '数据备份、数据迁移和应急处置等费用',
  expenseAccount: '人工费、设备费、技术服务费'
}, {
  orderNum: 18,
  link: '全流程环节',
  primaryIndex: '数据安全',
  secondIndex: '信息安全',
  amount: '',
  costInput: '软性:等保认证等',
  expenseAccount: '人工费、等保服务费、质量评价服务费、鉴权咨询费'
}, {
  orderNum: 19,
  link: '全流程环节',
  primaryIndex: '数据安全',
  secondIndex: '硬件或系统安全',
  amount: '',
  costInput: '硬件或系统:安全产品、安全管理技术或服务',
  expenseAccount: '防火墙或安全软件等采购费用'
}, {
  orderNum: 20,
  link: '全流程环节',
  primaryIndex: '间接成本',
  secondIndex: '软硬件成本',
  amount: '',
  costInput: '与数据资产相关的软硬件采购或研发以及维护费用',
  expenseAccount: '材料费,产品检测费,物料消耗费,修理费'
}, {
  orderNum: 21,
  link: '全流程环节',
  primaryIndex: '间接成本',
  secondIndex: '基础设施成本',
  amount: '',
  costInput: '包括机房、场地等建设或租赁以及维护费用',
  expenseAccount: '机房建设,物业费,租金,物联网大数据中心建设费'
}, {
  orderNum: 22,
  link: '全流程环节',
  primaryIndex: '间接成本',
  secondIndex: '公共管理成本',
  amount: '',
  costInput: '水电、职工福利、差旅费、折旧费、办公费、通讯费',
  expenseAccount: '水电、职工福利、差旅费、折旧费、办公费、通讯费'
}]);

const costTableSpanMethod = ({ row, column, rowIndex, columnIndex }) => {
  if (columnIndex == 0) { //第一列环节
    let columnValue = costTableData.value[rowIndex].link;
    if (rowIndex == 0 || columnValue != costTableData.value[rowIndex - 1].link) {
      let cnt = costTableData.value.filter(d => d.link == columnValue).length;
      return {
        rowspan: cnt,
        colspan: 1
      }
    } else {
      return {
        rowspan: 0,
        colspan: 0
      }
    }
  } else if (columnIndex == 1) {//第二列的合并
    let columnValue = costTableData.value[rowIndex].primaryIndex;
    if (rowIndex == 0 || columnValue != costTableData.value[rowIndex - 1].primaryIndex) {
      let cnt = costTableData.value.filter(d => d.primaryIndex == columnValue).length;
      return {
        rowspan: cnt,
        colspan: 1
      }
    } else {
      return {
        rowspan: 0,
        colspan: 0
      }
    }
  } else if (columnIndex == 2) {//二级指标,合并数据维护。
    let columnValue = costTableData.value[rowIndex].secondIndex;
    if (columnValue == '数据维护') {
      if (columnValue != costTableData.value[rowIndex - 1].secondIndex) {
        return {
          rowspan: 3,
          colspan: 1
        }
      } else {
        return {
          rowspan: 0,
          colspan: 0
        }
      }
    }
  }
  return {
    rowspan: 1,
    colspan: 1
  }
}

const costTableSummaryValue: any = ref(0);

// 表格合计行
const costTableSummaryMethod = ({ columns, data }) => {
  let sums: any[] = [];
  columns.forEach((column, index) => {
    if (index === 0) {  //需要显示'总金额'的列 坐标 :0
      sums[index] = '数据资产估值'
      return
    } else {
      if (column.property == 'amount') {
        const values = data.map(item => parseFloat(item[column.property] ? item[column.property].replace(/,/g, "") : 0));
        if (!values.every(value => isNaN(value))) {
          const sum = values.reduce((prev, curr) => {
            const value = parseFloat(curr || 0)
            if (!isNaN(value)) {
              return prev + curr
            } else {
              return prev
            }
          }, 0)
          sums[index] = costTableSummaryValue.value = changeNum(sum, 2, true)
        } else {
          sums[index] = costTableSummaryValue.value = 'N/A'
        }
      }
    }
  })
  return sums
}

/** --------------------------- 收入法 --------------------------- */

const incomeTableField: any = ref([
  { label: "指标名称", field: "indexName", width: 160 },
  { label: "单位", field: "unit", width: 100 },
  { label: "预测年限", field: "years", showChild: true, align: 'center' },
  { label: "说明", field: "instructions", width: 380 },
]);

const incomeYears = computed(() => {
  let formInline = formRef.value.formInline;
  if (formInline.evaluateMethod == '1') {
    return [];
  }
  let evaluateBaseDate = formInline.evaluateBaseDate;
  let useYears = formInline.useYears;
  let infos = evaluateBaseDate.split('-');
  let year = parseInt(infos[0]);
  let month = parseInt(infos[1]);
  if (month == 12) {
    let a: any = [];
    for (var i = 1; i < useYears + 1; i++) {
      a.push({
        field: year + i + '',
        label: (year + i) + '年'
      });
    }
    return a;
  } else if (month == 1) {
    let a = [{
      field: evaluateBaseDate + '',
      label: year + '年' + `(2~12)`
    }];
    for (var i = 1; i < useYears + 1; i++) {
      a.push({
        field: year + i + '',
        label: i == useYears ? ((year + i) + '年' + `(1)`) : ((year + i) + '年')
      });
    }
    return a;
  } else {
    let a = [{
      field: evaluateBaseDate + '',
      label: year + '年' + `(${month + 1}~12)`
    }];
    for (var i = 1; i < useYears + 1; i++) {
      a.push({
        field: year + i + '',
        label: i == useYears ? ((year + i) + '年' + `(1~${month})`) : ((year + i) + '年')
      });
    }
    return a;
  }
})

const incomeTableData: any = ref([{
  orderNum: 1,
  indexName: '收入',
  unit: '元',
  instructions: '数据创造或者是数据所在应用场景下的收入'
}, {
  orderNum: 2,
  indexName: '毛利率',
  unit: '%',
  instructions: '数据创造或者是数据所在应用场景下的毛利率'
}, {
  orderNum: 3,
  indexName: '营业利润率',
  unit: '%',
  instructions: '数据创造或者是数据所在应用场景下的营业利润率'
}, {
  orderNum: 4,
  indexName: '净利润率',
  unit: '%',
  instructions: '数据创造或者是数据所在应用场景下的净利润率'
}, {
  orderNum: 5,
  indexName: '行业利润率水平',
  unit: '%',
  instructions: '参考同行业上市公司/企业历史年度细分业务利润率水平'
}, {
  orderNum: 6,
  indexName: '数据资产分成率',
  unit: '%',
  instructions: '即关于数据对于实现收入的贡献'
}, {
  orderNum: 7,
  indexName: '衰减率',
  unit: '%',
  instructions: '数据有效期为5年,衰减率可理解为每年20%'
}, {
  orderNum: 8,
  indexName: '综合分成率',
  unit: '%',
  auto: true,
  instructions: '自动计算'
}, {
  orderNum: 9,
  indexName: '现金流',
  unit: '元',
  auto: true,
  instructions: '自动计算'
}, {
  orderNum: 10,
  indexName: '折现率',
  unit: '%',
  instructions: '一般行业在12%-16%之间,根据数据资产可变现的情况确认'
}, {
  orderNum: 11,
  indexName: '折现年期',
  unit: '年',
  auto: true,
  instructions: '自动计算'
}, {
  orderNum: 12,
  indexName: '折现因子',
  unit: '',
  auto: true,
  instructions: '自动计算'
}, {
  orderNum: 13,
  indexName: '折现现值',
  unit: '元',
  auto: true,
  instructions: '自动计算,收入*利润率*分成率*折现因子'
}, {
  orderNum: 14,
  indexName: '数据资产估值',
  unit: '元',
  auto: true,
  instructions: '自动计算'
}])

const inputChange = (val, scope, field) => {
  let row = scope.row;
  let strArr = val.split(".");
  if (strArr.length > 1) {
    let right = strArr[1];
    if (right === "" || right.length < 2) {
      row[field] = val = parseFloat(val || 0).toFixed(2);
    }
  } else {
    row[field] = val = parseFloat(val || 0).toFixed(2);
  }
  if (val == 'NaN') {
    row[field] = '0.00';
  }
}

/** 输入框输入触发事件 */
const inputEventChange = (val, scope, field, max: any = null) => {
  let row = scope.row;
  if (row.indexName == '数据资产分成率' || row.indexName == '衰减率' || formRef.value.formInline?.evaluateMethod == '1') { //只能输入正数
    let row = scope.row;
    row[field] = row[field].toString().replace(/[^\d.]/g, "")
    row[field] = row[field].toString().replace(/\.{2,}/g, ".")
    row[field] = row[field].toString().replace(".", "$#$").replace(/\./g, "").replace("$#$", ".")
    row[field] = row[field].toString().replace(/^(\-)*(\d+)\.(\d\d\d\d\d\d).*$/, "$1$2.$3")
    row[field] = row[field].toString().replace(/^\D*(\d{0,12}(?:\.\d{0,2})?).*$/g, "$1")
    if (max !== null && row[field] > max) {
      row[field] = max;
    }
  } else { //需要支持负数
    row[field] = row[field].toString().replace(/[^\d.-]/g, "")
    row[field] = row[field].toString().replace(/\.{2,}/g, ".")
    row[field] = row[field].toString().replace(".", "$#$").replace(/\./g, "").replace("$#$", ".")
    // 第四步:移除整数部分前面不必要的零,但保留小数部分的有效零
    if (row[field].startsWith('-')) {
      // 对于负数,去掉负号进行处理
      let tempValue = row[field].substring(1);
      tempValue = tempValue.replace(/-/g, '');;
      row[field] = '-' + tempValue;
    } else {
      // 对于正数直接处理
      row[field] = row[field].replace(/-/g, '');
    }
    row[field] = row[field].toString().replace(/^(-?\d{0,12})(\.\d{0,2})?$/, '$1$2');

    let parts = row[field].split('.');
    let integerPart = parts[0];
    let decimalPart = parts.length > 1 ? parts[1] : '';

    // 限制整数部分最多12位
    if (integerPart.length > 12) {
        integerPart = integerPart.substring(0, 12);
    }

    // 限制小数部分最多2位
    if (decimalPart.length > 2) {
        decimalPart = decimalPart.substring(0, 2);
    }
    row[field] = integerPart + (decimalPart ? '.' + decimalPart : (row[field].includes('.') ? '.' : ''))

    if (max !== null) {
      if (row[field] > max) {
        row[field] = max;
      }
      if (row[field] < 0 && row[field] < -max) {
        row[field] = -max;
      }
    }
  }
}

const incomeCalculateData = computed(() => { //响应式不生效
  let data = incomeTableData.value;
  let resultInfo: any = {};
  resultInfo['综合分成率'] = [];
  resultInfo['现金流'] = [];
  resultInfo['折现年期'] = [];
  resultInfo['折现因子'] = [];
  resultInfo['折现现值'] = [];
  resultInfo['数据资产估值'] = 0;
  let formInline = formRef.value.formInline;
  let evaluateBaseDate = formInline.evaluateBaseDate;
  let infos = evaluateBaseDate.split('-');
  let month = parseInt(infos[1]);
  let transfer = (v, need = true) => {
    return v ? (need ? parseFloat(v) / 100 : parseFloat(v)) : 0;
  }
  incomeYears.value.forEach((year, i) => {
    let C6 = transfer(data[5][year.field])
    let C7 = transfer(data[6][year.field])
    let sumC7: any = 0;
    if (i == 0) {
      sumC7 = C7;
    } else {
      incomeYears.value.slice(0, i + 1).forEach((item) => {
        sumC7 = sumC7 + transfer(data[6][item.field]);
      })
    }
    resultInfo['综合分成率'].push(changeNum(C6 * (1 - sumC7 + C7 / 2) * 100, 2, true)); //TODO综合分成率算法有问题
    let C1 = transfer(data[0][year.field], false)
    let C5 = transfer(data[4][year.field])
    resultInfo['现金流'].push(changeNum(C1 * C5 * resultInfo['综合分成率'][i] / 100, 2, true));
    if (i == 0) {
      let cnt = month == 12 ? 12 : (12 - month);
      resultInfo['折现年期'].push(changeNum(cnt / 12 / 2, 2, true));
    } else if (i == incomeYears.value.length - 1) {
      resultInfo['折现年期'].push(changeNum(parseFloat(resultInfo['折现年期'][i - 1]) + (month == 12 ? 1 : (month / 12 / 2)), 2, true))
    } else {
      resultInfo['折现年期'].push(changeNum(parseFloat(resultInfo['折现年期'][i - 1]) + 1, 2, true))
    }
    let C10 = transfer(data[9][year.field]);
    resultInfo['折现因子'].push(changeNum(1 / Math.pow((1 + C10), parseFloat(resultInfo['折现年期'][i])), 2, true));
    resultInfo['折现现值'].push(changeNum(parseFloat(resultInfo['折现因子'][i]) * parseFloat(resultInfo['现金流'][i]?.replace(/,/g, '')), 2, true));
  })
  resultInfo['数据资产估值'] = resultInfo['折现现值'].length < 2 ?  resultInfo['折现现值'][0] : changeNum(resultInfo['折现现值'].reduce(function (prev, curr, idx, arr) {
    return (typeof prev == 'string' ? parseFloat(prev?.replace(/,/g, '')) : parseFloat(prev)) + parseFloat(curr?.replace(/,/g, ''));
  }), 2, true);
  return resultInfo;
})

const submit = () => {
  formRef.value?.ruleFormRef?.validate((valid, errorItem) => {
    if (valid) {
      let params = formRef.value.formInline;
      if (params.evaluateMethod == '1') {
        params.valuationCostRQVOList = costTableData.value;
        params.damValuation = costTableSummaryValue.value;
        if (!costTableData.value.some(table => table.amount !== '')) {
          proxy.$ElMessage.error('成本法请至少输入一项指标金额');
          return
        }
      } else {
        params.valuationEarningsRQVOList = incomeTableData.value;
        params.damValuation = incomeCalculateData.value['数据资产估值'];
        for (const d of params.valuationEarningsRQVOList) {
          let years: any = {};
          for (const y of incomeYears.value) {
            if (d.auto != true && d[y.field] == null) {
              proxy.$ElMessage.error(`收益法的指标【${d.indexName}】预测年限中存在空值,请输入`);
              return;
            }
            years[y.field] = d[y.field];
          }
          d.predictedYears = years;
        }
      }
      fullscreenLoading.value = true;
      if (!route.query.guid) {
        saveValuationMode(params).then((res: any) => {
          fullscreenLoading.value = false;
          if (res.code == proxy.$passCode) {
            proxy.$ElMessage.success('新建估值模型提交保存成功');
            userStore.setTabbar(userStore.tabbar.filter((tab: any) => tab.fullPath !== fullPath));
            router.push({
              name: 'valuationModel'
            });
            entryStore.setIsRefresh(true);
          } else {
            proxy.$ElMessage({
              type: 'error',
              message: res.msg,
            })
          }
        })
      } else {
        params.guid = route.query.guid;
        updateValuationMode(params).then((res: any) => {
          fullscreenLoading.value = false;
          if (res.code == proxy.$passCode) {
            proxy.$ElMessage.success('编辑估值模型提交成功');
            userStore.setTabbar(userStore.tabbar.filter((tab: any) => tab.fullPath !== fullPath));
            router.push({
              name: 'valuationModel'
            });
            entryStore.setIsRefresh(true);
          } else {
            proxy.$ElMessage({
              type: 'error',
              message: res.msg,
            })
          }
        })
      }
    } else {
      var obj = Object.keys(errorItem);
      formRef.value.ruleFormRef.scrollToField(obj[0])
    }
  })
}

const cancel = () => {
  proxy.$openMessageBox("当前页面尚未保存,确定放弃修改吗?", () => {
    userStore.setTabbar(userStore.tabbar.filter((tab: any) => tab.fullPath !== fullPath));
    router.push({
      name: 'valuationModel'
    });
  }, () => {
    proxy.$ElMessage.info("已取消");
  });
}

const getDamProductListData = () => {
  getAssetCatalog({
    pageSize: -1
  }).then((res: any) => {
    if (res.code == proxy.$passCode) {
      damProductList.value = res.data || [];
      valuateFormItems.value[0].options = damProductList.value;
    } else {
      proxy.$ElMessage({
        type: 'error',
        message: res.msg,
      })
    }
  })
}

onBeforeMount(() => {
  getDamProductListData();
  if (route.query.guid) {
    fullscreenLoading.value = true;
    getValuationModelDetail({ guid: route.query.guid }).then((res: any) => {
      fullscreenLoading.value = false;
      if (res.code == proxy.$passCode) {
        let detailData = res.data || {};
        valuateFormItems.value.forEach(item => {
          item.default = detailData[item.field];
          if (item.field == 'evaluateMethod') {
            valuateFormItems.value.at(-1).visible = item.default == '2';
          }
        })
        if (detailData.evaluateMethod == '2') {
          incomeTableData.value = detailData.valuationEarningsRSVOList || [];
          incomeTableData.value.forEach((d, index) => {
            Object.assign(d, d.predictedYears || {});
            if (d.indexName == '综合分成率' || d.indexName == '现金流' || d.indexName == '折现年期' || d.indexName == '折现因子' || d.indexName == '折现现值' || d.indexName == '数据资产估值') {
              d.auto = true;
            }
          });
        } else {
          costTableData.value = detailData.valuationCostRSVOList || [];
          costTableSummaryValue.value = detailData.damValuation || '';
        }
      } else {
        proxy.$ElMessage({
          type: 'error',
          message: res.msg,
        })
      }
    });
  }
})

onMounted(async () => {
  await nextTick();
  await nextTick();
  const tables: any = document.querySelectorAll(
    "#cost-table .el-table__footer-wrapper tr>td"
  );
  tables[0].colSpan = 3;
  tables[0].style.textAlign = "center";
  tables[1].style.display = "none";
  tables[2].style.display = "none";
  tables[4].style.display = "none";
  tables[5].style.display = "none";
})

</script>

<template>
  <div class="container_wrap" v-loading="fullscreenLoading">
    <div class="content_main">
      <ContentWrap id="id-baseInfo" title="估值类型" instructions="" style="margin-top: 8px;">
        <Form ref="formRef" :itemList="valuateFormItems" :rules="valuateFormRules" formId="main-model-edit"
          @select-change="handleValudateFormChange" @input-change="handleInputChange" col="col3" />
      </ContentWrap>
      <ContentWrap id="id-grade-info" :title="formRef?.formInline?.evaluateMethod == '1' ? '填写成本明细' : '填写预期收益'"
        :description="formRef?.formInline?.evaluateMethod == '1' ? '填写时请按照所选数据产品的成本投入进行填写,跟数据产品产生的成本一致' : ''"
        style="margin-top: 16px;">
        <el-table id="cost-table" v-show="formRef?.formInline?.evaluateMethod == '1'" ref="costTableRef"
          :data="costTableData" :span-method="costTableSpanMethod" :summary-method="costTableSummaryMethod" show-summary
          border tooltip-effect="light" :tooltip-options="{ placement: 'top', popperClass: 'table_cell_tooltip' }">
          <el-table-column v-for="(item, i) in costTableField" :label="item.label" :width="item.width"
            :min-width="item.minWidth" :fixed="item.fixed" :align="item.align" :sortable="item.sortable ?? false"
            :prop="item.field" :class-name="item.columClass" show-overflow-tooltip>
            <template #default="scope">
              <div class="input_cell" v-if="item.type == 'input'">
                <el-input v-model.trim="scope.row[item.field]" placeholder="请输入" :maxlength="item.maxlength ?? ''"
                  @change="(val) => inputChange(val, scope, item.field)"
                  @input="(val) => inputEventChange(val, scope, item.field)" clearable></el-input>
              </div>
              <span v-else>
                {{ item.getName ? item.getName(scope) : scope.row[item.field] !== 0 && !scope.row[item.field] ?
                  "--" : scope.row[item.field] }}
              </span>
            </template>
          </el-table-column>
        </el-table>
        <el-table id="income-table" v-show="formRef?.formInline?.evaluateMethod != '1'" ref="costTableRef"
          :data="incomeTableData" border tooltip-effect="light"
          :tooltip-options="{ placement: 'top', popperClass: 'table_cell_tooltip' }">
          <el-table-column type="index" label="序号" width="80" align="center" />
          <el-table-column v-for="(item, i) in incomeTableField" :label="item.label" :width="item.width"
            :min-width="item.minWidth" :fixed="item.fixed" :align="item.align" :sortable="item.sortable ?? false"
            :prop="item.field" :class-name="item.columClass" show-overflow-tooltip>
            <template #default="scope">
              <template v-if="item.showChild == true">
                <el-table-column v-for="(year, j) in incomeYears" :label="year.label" :width="150" align="right"
                  :prop="year.field" show-overflow-tooltip>
                  <template #default="scope">
                    <div v-if="scope.row.auto != true" class="input_cell">
                      <el-input v-model.trim="scope.row[year.field]" placeholder="请输入"
                        @change="(val) => inputChange(val, scope, year.field)"
                        @input="(val) => inputEventChange(val, scope, year.field, scope.row.unit == '%' ? 100 : null)"
                        clearable></el-input>
                    </div>
                    <span v-else>
                      {{ scope.row.indexName == '数据资产估值' ? (j > 0 ? '-' : incomeCalculateData[scope.row.indexName])
                        : (incomeCalculateData[scope.row.indexName][j]) }}
                    </span>
                  </template>
                </el-table-column>
              </template>
              <span v-else>{{ scope.row[item.field] || '-' }}</span>
            </template>
          </el-table-column>
        </el-table>
      </ContentWrap>
    </div>
    <div class="bottom_tool_wrap">
      <el-button @click="cancel">取消</el-button>
      <el-button type="primary" @click="submit">提交</el-button>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.container_wrap {
  padding: 0px;
}

.content_main {
  height: calc(100% - 44px);
  padding: 10px 16px;
  overflow: auto;

  .table-top-btns {
    margin-bottom: 12px;
  }
}

.bottom_tool_wrap {
  height: 44px;
  padding: 0 16px;
  border-top: 1px solid #d9d9d9;
  display: flex;
  justify-content: center;
  align-items: center;
}

:deep(.el-table) {
  td.el-table__cell {
    padding: 2px 0;
    height: 36px;

    .el-input .el-input__inner {
      text-align: right;
    }
  }
}
</style>