<template>
  <el-form ref="ruleFormRef" class="ruleForm" :model="tableRows" :size="formSize" :rules="formRules">
    <bg-table-pro showIndex :headers="headers" :data="tableRows" ref="input-table" :border="true" :stripe="false">
      <template v-slot:account="{ row, index }">
        <el-form-item :prop="`[${index}].account`" :rules="formRules.account" style="width: 100%">
          <el-select
            v-model="row.account"
            placeholder="请选择帐号"
            style="width: 100%"
            @change="changeAccount(row)"
            :disabled="disabled">
            <el-option
              v-for="(item, index) in userLists"
              :key="'userItem' + index"
              :disabled="item.disabled"
              :label="item.account"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
      </template>
      <template v-slot:name="{ row, index }">
        <el-form-item :prop="`[${index}].name`" :rules="formRules.name" style="width: 100%">
          <el-input @change="changeName" placeholder="请输入姓名" :disabled="disabled" v-model.trim="row.name" />
        </el-form-item>
      </template>
      <template v-slot:mobile="{ row, index }">
        <el-form-item :prop="`[${index}].mobile`" :rules="formRules.mobile" style="width: 100%">
          <el-input
            @change="changeMobile"
            placeholder="请输入联系方式"
            :disabled="disabled"
            v-model.trim="row.mobile" />
        </el-form-item>
      </template>

      <template v-slot:action="{ row, index }">
        <bg-table-btn
          :disabled="disabled || !canAdd"
          :click="
            () => {
              addParam(index);
            }
          "
          >增加</bg-table-btn
        >
        <bg-table-btn
          :disabled="disabled"
          :click="
            () => {
              removeParam(row, index);
            }
          ">
          删除
        </bg-table-btn>
      </template>
    </bg-table-pro>
  </el-form>
</template>

<script setup>
import { reactive, toRefs, onBeforeMount, onMounted, ref, getCurrentInstance, watch, computed } from "vue";
import { v4 as uuidv4 } from "uuid";
import { validatePhone } from "@/services/rules.js";
const props = defineProps({
  data: {
    type: Array,
    default: () => [],
  },
  disabled: {
    type: Boolean,
    default: false,
  },
});

const emit = defineEmits(["change"]);
const formSize = ref("default");
const ruleFormRef = ref(null);

const formRules = reactive({
  name: [
    {
      required: true,
      message: "请输入键",
      trigger: "blur",
    },
    {
      max: 50,
      message: "最多50个字符",
      trigger: "blur",
    },
  ],
  account: [
    {
      required: true,
      message: "请选择帐号",
      trigger: "change",
    },
  ],
  mobile: [
    {
      required: true,
      message: "请输入联系方式",
      trigger: "blur",
    },
    { validator: validatePhone, trigger: "blur" },
  ],
});

const headers = reactive([
  {
    label: "帐号",
    prop: "account",
    required: true,
  },
  {
    label: "姓名",
    prop: "name",
    required: true,
  },
  {
    label: "联系方式",
    prop: "mobile",
    required: true,
  },
  {
    label: "操作",
    prop: "action",
    width: 120,
  },
]);

const state = reactive({
  tableRows: [],
  userLists: [
    {
      account: "admin",
      id: 1,
      name: "张一",
      mobile: "13111111111",
    },
    {
      account: "ys-admin",
      id: 2,
      name: "张二",
      mobile: "13222222222",
    },
    {
      account: "yf-user",
      id: 3,
      name: "张三",
      mobile: "13333333333",
    },
    {
      account: "putong",
      id: 4,
      name: "张四",
      mobile: "13444444444",
    },
  ],
});

watch(
  () => state.tableRows,
  (n, o) => {
    let list = state.tableRows.map((e) => {
      return e.account;
    });
    state.userLists.forEach((e) => {
      if (list.indexOf(e.id) > -1) {
        e.disabled = true;
      } else {
        e.disabled = false;
      }
    });
  },
  {
    deep: true,
  }
);

const canAdd = computed(() => {
  return state.tableRows.length >= 5 ? false : true;
}); // 最多五条数据，控制下新增按钮的禁用

onBeforeMount(() => {
  initTable();
});

var initTable = () => {
  if (props.data && props.data.length >= 1) {
    state.tableRows = props.data;
  } else {
    state.tableRows = [];
    addParam(0);
  }
};

var createRow = () => {
  return {
    id: uuidv4(),
    account: "",
    name: "",
    mobile: "",
  };
};

var addParam = (index) => {
  state.tableRows.splice(index + 1, 0, createRow());
};

var removeParam = (row, index) => {
  state.tableRows.splice(index, 1);
  if (state.tableRows.length === 0) {
    addParam(0);
  }
};

const changeAccount = (row) => {
  state.userLists.forEach((e) => {
    if (e.id == row.account) {
      row.name = e.name;
      row.mobile = e.mobile;
    }
  });
  emit("change", {
    type: "account",
    data: state.tableRows,
  });
};

const changeName = () => {
  emit("change", {
    type: "name",
    data: state.tableRows,
  });
};

const changeMobile = () => {
  emit("change", {
    type: "mobile",
    data: state.tableRows,
  });
};

var getInputData = () => {
  let lastData = [];
  let tempObj = {};
  state.tableRows.forEach((e) => {
    tempObj[e.name] = e;
  });
  for (const key in tempObj) {
    if (key && tempObj[key].value) {
      lastData.push(tempObj[key]);
    }
  }
  return lastData;
};

const { tableRows, userLists } = toRefs(state);

//暴露获取数据方法
defineExpose({
  getInputData,
  initTable,
});
</script>

<style scoped></style>
