strategyTable.vue 29.7 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
<template>
  <div v-if="showTitle" class="title-row">
    <div class="h-title">策略信息</div>
    <el-button v-if="!isLook" plain @click="invokeTemplate" v-preReClick>合约模板调用</el-button>
  </div>
  <el-table :key="key" class="strategyTable no-scroll-vertical" ref="strategyTableRef" v-loading="strategyDataLoading"
    :data="strategyData" :height="(isReport || isLook) ? 'auto' : '250px'" :highlight-current-row="true" stripe
    tooltip-effect="light" border :span-method="arraySpanMethod">
    <el-table-column label="序号" width="56" align="center" fixed="left" :formatter="formatIndex" />
    <el-table-column prop="action" label="行为类型" :width="isLook ? '106px' : (isReport ? 'auto' : '150px')"
      :min-width="isReport ? '100px' : undefined" align="left" :show-overflow-tooltip="!isReport">
      <template #header>
        <span>行为类型</span>
        <span style="color:red;margin-left: 2px;">*</span>
      </template>
      <template #default="scope">
        <el-select v-if="!isLook" v-model="scope.row['action']" placeholder="请选择" :disabled="isLook"
          @change="(val) => selectOperationChange(val, scope)" clearable filterable>
          <!-- 合约模板时不可以设置这个属性,只能在合约创建时设置 -->
          <el-option
            v-for="opt in actionOptionsList.filter(a => scope.row.action == a.policyName || !strategyData.some(s => s.action == a.policyName))"
            :key="opt['policyName']" :label="opt['policyName']" :value="opt['policyName']" />
        </el-select>
        <span v-else>{{ scope.row['action'] || '--' }}</span>
      </template>
    </el-table-column>
    <el-table-column prop="actionEnName" label="行为类型英文名称" :width="isReport ? 'auto' : '150px'"
      :min-width="isReport ? '120px' : undefined" align="left" :show-overflow-tooltip="!isReport">
      <template #default="scope">
        <el-input v-if="!isLook" v-model="scope.row['actionEnName']" :disabled="true" placeholder="-"></el-input>
        <span v-else>{{ scope.row['actionEnName'] || '--' }}</span>
      </template>
    </el-table-column>
    <el-table-column prop="constraintName" label="约束条件" :width="isLook ? '135px' : (isReport ? 'auto' : '150px')"
      :min-width="isReport ? '100px' : undefined" align="left" :show-overflow-tooltip="!isReport">
      <template #header>
        <span>约束条件</span>
        <span style="color:red;margin-left: 2px;">*</span>
      </template>
      <template #default="scope">
        <el-select v-if="!isLook" v-model="scope.row['constraintName']" placeholder="请选择" :disabled="isLook"
          @change="(val) => selectConditionChange(val, scope)" clearable filterable>
          <el-option v-for="opt in constraintOptionsList" :key="opt['policyName']" :label="opt['policyName']"
            :value="opt['policyName']" />
        </el-select>
        <span v-else>{{ scope.row['constraintName'] || '--' }}</span>
      </template>
    </el-table-column>
    <el-table-column prop="constraintEnName" label="约束条件英文名称" :width="isReport ? 'auto' : '162px'"
      :min-width="isReport ? '120px' : undefined" align="left" :show-overflow-tooltip="!isReport">
      <template #default="scope">
        <el-input v-if="!isLook" v-model="scope.row['constraintEnName']" :disabled="true" placeholder="-"></el-input>
        <span v-else>{{ scope.row['constraintEnName'] || '--' }}</span>
      </template>
    </el-table-column>
    <el-table-column prop="constraintOperatorCode" label="运算符" :width="isLook ? '118px' : (isReport ? 'auto' : '150px')"
      :min-width="isReport ? '100px' : undefined" align="left" :show-overflow-tooltip="!isReport">
      <template #header>
        <span>运算符</span>
        <span style="color:red;margin-left: 2px;">*</span>
      </template>
      <template #default="scope">
        <el-select v-if="!isLook" v-model="scope.row['constraintOperatorCode']" placeholder="请选择" :disabled="isLook"
          clearable filterable @change="(val) => handleOperatorSelectChange(val, scope, 'constraintOperatorCode')">
          <el-option v-for="opt in getActualOperationList(scope)" :key="opt['value']" :label="opt['label']"
            :value="opt['value']" />
        </el-select>
        <span v-else>{{ scope.row['constraintOperatorName'] || '--' }}</span>
      </template>
    </el-table-column>
    <el-table-column prop="constraintValue" label="约束值" :width="(isReport || isLook) ? 'auto' : '300px'"
      :min-width="(isReport || isLook) ? '160px' : undefined" align="left" :show-overflow-tooltip="!isReport">
      <template #header>
        <span>约束值</span>
        <!-- <span style="color:red;margin-left: 2px;">*</span> -->
      </template>
      <template #default="scope">
         <template
          v-if="!isLook && !(productFieldList != null && (scope.row.constraintEnName == 'limitedDeliveryConnector' || scope.row.constraintEnName == 'limitedUseConnector' || scope.row.constraintEnName == 'dataField' || scope.row.constraintEnName == 'limitedState' || scope.row.constraintEnName == 'areaAddress'))">
          <el-input v-model="scope.row['constraintValue']" placeholder="请输入" :maxlength="200"
            @change="(val) => handleOperatorSelectChange(val, scope, 'constraintValue')" clearable></el-input>
          <!-- <span v-if="scope.row.constraintEnName == 'limitedDistributeVolume' || scope.row.constraintEnName == 'limitedUsage'">KB</span> -->
        </template>
        <!-- 限定连接器 -->
        <el-select
          v-else-if="!isLook && productFieldList != null && (scope.row.constraintEnName == 'limitedDeliveryConnector' || scope.row.constraintEnName == 'limitedUseConnector')"
          v-model="scope.row['constraintConnectorValue']" :loading="loading" :remote="true"
          :remote-method="remoteMethod" :max-collapse-tags="1" :collapse-tags="true" :collapse-tags-tooltip="true"
          multiple filterable clearable :placeholder="scope.row.constraintPlaceholderValue || '请输入关键字搜索'"
          value-key="guid" @change="(val) => handleOperatorSelectChange(val, scope, 'constraintConnectorValue')">
          <el-option v-for="opt in connectorList" :key="opt['guid']" :label="opt['tenantName']" :value="opt['guid']" />
        </el-select>
        <!-- 限定字段 -->
        <el-select v-else-if="!isLook && productFieldList != null && scope.row.constraintEnName == 'dataField'"
          :max-collapse-tags="1" :collapse-tags="true" :collapse-tags-tooltip="true"
          v-model="scope.row['constraintFieldValue']" multiple filterable clearable
          :placeholder="scope.row.constraintPlaceholderValue || '请选择'"
          @change="(val) => handleOperatorSelectChange(val, scope, 'constraintFieldValue')">
          <el-option v-for="opt in (scope.row.actionEnName == 'anonymize' ? annonFieldsList : productFieldList)"
            :key="opt['enName']" :label="opt['chName']" :value="opt['enName']" />
        </el-select>
        <!-- 限定状态 -->
        <el-select v-else-if="!isLook && productFieldList != null && scope.row.constraintEnName == 'limitedState'"
          :max-collapse-tags="1" :collapse-tags="true" :collapse-tags-tooltip="true"
          v-model="scope.row['constraintStateValue']" :multiple="false" filterable clearable
          :placeholder="scope.row.constraintPlaceholderValue || '请选择'"
          @change="(val) => handleOperatorSelectChange(val, scope, 'constraintStateValue')">
          <el-option v-for="opt in limitStateOptionList" :key="opt['value']" :label="opt['label']"
            :value="opt['value']" />
        </el-select>
        <el-cascader v-else-if="!isLook && productFieldList != null && scope.row.constraintEnName == 'areaAddress'"
          v-model="scope.row['constraintAddressValue']" :props="addressProps" :show-all-levels="true" :clearable="true"
          show-checked-strategy="parent" :filterable="true" :collapse-tags="true" :collapse-tags-tooltip="true"
          :max-collapse-tags="1" :options="parentAreaData" :disabled="false"
          @change="(val) => handleOperatorSelectChange(val, scope, 'constraintAddressValue')">
        </el-cascader>
        <span v-else>{{ ((scope.row.constraintEnName == 'dataField') ?
          scope.row.additionValue?.map(a => a.chName)?.join(',') : ((scope.row.constraintEnName ==
            'limitedDeliveryConnector' || scope.row.constraintEnName == 'limitedUseConnector') ?
            scope.row.additionValue?.map(a => a.tenantName)?.join(',') : (scope.row.constraintEnName == 'limitedState' ||
              scope.row.constraintEnName == 'areaAddress' ? scope.row.additionValue?.map(a => a.label)?.join(',') :
              scope.row['constraintValue']))) || '--' }}</span>
      </template>
    </el-table-column>
    <el-table-column v-if="!isLook" label="操作" width="140px" align="left" fixed="right" show-overflow-tooltip>
      <template #default="scope">
        <span class="text_btn" @click="handleConditionClickAdd(scope)" v-preReClick>添加约束</span>
        <el-divider direction="vertical" />
        <span class="text_btn" @click="handleConditionDelete(scope)">删除</span>
      </template>
    </el-table-column>
  </el-table>
  <div v-if="!isLook" class="row-add-btn">
    <el-button link @click="addStrategy" :icon="CirclePlus" v-preReClick>添加行为类型</el-button>
  </div>
  <!-- 选择合约模板对话框 -->
  <Dialog_form :dialogConfigInfo="templateDialogInfo" />
