<template>
  <div>
    <el-table :data="item.rows" :resizable="false">
      <el-table-column
        v-for="(rowItem, rowItemIdx) in item.rows[0]"
        :key="rowItemIdx"
      >
        <template #header>
          <div v-if="item.label != 'text'">
            <el-dropdown
              :disabled="item.isPreviewModel"
              trigger="click"
              :show-timeout="0"
              @command="projectCommand"
            >
              <el-button text :type="item.isPreviewModel ? '' : 'primary'">
                <span>{{
                  item.header[rowItemIdx]
                    ? item.headerName
                      ? item.headerName[rowItemIdx]
                      : tableHeaderLabel[item.header[rowItemIdx]]
                    : "多余列"
                }}</span>
                <operation class="m-l-2 w-4 h-4 inline-block" />
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item
                    :disabled="!rowItemIdx"
                    :command="{
                      method: projectExchangeLeft,
                      params: [item, rowItemIdx]
                    }"
                    ><d-arrow-left
                      class="w-4 h-4 inline-block"
                    />交换左列</el-dropdown-item
                  >
                  <el-dropdown-item
                    :disabled="rowItemIdx >= item.rows[0].length - 1"
                    :command="{
                      method: projectExchangeRight,
                      params: [item, rowItemIdx]
                    }"
                    ><d-arrow-right
                      class="w-4 h-4 inline-block"
                    />交换右列</el-dropdown-item
                  >
                  <el-dropdown-item
                    :command="{
                      method: splitColumn,
                      params: [item, rowItemIdx, -1]
                    }"
                    ><Fold class="w-4 h-4 inline-block" />
                    拆分列,数字在前</el-dropdown-item
                  >
                  <el-dropdown-item
                    :command="{
                      method: splitColumn,
                      params: [item, rowItemIdx, 1]
                    }"
                    ><Expand class="w-4 h-4 inline-block" />
                    拆分列,数字在后</el-dropdown-item
                  >
                  <el-dropdown-item
                    :command="{
                      method: splitNumberColumn,
                      params: [item, rowItemIdx]
                    }"
                    ><Scissor
                      class="w-4 h-4 inline-block"
                    />抽取数字列</el-dropdown-item
                  >
                  <el-dropdown-item
                    :command="{
                      method: deleteProjectColumn,
                      params: [item, rowItemIdx]
                    }"
                    ><Delete
                      class="w-4 h-4 inline-block"
                    />删除列</el-dropdown-item
                  >
                </el-dropdown-menu>
              </template>
            </el-dropdown>
            <!-- <span v-else>{{ item.header[rowItemIdx] ? (item.headerName ? item.headerName[rowItemIdx] : tableHeaderLabel[item.header[rowItemIdx]]) : '多余列' }}</span> -->
          </div>
          <span v-else>结果</span>
        </template>
        <template #default="{ row, $index }">
          <template v-if="row[rowItemIdx]">
            <template v-if="!item.isPreviewModel">
              <template
                v-if="
                  item.header[rowItemIdx] == 'value' &&
                  row[0].extra?.valueRegexType == 3
                "
              >
                <el-select
                  v-model="row[rowItemIdx].infer"
                  :disabled="item.isPreviewModel"
                  :class="{
                    'no-match':
                      item.header[rowItemIdx] == 'value'
                        ? !verificationProjectRowVal(
                            row[rowItemIdx].infer,
                            row[0]
                          )
                        : rowItemIdx && !row[rowItemIdx].extra,
                    'form-disabled': item.isPreviewModel
                  }"
                >
                  <el-option
                    v-for="(value, valueIndex) in row[0].extra?.valueRegexRule
                      .data.valueList"
                    :key="valueIndex"
                    :label="value"
                    :value="value"
                  ></el-option>
                </el-select>
              </template>
              <template
                v-else-if="
                  item.header[rowItemIdx] == 'value' &&
                  row[0].extra?.valueLimit &&
                  row[0].extra?.valueLimit.type == 3
                "
              >
                <el-select
                  v-model="row[rowItemIdx].infer"
                  :disabled="item.isPreviewModel"
                  filterable
                  :class="{
                    'no-match':
                      item.header[rowItemIdx] == 'value'
                        ? !verificationProjectRowVal(
                            row[rowItemIdx].infer,
                            row[0]
                          )
                        : rowItemIdx && !row[rowItemIdx].extra,
                    'form-disabled': item.isPreviewModel
                  }"
                >
                  <el-option
                    v-for="(value, valueIndex) in row[0].extra?.valueLimit
                      .value"
                    :key="valueIndex"
                    :label="value"
                    :value="value"
                  ></el-option>
                </el-select>
              </template>
              <el-input
                v-else
                v-model.trim="row[rowItemIdx].infer"
                :key="`${$index}-${rowItemIdx}`"
                type="textarea"
                :disabled="item.isPreviewModel"
                :class="{
                  'proof-input': true,
                  'form-disabled': item.isPreviewModel,
                  'no-match':
                    item.header[rowItemIdx] == 'value'
                      ? !verificationProjectRowVal(
                          row[rowItemIdx].infer,
                          row[0]
                        )
                      : rowItemIdx && !row[rowItemIdx].extra
                }"
                :resize="item.isPreviewModel ? 'none' : undefined"
                :autosize="item.isPreviewModel ? false : { minRows: 1 }"
              ></el-input>
            </template>
            <span
              v-else
              :class="{
                'no-match':
                  item.header[rowItemIdx] == 'value'
                    ? !verificationProjectRowVal(row[rowItemIdx].infer, row[0])
                    : rowItemIdx && !row[rowItemIdx].extra
              }"
              >{{ row[rowItemIdx].infer }}</span
            >
          </template>
        </template>
      </el-table-column>
      <el-table-column v-if="isEditView" label="操作" width="80">
        <template #default="{ row, $index }">
          <el-dropdown
            :disabled="item.isPreviewModel"
            trigger="click"
            :show-timeout="0"
            @command="projectCommand"
          >
            <el-button
              text
              :type="item.isPreviewModel ? '' : 'primary'"
              class="f-s-16"
              ><operation class="m-r-2 w-4 h-4 inline-block"
            /></el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item
                  :command="{
                    method: mergeProjectRow,
                    params: [item, $index, 1]
                  }"
                  ><bottom
                    class="w-4 h-4 inline-block"
                  />向下合并</el-dropdown-item
                >
                <el-dropdown-item
                  :command="{
                    method: mergeProjectRow,
                    params: [item, $index, -1]
                  }"
                  ><top
                    class="w-4 h-4 inline-block"
                  />向上合并</el-dropdown-item
                >
                <el-dropdown-item
                  :command="{
                    method: deleteProjectRow,
                    params: [item, $index]
                  }"
                  ><delete
                    class="w-4 h-4 inline-block"
                  />删除行</el-dropdown-item
                >
                <el-dropdown-item
                  :command="{
                    method: addProjectRow,
                    params: [item, $index]
                  }"
                  ><Plus class="w-4 h-4 inline-block" />添加行</el-dropdown-item
                >
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </template>
      </el-table-column>
      <el-table-column
        v-for="(col, colIdx) in item.label == 'indicator'
          ? ['身体物质/部位', '检查项目']
          : ['检查项目', '身体物质/部位']"
        :label="col"
      >
        <template #default="{ row, $index }">
          <template v-if="col == '身体物质/部位'">
            <template v-if="!item.isPreviewModel">
              <el-select
                v-model="item.node[$index]"
                :disabled="
                  item.isPreviewModel ||
                  (item.label == 'text' && !item.matchProject[$index])
                "
                :placeholder="
                  item.isPreviewModel && !item.node[$index]
                    ? ''
                    : '请输入搜索后选择'
                "
                filterable
                clearable
                collapse-tags
                remote
                :class="{
                  'no-match': !item.node[$index],
                  'form-disabled': item.isPreviewModel
                }"
                :multiple="item.label == 'text'"
                :remote-method="
                  query =>
                    item.label != 'text' && searchBodyNodes(query, idx, $index)
                "
                @change="matchNodeChange(item, idx, $index, row)"
                @clear="matchNodeClear(item, $index)"
              >
                <!-- 'repeat-match':
                            row[0].repeat && row[0].repeat.length, -->
                <el-option
                  v-for="(project, projectIdx) in item.nodes[$index]"
                  :key="project.id"
                  :label="project.properties?.name"
                  :value="project.id"
                  class="h-auto"
                >
                  <div class="">
                    <div>{{ project.properties?.name }}</div>
                    <div v-if="project.matched" class="text-gray-500 text-xs">
                      匹配名称：{{ project.matched }}
                    </div>
                  </div>
                </el-option>
              </el-select>
            </template>
            <template v-else>
              <span
                v-if="
                  Array.isArray(item.node[$index])
                    ? item.node[$index].length
                    : item.node[$index]
                "
              >
                {{
                  Array.isArray(item.node[$index])
                    ? item.node[$index]
                        .map(
                          nodeId =>
                            item.nodes[$index].find(v => v.id == nodeId)
                              ?.properties?.name
                        )
                        .join()
                    : item.nodes[$index].find(v => v.id == item.node[$index])
                        ?.properties?.name
                }}
              </span>
              <span v-else class="text-red-500">未匹配</span>
            </template>
          </template>
          <template v-else>
            <template v-if="!item.isPreviewModel">
              <el-select
                v-model="item.matchProject[$index]"
                :disabled="
                  item.isPreviewModel ||
                  (item.label == 'indicator' && !item.node[$index])
                "
                :placeholder="
                  item.isPreviewModel && !item.matchProject[$index]
                    ? ''
                    : '请输入搜索后选择'
                "
                filterable
                clearable
                remote
                :class="{
                  'no-match': !item.matchProject[$index],
                  'form-disabled': item.isPreviewModel
                }"
                :remote-method="query => searchOcrIndicator(query, idx, $index)"
                @change="matchProjectChange(item, idx, $index, $event)"
                @clear="matchProjectClear(item, $index)"
              >
                <!-- 'repeat-match':
                              row[0].repeat && row[0].repeat.length, -->
                <el-option
                  v-for="(project, projectIdx) in item.indicators[$index]"
                  :key="project.id"
                  :label="project.properties?.name"
                  :value="project.id"
                  class="h-auto"
                >
                  <div class="">
                    <div>{{ project.properties?.name }}</div>
                    <div v-if="project.matched" class="text-gray-500 text-xs">
                      匹配名称：{{ project.matched }}
                    </div>
                  </div>
                </el-option>
              </el-select>
            </template>
            <template v-else>
              <span v-if="item.matchProject[$index]">
                {{
                  item.indicators[$index].find(
                    v => v.id == item.matchProject[$index]
                  ).properties?.name
                }}
              </span>
              <span v-else class="text-red-500">未匹配</span>
            </template>
          </template>
        </template>
      </el-table-column>
    </el-table>
    <div
      v-if="item.children && item.children.length"
      class="mt-2 bg-gray-50 p-4"
    >
      <div class="font-bold pb-2 border-b border-solid border-white">
        <span class="text-gray-700">异常内容</span>
      </div>
      <div v-for="(child, childIdx) in item.children" :key="childIdx">
        <div class="text-sm text-gray-600">
          {{
            item.rows[child.rowIdx] &&
            item.rows[child.rowIdx][0] &&
            item.rows[child.rowIdx][0]?.extra?.node?.properties?.name
          }}
        </div>
        <template v-if="!item.isPreviewModel">
          <div class="mb-2">
            <el-select
              v-model="child.curChildIndex"
              multiple
              filterable
              collapse-tags
              collapse-tags-tooltip
              class="w-80"
            >
              <el-option
                v-for="(childAlias, childAliasIdx) in child.abnormal"
                :key="childAliasIdx"
                :label="childAlias?.properties?.name"
                :value="childAliasIdx"
              ></el-option>
            </el-select>
          </div>
        </template>
        <div class="flex flex-wrap items-center">
          <div
            v-for="(childProject, childProjectIdx) in child.curChildIndex.map(
              k => child.abnormal[k]
            )"
            class="mr-2 mb-2 bg-blue-50 text-blue-600 py-2 px-4 rounded text-sm w-fit"
            :key="childProjectIdx"
          >
            <div class="flex items-center justify-between">
              <span class="text-base">{{
                childProject?.properties?.name
              }}</span>
              <Close
                v-if="!item.isPreviewModel"
                class="w-4 h-4 block cursor-pointer ml-2"
                @click="child.curChildIndex.splice(childProjectIdx, 1)"
              />
            </div>
            <template v-if="!item.isPreviewModel">
              <div
                v-if="childProject.properties?.props?.length"
                class="space-y-2 mt-2"
              >
                <div
                  v-for="(attr, attrIdx) in childProject.properties?.props"
                  :key="attrIdx"
                >
                  <span class="mr-2">{{ attr.name }}</span>

                  <template v-if="attr.type == 1">
                    <el-input
                      v-model.number="attr.val"
                      class="w-52 margin-left-10"
                      :placeholder="attr.placeholder || '请输入'"
                    ></el-input>
                  </template>
                  <template v-if="attr.type == 2">
                    <el-input
                      v-model.number="attr.val"
                      type="number"
                      :min="Number(attr.min)"
                      :max="Number(attr.max)"
                      class="w-52 margin-left-10"
                      :placeholder="attr.placeholder || '请输入'"
                    ></el-input>
                  </template>
                  <template v-if="attr.type == 3">
                    <el-select v-model="attr.val">
                      <el-option
                        v-for="(value, valueIndex) in attr.value"
                        :key="valueIndex"
                        :label="value"
                        :value="value"
                      ></el-option>
                    </el-select>
                  </template>
                </div>
                <template v-if="childProject.type == 1">
                  <el-input
                    v-model="childProject.val"
                    type="number"
                    size="small"
                    :max="
                      (childProject.valueRegexRule &&
                        childProject.valueRegexRule.data &&
                        childProject.valueRegexRule.data.total.max) ||
                      undefined
                    "
                    class="w-32 margin-left-10"
                    placeholder="请输入"
                  ></el-input>
                  <el-select
                    v-if="childProject.units.length"
                    v-model="childProject.unit"
                    size="small"
                  >
                    <el-option
                      v-for="(unit, unitIdx) in childProject.units"
                      :key="unitIdx"
                      :label="unit.name"
                      :value="unit.name"
                    ></el-option>
                  </el-select>
                </template>
                <template v-if="childProject.type == 2">
                  <el-input
                    v-model="childProject.val"
                    size="small"
                    :maxlength="
                      (childProject.valueRegexRule &&
                        childProject.valueRegexRule.data &&
                        childProject.valueRegexRule.data.total.max) ||
                      undefined
                    "
                    class="w-32 margin-left-10"
                    placeholder="请输入"
                  ></el-input>
                  <el-select
                    v-if="childProject.units.length"
                    v-model="childProject.unit"
                    size="small"
                  >
                    <el-option
                      v-for="(unit, unitIdx) in childProject.units"
                      :key="unitIdx"
                      :label="unit"
                      :value="unit"
                    ></el-option>
                  </el-select>
                </template>
                <el-select
                  v-if="childProject.type == 3"
                  v-model="childProject.val"
                  size="small"
                >
                  <el-option
                    v-for="(value, valueIndex) in childProject.valueRegexRule
                      .data.valueList"
                    :key="valueIndex"
                    :label="value"
                    :value="value"
                  ></el-option>
                </el-select>
              </div>
            </template>
            <template v-else>
              <template v-if="childProject.valueRegexType > 0">
                ：{{ childProject.val }}
                {{ childProject.unit || "" }}
              </template>
              <tr
                v-for="(attr, attrIdx) in childProject.properties?.props"
                :key="attrIdx"
              >
                <td>
                  <span class="mr-2">{{ attr.name }}</span>
                </td>
                <td>
                  <span class="text-gray-600">{{ attr.val }}</span>
                </td>
              </tr>
            </template>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, inject } from "vue";
