<template>
  <el-form :model="state.form" ref="form" :rules="state.rules" label-width="80px" :disabled="disabled">
    <el-form-item label="通知方式" prop="method">
      <el-checkbox-group v-model="state.form.method">
        <el-checkbox v-for="(value, key) in METHODS" :key="key" :label="key">
          {{ value }}
        </el-checkbox>
      </el-checkbox-group>
    </el-form-item>
    <el-form-item label="" prop="lists" class="user-table bg-scroll">
      <el-form :model="state.form.lists" ref="table_form" :rules="table_rules" label-width="0">
        <el-table :data="state.form.lists" stripe border>
          <el-table-column type="index" label="序号" width="60px"> </el-table-column>
          <el-table-column
            v-for="header in headers"
            :prop="header.prop"
            :key="header.prop"
            :label="header.label"
            :width="header.width">
            <template #default="{ $index }">
              <div v-if="header.prop == 'user_id'">
                <el-form-item :prop="`[${$index}].user_id`" :rules="state.tableRules.user_id">
                  <el-select
                    v-model="state.form.lists[$index].user_id"
                    placeholder="请选择"
                    filterable
                    @change="($event) => chooseUser($event, $index)">
                    <el-option
                      v-for="item in userOptions($index)"
                      :key="item.user_id"
                      :label="item.user_id"
                      :value="item.user_id">
                    </el-option>
                  </el-select>
                </el-form-item>
              </div>
              <div v-else>
                <el-form-item :prop="`[${$index}].${header.prop}`" :rules="state.tableRules[header.prop]">
                  <el-input v-model="state.form.lists[$index][header.prop]" placeholder="请输入"></el-input>
                </el-form-item>
              </div>
            </template>
          </el-table-column>

          <el-table-column prop="" label="操作" width="125px">
            <template #default="{ $index }">
              <div class="table-operation">
                <el-button
                  link
                  type="primary"
                  @click="Add($index)"
                  :disabled="userLists.length <= state.form.lists.length || addTrue >= ADD_NUM">
                  新增
                </el-button>
                <span class="line"></span>
                <el-button link type="primary" @click="Remove($index)" :disabled="state.form.lists.length == 1">
                  删除
                </el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
    </el-form-item>
  </el-form>
</template>

<script setup>
import { reactive, watch, ref, computed } from "vue";
import { METHODS, ADD_NUM } from "./env";
const props = defineProps({
  disabled: {
    type: Boolean,
    default: false,
  },
});
const form = ref(null);
// 表单数据
const state = reactive({
  form: {
    method: [],
    lists: [],
  },
  rules: {
    method: [
      {
        type: "array",
        required: true,
        message: "请至少选择一个通知方式",
        trigger: "change",
      },
    ],
  },
  tableRules: {
    user_id: [{ required: true, message: "请选择", trigger: "change" }],
    user_name: [{ required: true, message: "请输入", trigger: "blur" }],
    phone: [{ required: true, message: "请输入", trigger: "blur" }],
  },
});
// 已选中的用户id列表
const selectedUser = computed(() => {
  return state.form.lists.map((e) => e.user_id) || [];
});
// 表头
const headers = [
  {
    prop: "user_id",
    label: "账号",
  },
  {
    prop: "user_name",
    label: "姓名",
  },
  {
    prop: "phone",
    label: "联系方式",
  },
];
const table_form = ref(null);
// 立即下发
const Submit = (cb = null) => {
  form.value.validate((valid) => {
    if (valid) {
      table_form.value.validate((t_v) => {
        if (t_v) {
          cb && cb(state.form);
        } else {
          return false;
        }
      });
    } else {
      return false;
    }
  });
};
// 已经新增的数量记录
const addTrue = ref(0);
// 获取远程用户列表
const userLists = ref([]);
const getUserLists = () => {
  userLists.value = [
    {
      user_id: 1,
      user_name: 11,
      phone: 13000000001,
    },
    {
      user_id: 2,
      user_name: 22,
      phone: 13000000002,
    },
    {
      user_id: 3,
      user_name: 33,
      phone: 13000000003,
    },
    {
      user_id: 4,
      user_name: 44,
      phone: 13000000004,
    },
    {
      user_id: 5,
      user_name: 55,
      phone: 13000000005,
    },
    {
      user_id: 6,
      user_name: 66,
      phone: 13000000006,
    },
    {
      user_id: 7,
      user_name: 77,
      phone: 13000000007,
    },
  ];
};
// 格式化处理用户下拉列表，去除已经选择的用户，并将当前选中的也显示到列表中
const userOptions = computed(() => {
  return (index) => {
    let user_id = state.form.lists[index].user_id;
    let s_u_ids = [...selectedUser.value];
    if (user_id) {
      let i = s_u_ids.findIndex((e) => e == user_id);
      s_u_ids.splice(i, 1);
    }
    return userLists.value.filter((e) => !s_u_ids.includes(e.user_id));
  };
});
// 表格新增
const Add = (index) => {
  // 新增上限
  if (addTrue.value >= ADD_NUM) return;
  state.form.lists.splice(index + 1, 0, {
    user_id: "",
    user_name: "",
    phone: "",
  });
  addTrue.value += 1;
};
// 表格删除
const Remove = (index) => {
  state.form.lists.splice(index, 1);
  addTrue.value -= 1;
};
// 初始化加载基础数据和获取用户下拉列表
const init = (history) => {
  getUserLists();
  state.form.method = history?.method || [];
  state.form.lists = history?.lists || [];
  // 如果没有默认下发用户则创建一条空数据
  if (state.form.lists.length == 0) {
    Add(0);
  }
  setTimeout(() => {
    form.value.clearValidate();
  });
};
// 选择用户操作
const chooseUser = ($event, index) => {
  let user = userLists.value.find((e) => e.user_id == state.form.lists[index].user_id);
  state.form.lists[index].user_name = user.user_name;
  state.form.lists[index].phone = user.phone;
};
defineExpose({
  Submit,
  form,
  init,
});
watch(
  () => state.form.lists,
  (n) => {
    console.log(n);
  },
  { deep: true }
);
</script>

<style lang="scss" scoped>
.table-operation {
  display: flex;
  align-items: center;
  .line {
    width: 1px;
    height: 14px;
    background-color: #c1c7d7;
    margin: 0 16px;
    display: inline-block;
  }
}
.user-table {
  max-height: 345px;
  :deep(.el-form-item__content) {
    margin-left: 0 !important;
    .el-table thead th {
      background-color: #f5f6f9;
    }
  }
}
</style>