</template>

<script lang="ts" setup name="strategyTable">
import { useValidator } from "@/hooks/useValidator";
import { CirclePlus } from "@element-plus/icons-vue";
import {
  getValidContractTemplateList,
  getContractTenantList
} from "@/api/modules/dataSmartContract";
import {
  getAreaData,
} from "@/api/modules/queryService";

const { required } = useValidator();
const { proxy } = getCurrentInstance() as any;

const props = defineProps({
  isLook: { //是否是查看页面,详情查看不需要展示输入框。
    type: Boolean,
    default: false
  },
  value: { // 是个表格数组
    type: Array<any>,
    default: <any>[]
  },
  showTitle: {
    type: Boolean,
    default: false
  },
  actionOptionsList: {//策略操作行为下拉列表
    type: Array<any>,
    default: []
  },
  constraintOptionsList: {//约束行为下拉列表
    type: Array<any>,
    default: []
  },
  operatorOptionList: {//运算符字典下拉列表
    type: Array<any>,
    default: []
  },
  limitStateOptionList: { //限定状态字典下拉列表
    type: Array<any>,
    default: []
  },
  productFieldList: { //字段列表
    type: Array<any>,
    default: null
  },
  annonFieldsList: { //匿名化选择的字段列表
    type: Array<any>,
    default: null
  },
  isReport: {
    type: Boolean,
    default: false
  }
})