import {
  CopyDocument,
  Close,
  Delete,
  Scissor,
  Expand,
  Fold,
  DArrowLeft,
  DArrowRight,
  Operation,
  Top,
  Plus,
  Bottom
} from "@element-plus/icons-vue";

import { ElMessage, ElLoading, ElMessageBox } from "element-plus";
const props = defineProps({
  info: {
    type: Object,
    default: undefined
  },
  edit: {
    type: Boolean,
    default: false
  },
  list: {
    type: Array,
    default: []
  },
  idx: {
    type: Number,
    default: undefined
  }
});
const emit = defineEmits(["update:info", "update:edit"]);
const item = computed({
  get() {
    return props.info;
  },
  set(v) {
    emit("update:info");
  }
});
const isEditView = computed({
  get() {
    return props.info;
  },
  set(v) {
    emit("update:edit");
  }
});
const list = computed(() => props.list);
const idx = computed(() => props.idx);
const searchAddNodes = inject("searchAddNodes");
const searchRelateNodes = inject("searchRelateNodes");

const formatChildProjectChildren = inject("formatChildProjectChildren");

const tableHeaderLabel = {
  key: "项目名称",
  value: "检验结果",
  unit: "单位",
  scope: "参考范围"
};

const recognitionType = ["身体物质/部位", "医学检查项目"];
const relatedRelationship = ["异常属于", "可检测"];

