<template>
  <el-form style="margin: 16px 0" ref="ruleFormRef" class="rule-form" :model="tableRows">
    <bg-table-pro
      class="input-table"
      :headers="headers"
      :data="tableRows"
      ref="inputTable"
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      row-key="id"
      default-expand-all
      :border="true"
      :stripe="false">
      <template #ip="{ row }">
        <el-form-item
          :rules="{
            required: true,
            message: 'IP不能为空',
            trigger: 'blur',
          }"
          style="width: 100%"
          :prop="`${row.$row_path}.ip`">
          <el-input clearable placeholder="请输入IP" v-model="row.ip" />
        </el-form-item>
      </template>
      <template #port="{ row }">
        <el-form-item style="width: 100%">
          <el-input clearable placeholder="请输入端口号" v-model="row.port" />
        </el-form-item>
      </template>
      <template #voucher_type="{ row }">
        <el-form-item
          :rules="{
            required: true,
            message: '凭证类型不能为空',
            trigger: 'change',
          }"
          style="width: 100%"
          :prop="`${row.$row_path}.voucher_type`">
          <el-select @change="(val) => changeType(val, row)" v-model="row.voucher_type" placeholder="请选择凭证类型">
            <el-option v-for="item in typeOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
      </template>
      <template #user_name="{ row }">
        <el-form-item
          :rules="{
            required: true,
            message: '用户名不能为空',
            trigger: 'blur',
          }"
          style="width: 100%"
          :prop="`${row.$row_path}.user_name`">
          <el-input clearable placeholder="请输入用户名" v-model="row.user_name" />
        </el-form-item>
      </template>
      <template #password="{ row }">
        <el-form-item
          v-if="row.voucher_type != 1"
          :rules="{
            required: true,
            message: '密码不能为空',
            trigger: 'blur',
          }"
          style="width: 100%"
          :prop="`${row.$row_path}.password`">
          <el-input clearable placeholder="请输入密码" v-model="row.password" />
        </el-form-item>
        <el-form-item v-else required style="width: 100%">
          <el-input disabled />
        </el-form-item>
      </template>
      <template #action="{ row }">
        <bg-table-btn
          :click="
            () => {
              addInputConf(row);
            }
          "
          :disabled="tableRows.length == 5">
          新增
        </bg-table-btn>
        <bg-table-btn
          :click="
            () => {
              removeInputConf(row);
            }
          "
          :disabled="tableRows.length == 1">
          删除
        </bg-table-btn>
      </template>
    </bg-table-pro>
  </el-form>
</template>

<script setup>
import { ref, reactive, toRefs, watch } from "vue";
import { v4 as uuidv4 } from "uuid";

const props = defineProps({
  initTableData: {
    default: () => {
      return [];
    },
  },
});

const ruleFormRef = ref(null);
const inputTable = ref(null);

const headers = reactive([
  {
    label: "IP（IP之间用英文逗号分隔）",
    required: true,
    prop: "ip",
    width: 300,
  },
  {
    label: "端口号（不填写，默认为22）",
    prop: "port",
  },
  {
    label: "凭证类型",
    required: true,
    prop: "voucher_type",
  },
  {
    label: "用户名",
    required: true,
    prop: "user_name",
  },
  {
    label: "密码",
    required: true,
    prop: "password",
  },
  {
    label: "操作",
    prop: "action",
    width: 120,
  },
]);

const typeOptions = [
  {
    value: 0,
    label: "密码验证",
  },
  {
    value: 1,
    label: "密钥验证",
  },
];

const state = reactive({
  inputTable,
  tableRows: [],
});
const { tableRows } = toRefs(state);

const addInputConf = (row) => {
  let tempRow = createRow();

  if (row) {
    let { index, rows } = getInputRowInfo(row);
    rows.splice(index + 1, 0, tempRow);
  } else {
    state.tableRows = [tempRow];
  }

  updateInputConfRows();
}; //增加

const updateInputConfRows = () => {
  let recursionItems = (items, parentType, parentPath) => {
    for (let i = 0; i < items.length; i++) {
      let item = items[i];

      item.$parent_type = parentType;
      item.$row_path = `${parentPath}[${i}]`;

      if (item.children && item.children.length) {
        let basePath = `${item.$row_path}.children.`;

        recursionItems(item.children, item.paramType, basePath);
      }
    }
  };

  recursionItems(state.tableRows, "", "");
  clearValidate();
}; // 更新 $parent_type 和 $row_path 字段

const clearValidate = () => {
  ruleFormRef.value && ruleFormRef.value.clearValidate();
};

const createRow = () => {
  return {
    id: uuidv4(),
    ip: "",
    port: "22",
    voucher_type: "",
    user_name: "",
    password: "",
  };
};

const getInputRowInfo = (row) => {
  return state.inputTable && state.inputTable.getRowInfo(row, `id`);
}; //获取当前行的数据信息

const removeInputConf = (row) => {
  let { index, rows } = getInputRowInfo(row);

  rows.splice(index, 1);

  if (rows.length === 0) {
    rows.push(createRow());
  }

  updateInputConfRows();
}; // 删除

const initTable = () => {
  if (props.initTableData && props.initTableData.length >= 1) {
    state.tableRows = props.initTableData;
    updateInputConfRows();
  } else {
    addInputConf();
  }
};

const changeType = (val, row) => {
  if (val == 2) {
    row.password = "";
  }
};

const getData = () => {
  ruleFormRef.value && ruleFormRef.value.validate((valid) => {});
  let flag = true;
  let list = state.tableRows.map((item) => {
    if (
      item.ip == "" ||
      item.voucher_type === "" ||
      item.user_name == "" ||
      (item.voucher_type === 0 && item.password == "")
    ) {
      flag = false;
    }
    return {
      ip: item.ip,
      port: item.port,
      voucher_type: item.voucher_type,
      user_name: item.user_name,
      password: item.password,
    };
  });
  return {
    list,
    flag,
  };
};

watch(
  () => {
    return props.initTableData;
  },
  () => {
    initTable();
  },
  {
    immediate: true,
  }
);

defineExpose({
  getData,
  clearValidate,
});
</script>

<style lang="scss" scoped>
.rule-form {
  ::v-deep(.bg-table .el-form-item .el-form-item__error) {
    bottom: -13px;
  }
}
</style>