const loading = ref(false);
/** 连接器下拉列表,搜索取得 */
const connectorList: any = ref([]);

const key = ref(0);

const getParentAreaPromise: any = ref(null);
const getAreaDataPromise: any = ref({});
const getAreaDatas: any = ref({});
const parentAreaData: any = ref([]);

const getArea = (node, resolve) => {
  const { level } = node
  if (node.data.code == '710000') {
    resolve([]);
    return;
  }
  let params = {
    parentGuid: node.value
  }
  if (!node.value) {
    if (getParentAreaPromise.value) {
      getParentAreaPromise.value.then((res: any) => {
        resolve(res);
      })
    } else {
      resolve(parentAreaData.value);
    }
    return;
  }
  if (node.loaded) {
    resolve([]);
    return;
  }
  if (getAreaDatas.value[node.value]?.length) {
    resolve(getAreaDatas.value[node.value]);
    return;
  }
  if (!getAreaDataPromise.value[node.value]) {
    getAreaDataPromise.value[node.value] = getAreaData(params).then((res: any) => {
      node.loaded = true;
      getAreaDataPromise.value[node.value] = null;
      if (res?.code == proxy.$passCode) {
        const data = res.data ?? []
        data.map(item => {
          item.leaf = level >= 2
        })
        node.data.children = data;
        resolve(data)
        getAreaDatas.value[node.value] = data;
        nextTick(() => {
          if (level == 2 && init.value) {
            key.value++;
            strategyValueInfo.value = transferValueToNew(props.value);
            init.value = false;
          }
        })
        return data;
      }
    })
  } else {
    getAreaDataPromise.value[node.value].then((data) => {
      getAreaDataPromise.value[node.value] = null;
      node.loaded = true;
      data.map(item => {
        item.leaf = level >= 2
      })
      node.data.children = data;
      resolve(data)
      nextTick(() => {
        if (level == 2 && init.value) {
          key.value++;
          strategyValueInfo.value = transferValueToNew(props.value);
          init.value = false;
        }
      })
    })
  }
}