const swapProjectExchange = (item, idx, direction = 1) => {
  const afterIdx = idx + direction;
  item.rows.forEach(row => {
    swap(row, idx, afterIdx);
  });
};
// 拆分列
const splitColumn = (item, rowIdx, direction) => {
  console.log(
    "splitColumn",
    item,
    rowIdx,
    item.rows,
    item.rows.map(v => v[rowIdx])
  );
  // direction > 0 ?
  let addFlag = false;
  let tRows = item.rows.map(v => {
    let tVal =
      direction > 0
        ? formatProjectLastColumnVal(v[rowIdx].infer)
        : formatProjectFirstColumnVal(v[rowIdx].infer);
    console.log(tVal);
    if (Array.isArray(tVal) && tVal.length > 1) {
      addFlag = true;
    }
    return tVal;
  });
  if (!addFlag) {
    return ElMessage.error("未找到数字");
  }
  tRows.forEach((val, idx) => {
    if (addFlag) {
      console.log(val);
      if (Array.isArray(val) && val.length > 1) {
        item.rows[idx][rowIdx].infer = val[1];
        item.rows[idx].splice(rowIdx, 0, {
          ...item.rows[idx][rowIdx],
          infer: val[0]
        });
      } else {
        item.rows[idx].splice(direction > 0 ? rowIdx + 1 : rowIdx, 0, {
          ...item.rows[idx][rowIdx],
          infer: ""
        });
      }
    }
  });
};
const formatProjectFirstColumnVal = v => {
  if (!v && v !== 0) return v;
  console.log(v);
  let firstIdx = v.split("").findIndex(v => v !== "." && isNaN(Number(v)));
  return [v.slice(0, firstIdx), v.slice(firstIdx)].filter(v => v || v === 0);
};
const formatProjectLastColumnVal = v => {
  if (!v && v !== 0) return v;
  let lastIdx =
    v.split("").findLastIndex(v => v !== "." && isNaN(Number(v))) + 1;
  if (lastIdx == v.length) return v;
  let result = [v.slice(0, lastIdx), v.slice(lastIdx)].filter(
    v => v || v === 0
  );
  return result;
};
const splitNumberColumn = (item, colIdx) => {
  item.rows.forEach((row, idx) => {
    let tempNumCol = row[colIdx].infer.replace(/\D/g, "");
    row[colIdx].infer = row[colIdx].infer.replace(/\d/g, "");
    row.splice(colIdx, 0, {
      ...row,
      infer: tempNumCol
    });
  });
};