/** 省市区级联属性配置 */
const addressProps = ref({
  label: 'name',
  value: 'guid',
  lazy: true,
  checkStrictly: true,
  lazyLoad: getArea,
  multiple: true,
  checkOnClickNode: false,
})

onBeforeMount(() => {
  getParentAreaPromise.value = getAreaData({ parentId: null }).then((res: any) => {
    if (res?.code == proxy.$passCode) {
      parentAreaData.value = res.data ?? [];
      return parentAreaData.value;
    }
  })
})

const getActualOperationList = (scope) => {
  let val = scope.row.constraintName;
  let conditionItem = val && props.constraintOptionsList.find(c => c.policyName == val);
  let constraintOperatorCodes = conditionItem?.constraintOperatorCodes || [];
  if (!constraintOperatorCodes?.length) {
    return props.operatorOptionList;
  }
  let list: any = constraintOperatorCodes?.map((c, index) => {
    return {
      value: c,
      label: conditionItem?.constraintOperatorCodesName?.[index] || c
    }
  });
  return list;
}

const strategyDataLoading = ref(false);

/** 策略信息结构最终值,带children层级结构 */
const strategyValueInfo: any = ref([{
  index: 1,
  action: '',
  children: [{ childIndex: 1 }]
}]);

/** 将数据库存储的值转化为该组件接收的树形结构 */
const transferValueToNew = (val, isTemplate = false) => {
  let detailPolicyListValue: any[] = []
  connectorList.value = [];
  val?.forEach((p, index) => {
    let lastItem = detailPolicyListValue?.[detailPolicyListValue.length - 1];
    let childInfo = Object.assign({}, p);
    if (childInfo.constraintEnName == 'dataField' && childInfo.additionValue?.length) {
      childInfo.constraintFieldValue = childInfo.additionValue.map(a => a.enName);
    }
    if (childInfo.constraintEnName == 'limitedState' && childInfo.additionValue?.length) {
      childInfo.constraintStateValue = childInfo.additionValue?.[0].value;
    }
    if (childInfo.constraintEnName == 'areaAddress' && childInfo.additionValue?.length) {
      childInfo.constraintAddressValue = childInfo.additionValue.map(a => a.value?.split('-'));
    }
    if ((childInfo.constraintEnName == 'limitedDeliveryConnector' || childInfo.constraintEnName == 'limitedUseConnector') && childInfo.additionValue?.length) {
      childInfo.constraintConnectorValue = childInfo.additionValue.map(a => a.guid);
      connectorList.value.push(...childInfo.additionValue);
    }
    if (isTemplate && (childInfo.constraintEnName == 'dataField' || childInfo.constraintEnName == 'limitedState' || childInfo.constraintEnName == 'limitedDeliveryConnector' || childInfo.constraintEnName == 'limitedUseConnector')) {
      childInfo.constraintPlaceholderValue = childInfo.constraintValue;
    }
    delete childInfo.children; //删掉冗余信息,否则后续修改会覆盖正确的值
    delete childInfo.action;
    delete childInfo.actionEnName;
    delete childInfo.policyTypeCode;
    if (!lastItem || lastItem.action != p.action) {
      detailPolicyListValue.push(Object.assign({
        index: detailPolicyListValue.length + 1,
      }, p, {
        children: [Object.assign({ childIndex: 1 }, childInfo)]
      }))
    } else {
      lastItem.children.push(Object.assign({ childIndex: lastItem.children?.length + 1 }, childInfo));
    }
  })
  return detailPolicyListValue;
}

const init = ref(false);

watch(() => props.value, (val) => {
  //init.value = true;
  strategyValueInfo.value = transferValueToNew(val);
  if (strategyValueInfo.value.some(s => s.constraintEnName == 'areaAddress' && s.additionValue?.some(a => a.value.split('-')?.length > 2))) {
    init.value= true;
  } else {
    init.value= false;
  }
}, {
  deep: true,
  immediate: true
})

watch(() => props.productFieldList, (val, oldValue) => {
  strategyValueInfo.value.forEach(s => {
    s.children?.forEach(sc => {
      if (sc.constraintFieldValue?.length && s.actionEnName != 'anonymize') {
        sc.constraintFieldValue = sc.constraintFieldValue.filter(f => val.some(v => v.enName == f))
      }
    })
  })
}, {
  deep: true
})

watch(() => props.annonFieldsList, (val, oldValue) => {
  strategyValueInfo.value.forEach(s => {
    s.children?.forEach(sc => {
      if (sc.constraintFieldValue?.length && s.actionEnName == 'anonymize') {
        sc.constraintFieldValue = sc.constraintFieldValue.filter(f => val.some(v => v.enName == f))
      }
    })
  })
}, {
  deep: true
})

/** 策略信息表格数据 */
const strategyData = computed(() => {
  let v: any = [];
  strategyValueInfo.value.forEach(s => {
    s.children?.forEach(sc => {
      v.push(Object.assign({}, {
        guid: sc.guid,
        action: s.action,
        actionEnName: s.actionEnName,
        policyTypeCode: s.policyTypeCode,
        index: s.index,
        orderNum: s.orderNum
      }, sc));
    })
  })
  return v;
});

/** 操作行为下拉框改变,带出英文名称等信息 */
const selectOperationChange = (val, scope) => {
  init.value = false;
  let index = scope.row.index;
  let sv = strategyValueInfo.value.find(s => s.index == index);
  if (sv) {
    let actionOption = props.actionOptionsList.find(o => o.policyName == val);
    sv.actionEnName = actionOption?.policyEnName;
    sv.policyTypeCode = actionOption?.policyTypeCode;
    sv.action = val;
  }
}

/** 约束条件下拉框改变,带出英文名称 */
const selectConditionChange = (val, scope) => {
  init.value = false;
  let constraintEnName = scope.row.constraintEnName;
  let index = scope.row.index;
  let sv = strategyValueInfo.value.find(s => s.index == index);
  let svChild = sv.children?.find(c => c.childIndex == scope.row.childIndex);
  svChild && (svChild.constraintEnName = props.constraintOptionsList.find(o => o.policyName == val)?.policyEnName);
  svChild && (svChild.constraintName = val);
  if (svChild && (!val || val != constraintEnName) && (constraintEnName == 'areaAddress' || constraintEnName == 'dataField' || constraintEnName == 'limitedState' || constraintEnName == 'limitedDeliveryConnector' || constraintEnName == 'limitedUseConnector')) {
     //可能是清除操作,需要同步清除部分值
    svChild.constraintValue = '';
  } 
  if (svChild && svChild.constraintOperatorCode) {
    let opList = getActualOperationList(scope);
    if (!opList.some(o => o.value == svChild.constraintOperatorCode)) {
      svChild.constraintOperatorCode = '';
    }
  }
}