const deleteProjectColumn = (item, rowIdx) => {
  console.log("deleteProjectColumn", item, rowIdx);
  const checkLen = item.header.filter(v => v).length;
  if (item.rows[0].length <= checkLen) {
    return ElMessage.error("必须保留", item.headerName);
  }
  item.rows.forEach(row => {
    row.splice(rowIdx, 1);
  });
};

const deleteProjectRow = (item, $index) => {
  item.rows.splice($index, 1);
  item.indicators.splice($index, 1);
  item.matchProject.splice($index, 1);
  item.node.splice($index, 1);
  item.nodes.splice($index, 1);
  const childIdx = item.children.findIndex(v => v.rowIdx == $index);
  console.log(childIdx)
  if (childIdx > -1) {
    item.children.splice(childIdx, 1)
    item.children.forEach(v => {
      if (v.rowIdx > childIdx) {
        v.rowIdx--;
      }
    })
  }
  console.log(item)
};
const addProjectRow = (item, $index) => {
  if (item.label == "text") {
    item.rows.splice($index + 1, 0, [
      {
        extra: null,
        infer: ""
      }
    ]);
    item.node.splice($index + 1, 0, []);
  } else {
    item.rows.splice(
      $index + 1,
      0,
      Array(4)
        .fill(0)
        .map(() => ({
          extra: null,
          infer: ""
        }))
    );

    item.node.splice($index + 1, 0, "");
  }
  item.matchProject.splice($index + 1, 0, "");
  item.indicators.splice($index + 1, 0, []);
  item.nodes.splice($index + 1, 0, []);
};

const mergeProjectRow = (item, index, direction) => {
  item.rows[0].forEach((_, key) => {
    if (direction < 0) {
      item.rows[index + direction][key].infer += item.rows[index][key].infer;
    } else {
      item.rows[index + direction][key].infer =
        item.rows[index][key].infer + item.rows[index + direction][key].infer;
    }
    const filter = {};
    const nodeFilter = {};
    item.nodes[index + direction] = [
      ...item.nodes[index],
      ...item.nodes[index + direction]
    ].filter(v => {
      if (!nodeFilter[v.id]) {
        nodeFilter[v.id] = 1;
        return true;
      }
      return false;
    });
    item.node[index + direction] = item.node[index + direction]
      ? item.node[index + direction]
      : item.node[index];
    item.indicators[index + direction] = [
      ...item.indicators[index],
      ...item.indicators[index + direction]
    ].filter(v => {
      if (!filter[v.id]) {
        filter[v.id] = 1;
        return true;
      }
      return false;
    });
    item.matchProject[index + direction] = item.matchProject[index + direction]
      ? item.matchProject[index + direction]
      : item.matchProject[index];
  });
  deleteProjectRow(item, index);
};

const searchBodyNodes = async (key, index, rowIdx) => {
  if (!key) return;
  const nodes =
    (await searchAddNodes(key, false, {
      type: 0
    })) || [];
  const dataIds = nodes.map(v => v.id);
  console.log(list.value);
  let findItem = list.value[index].nodes[rowIdx].find(
    v => v.id == list.value[index].node[rowIdx]
  );
  list.value[index].nodes[rowIdx] =
    findItem && !dataIds.includes(findItem.id) ? [findItem, ...nodes] : nodes;
};
const matchNodeChange = async (item, index, rowIdx, row) => {
  console.log(item, row, item.nodes[rowIdx]);
  const appendChildren = [];
  if (item.label == "indicator") {
    const curNode = item.nodes[rowIdx].find(v => item.node[rowIdx] == v.id);
    const projects = await searchRelateNodes(item.node[rowIdx], 1);
    item.matchProject[rowIdx] = "";
    item.indicators[rowIdx] = projects;
    if (row[0].extra) {
      row[0].extra.node = curNode;
    }
    if (
      curNode &&
      curNode.properties["类型编号"] &&
      Number(curNode.properties["类型编号"][0]) == 0
    ) {
      const abnormal = await searchRelateNodes(item.node[rowIdx], 0);
      abnormal.length &&
        appendChildren.push({
          id: item.node[rowIdx],
          abnormal
        });
    }
  }
  console.log(item);
  if (item.label == "text") {
    const curNodes = item.node[rowIdx].filter(v => {
      const curNode = item.nodes[rowIdx].find(v2 => v == v2.id);
      return (
        curNode.properties["类型编号"] &&
        Number(curNode.properties["类型编号"][0]) == 0
      );
    });
    if (curNodes?.length) {
      const data = await searchRelateNodes(curNodes.join(","), 0);
      data.length &&
        appendChildren.push({
          id: item.node[rowIdx],
          abnormal: data
        });
    }
  }
  console.log(item.children);
  const children = item.children.filter(v => v.rowIdx != rowIdx);
  const temps = [];
  appendChildren.forEach(child => {
    const temp = formatChildProjectChildren(child, { rowIdx });
    temps.push(temp);
  });
  item.children = children.concat(temps);
};
const matchNodeClear = (item, rowIdx) => {
  if (item.label == "indicator") {
    item.nodes[rowIdx] = [];
    item.matchProject[rowIdx] = "";
    item.indicators[rowIdx] = [];
  }
};
const searchOcrIndicator = async (key, index, rowIdx) => {
  if (!key) return;
  const nodes =
    (await searchAddNodes(key, false, {
      type: 1
    })) || [];
  const dataIds = nodes.map(v => v.id);
  let findItem = list.value[index].indicators[rowIdx].find(
    v => v.id == list.value[index].matchProject[rowIdx]
  );
  list.value[index].indicators[rowIdx] =
    findItem && !dataIds.includes(findItem.id) ? [findItem, ...nodes] : nodes;
};
const matchProjectChange = async (item, index, rowIdx, event) => {
  if (item.label == "text") {
    const nodes = await searchRelateNodes(item.matchProject[rowIdx], 1);
    item.node[rowIdx] = [];
    item.nodes[rowIdx] = nodes;
  }
};
const matchProjectClear = (item, rowIdx) => {
  if (item.label == "text") {
    item.node[rowIdx] = [];
    item.nodes[rowIdx] = [];
    item.matchProject[rowIdx] = "";
    item.indicators[rowIdx] = [];
  }
};
const changeEditModule = (item, index) => {
  list.value.forEach((v, k) => {
    v.isPreviewModel = k == index ? !v.isPreviewModel : true;
  });
};