const removeChildrenWithParentsOptimized = (selectedValues) => {
  if (!Array.isArray(selectedValues) || selectedValues.length === 0) {
    return []
  }
  
  // 1. 按路径长度排序(从短到长)
  const sortedValues = [...selectedValues].sort((a, b) => a.length - b.length)
  
  // 2. 使用Map存储所有路径的前缀
  const parentMap = new Map()
  const result = []
  
  // 3. 处理每个路径
  for (const path of sortedValues) {
    let isChild = false
    
    // 4. 检查当前路径的每个前缀(不包括自身)是否已经在parentMap中
    for (let i = 1; i < path.length; i++) {  // 注意:i < path.length,不是 i <= path.length
      const prefix = path.slice(0, i)
      const prefixKey = prefix.join(',')
      
      if (parentMap.has(prefixKey)) {
        // 当前路径是某个已有路径的子节点
        isChild = true
        break
      }
    }
    
    // 5. 如果不是任何已有路径的子节点
    if (!isChild) {
      result.push(path)
      // 将当前路径添加到Map中(作为可能的父节点)
      const pathKey = path.join(',')
      parentMap.set(pathKey, true)
    }
  }
  
  return result
}

const handleOperatorSelectChange = (val, scope, field) => {
  init.value = false;
  let index = scope.row.index;
  let sv = strategyValueInfo.value.find(s => s.index == index);
  let svChild = sv.children?.find(c => c.childIndex == scope.row.childIndex);
  svChild && (svChild[field] = val);
  if (field == 'constraintConnectorValue') {
    svChild.additionValue = val?.map(vv => {
      return connectorList.value.find(c => c.guid == vv);
    })
  } else if (field == 'constraintAddressValue') {
    let result: any[] = removeChildrenWithParentsOptimized(val);
    svChild.additionValue = result?.map(vv => {
      let label = ''
      let node: any = {};
      vv.forEach((vc, index) => {
        if (index == 0) {
          node = parentAreaData.value.find(p => p.code == vc);
          label = label + (node?.name || '');
        } else {
          node = node.children?.find(p => p.code == vc);
          label = label + '/' + (node?.name || '');
        }
      })
      return {
        value: vv.join('-'),
        label: label,
        targetValue: vv.at(-1)
      };
    })
  } else if (field == 'constraintStateValue') {
    let item = val && props.limitStateOptionList?.find(c => c.guid == val);
    svChild.additionValue = !item ? [] : [{
      value: item.value,
      label: item.label
    }];
  }
}

/** 添加策略信息的操作行为行 */
const addStrategy = () => {
  init.value = false;
  let len = strategyValueInfo.value.length;
  if (len == props.actionOptionsList?.length) {
    proxy.$ElMessage.warning('暂无可添加的行为类型!');
    return;
  }
  let lastIndex = strategyValueInfo.value.at(-1)?.index || 0;
  strategyValueInfo.value.push({
    index: lastIndex + 1,
    action: '',
    children: [{ childIndex: 1 }]
  })
}

/** 添加约束条件 */
const handleConditionClickAdd = (scope) => {
  init.value = false;
  /** 根据index值进行添加删除 */
  let index = scope.row.index;
  let sv = strategyValueInfo.value.find(s => s.index == index);
  if (sv) {
    let childIndex = scope.row.childIndex;
    let lastIndex = sv.children.at(-1)?.childIndex || 0;
    sv.children.splice(childIndex, 0, { childIndex: lastIndex + 1 })
  }
}