const verificationProjectRowVal = (val, row) => {
  // console.log(val, row);
  if (!row.extra) return true;
  const { valueRegexType, valueRegexRule } = row.extra;

  if (valueRegexType < 0) {
    return true;
  }
  if (!valueRegexRule) return true;

  let rule;
  if (typeof valueRegexRule != "object") {
    try {
      rule = JSON.parse(valueRegexRule);
      row.extra.valueRegexRule = rule;
    } catch (e) {
      console.log(e);
    }
  } else {
    rule = valueRegexRule;
  }
  // console.log(rule);

  switch (valueRegexType) {
    case 1:
      if (isNaN(Number(val))) return false;
      if (rule.data && rule.data.total && rule.data.total.max) {
        return val >= rule.data.total.min && val <= rule.data.total.max;
      }
      return val >= rule.data.total.min;
    case 2:
      if (rule.data.total.max) {
        return val.length <= rule.data.total.max;
      }
      return val.length >= rule.data.total.min || 0;
    case 3:
      return rule.data.valueList.includes(val);
  }
};

const projectCommand = command => {
  console.log({ ...command });

  eval(command.method)(...command.params);
};

const projectExchangeLeft = (item, rowIdx) => {
  swapProjectExchange(item, rowIdx, -1);
};

const projectExchangeRight = (item, rowIdx) => {
  swapProjectExchange(item, rowIdx);
};
const swap = (arr, idx1, idx2) => {
  [arr[idx1], arr[idx2]] = [arr[idx2], arr[idx1]];
};
</script>

<style lang="scss" scoped></style>