const handleConditionDelete = (scope) => {
  let index = scope.row.index;
  let sv = strategyValueInfo.value.find(s => s.index == index);
  if (!sv) {
    return;
  }
  if (sv?.children?.length > 1) {
    //删除约束条件。
    proxy.$openMessageBox("确定要删除该约束条件吗?", () => {
      let childIndex = scope.row.childIndex;
      let delIndex = sv.children.findIndex(c => c.childIndex == childIndex);
      delIndex > -1 && sv.children.splice(delIndex, 1);
      proxy.$ElMessage.success('删除成功');
    }, () => {
      proxy.$ElMessage.info("已取消删除");
    })
  } else {
    //同步删除操作行为
    proxy.$openMessageBox("确定要删除该行为类型和约束条件吗?", () => {
      let index = scope.row.index;
      strategyValueInfo.value.splice(index - 1, 1);
      proxy.$ElMessage.success('删除成功');
    }, () => {
      proxy.$ElMessage.info("已取消删除");
    })
  }
}

// 计算合并后的序号
const mergedIndexes = computed(() => {
  let index = 1;
  const mergedIndexes: any[] = [];

  for (let i = 0; i < strategyData.value.length; i++) {
    if (i === 0 || strategyData.value[i - 1]['action'] != strategyData.value[i]['action'] || strategyData.value[i - 1]['index'] != strategyData.value[i]['index']) {
      // 新合并组开始
      mergedIndexes.push(index);
      index++;
    } else {
      // 同一合并组
      mergedIndexes.push(0); // 0表示不显示序号
    }
  }

  return mergedIndexes;
});

// 序号格式化
const formatIndex = (row, column, cellValue, index) => {
  return <string>mergedIndexes.value[index] || '';
};

const arraySpanMethod = ({ row, column, rowIndex, columnIndex }) => {
  if (columnIndex > 2) {
    return [1, 1];
  }

  // 查找当前字段值相同的连续行
  let startRow = rowIndex;
  let endRow = rowIndex;
  let field = column.field;
  // 向前查找
  while (startRow > 0 && strategyData.value[startRow - 1][field] === strategyData.value[rowIndex][field] && strategyData.value[startRow - 1]['index'] == strategyData.value[rowIndex]['index']) {
    startRow--;
  }

  // 向后查找
  while (endRow < strategyData.value.length - 1 && strategyData.value[endRow + 1][field] === strategyData.value[rowIndex][field] && strategyData.value[endRow + 1]['index'] === strategyData.value[rowIndex]['index']) {
    endRow++;
  }

  // 如果当前行不是相同值组的起始行,则不显示
  if (startRow !== rowIndex) {
    return [0, 0];
  }

  // 返回合并的行数
  const rowspan = endRow - startRow + 1;
  return [rowspan, 1];
}

/** 弹出模板选择对话框 */
const invokeTemplate = () => {
  /** 调用获取启用的模板列表接口,如果返回null则提示没有可调用的模板。 */
  getValidContractTemplateList().then((res: any) => {
    if (res?.code == proxy.$passCode) {
      const listData = res.data || [];
      if (!listData?.length) {
        proxy.$ElMessage.warning('当前没有可调用的合约模板');
        return;
      }
      templateFormItems.value[0].options = listData;
      templateFormItems.value[0].default = '';
      templateDialogInfo.value.visible = true;
    } else {
      res?.msg && proxy.$ElMessage.error(res?.msg)
    }
  })
}

const templateFormItems = ref([{
  type: 'select',
  label: '合约模板名称',
  field: 'guid',
  default: '',
  block: true,
  placeholder: '请选择',
  options: [],
  props: {
    value: 'guid',
    label: 'templateName'
  },
  filterable: true,
  clearable: true,
  required: true
}]);

const templateFormRules = ref({
  guid: [required("请选择合约模板名称")],
});

const templateDialogInfo = ref({
  visible: false,
  size: 480,
  title: "合约模板调用",
  type: 'edit',
  formInfo: {
    id: 'copy-form',
    items: templateFormItems.value,
    rules: templateFormRules.value
  },
  btns: {
    submit: (btn, info) => {
      templateDialogInfo.value.visible = false;
      //将选择的值带入表格 TODO,跟经理确认是全量覆盖,还是保留操作行为不同的行。暂时先做成全量覆盖吧。
      let item: any = templateFormItems.value[0].options?.find((i: any) => i.guid == info.guid);
      strategyValueInfo.value = transferValueToNew(item?.policyRSVOS || [], true);
    },
    cancel: () => {
      templateDialogInfo.value.visible = false;
    }
  },
  submitBtnLoading: false
});

const validateValue = () => {
  for (const d of strategyData.value) {
    if (!d.action) {
      proxy.$ElMessage.error('行为类型必填,请填写完整');
      return false;
    }
    if (d.action == '删除' || d.action == '加密') { //删除不需要设置如下条件,先不做判断。
      continue;
    }
    // 加密不需要填写约束条件和运算符
    if (d.action != '加密' && !d.constraintName) {
      proxy.$ElMessage.error('约束条件必填,请填写完整');
      return false;
    }
    if (d.action != '加密' && !d.constraintOperatorCode) {
      proxy.$ElMessage.error('运算符必填,请填写完整');
      return false;
    }
    if (d.constraintEnName == 'dataField') {
      // 如果是模板不需要必填。只有
      if (props.productFieldList !== null) {
        if (!d.constraintFieldValue?.length) {
          proxy.$ElMessage.error('字段的约束值必填,请填写完整');
          return false;
        }
      }
    } else if (d.constraintEnName == 'limitedState') {
      // 如果是模板不需要必填。只有
      if (props.productFieldList !== null) {
        if (!d.constraintStateValue) {
          proxy.$ElMessage.error('字段的约束值必填,请填写完整');
          return false;
        }
      }
    } else if (d.constraintEnName == 'areaAddress') {
      // 如果是模板不需要必填。只有
      if (props.productFieldList !== null) {
        if (!d.constraintAddressValue?.length) {
          proxy.$ElMessage.error('字段的约束值必填,请填写完整');
          return false;
        }
      }
    } else if ((d.constraintEnName == 'limitedDeliveryConnector' || d.constraintEnName == 'limitedUseConnector')) {
      if (props.productFieldList !== null) {
        if (!d.constraintConnectorValue?.length) {
          proxy.$ElMessage.error('约束值必填,请填写完整');
          return false;
        }
      }
    } else {
      if (d.action != '加密' && !d.constraintValue) {
        proxy.$ElMessage.error('约束值必填,请填写完整');
        return false;
      }
    }
  }
  return true;
}

const remoteMethod = (query: string) => {
  if (query) {
    loading.value = true;
    getContractTenantList(query).then((res: any) => {
      loading.value = false;
      if (res.code == proxy.$passCode) {
        connectorList.value = res.data || [];
      } else {
        res?.msg && proxy.$ElMessage.error(res.msg);
      }
    })
    // loading.value = true
    // setTimeout(() => {
    //   loading.value = false
    //   options.value = list.value.filter((item) => {
    //     return item.label.toLowerCase().includes(query.toLowerCase())
    //   })
    // }, 200)
  } else {
    connectorList.value = []
  }
}

defineExpose({
  strategyData,
  validateValue
})
</script>

<style lang="scss" scoped>
.row-add-btn {
  .el-button--default {
    padding: 4px 0px;
    margin-top: 4px;
  }

  :deep(.el-icon) {
    width: 16px;
    height: 16px;

    svg {
      width: 16px;
      height: 16px;
    }
  }
}

.title-row {
  display: flex;
  flex-direction: row;
  height: 44px;
  align-items: center;

  .el-button {
    color: var(--el-button-hover-text-color);
    border-color: var(--el-button-hover-border-color);
  }
}

.h-title {
  font-size: 14px;
  color: #212121;
  font-weight: 600;
  margin-right: 8px;
}

.wid-left-input {
  width: calc(100% - 18px) !important;
  margin-right: 2px;
}
</style>