<template>
  <el-form
    :model="state.form"
    ref="form_ref"
    :rules="state.rules"
    label-width="110px"
    :disabled="disabled"
    style="width: 100%">
    <el-form-item :label="methodLabel || '通知方式'" 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"
      :class="{
        'no-el-label': noElLabel,
      }">
      <el-form :model="state.form.lists" ref="table_form" :rules="state.tableRules" label-width="0" style="width: 100%">
        <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 || (ADD_NUM && 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,
  },
  noElLabel: {
    type: Boolean,
    default: true,
  },
  methodLabel: {
    type: String,
    default: "",
  },
  history: {
    type: Object,
    default: () => ({}),
  },
});
const form_ref = 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 = async (cb = null) => {
  let form_valid = await new Promise((resolve, reject) => {
    form_ref.value.validate((res) => resolve(res));
  });
  let table_form_valid = await new Promise((resolve, reject) => {
    table_form.value.validate((res) => resolve(res));
  });
  return form_valid && table_form_valid;
};
// 已经新增的数量记录
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 (ADD_NUM && 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;
};
watch(
  () => props.history,
  (n) => {
    let history = { ...n };
    getUserLists();
    state.form.method = history?.method || [];
    state.form.lists = history?.lists || [];
    // 如果没有默认下发用户则创建一条空数据
    if (state.form.lists.length == 0) {
      Add(0);
    }
    setTimeout(() => {
      form_ref.value.clearValidate();
    });
  },
  {
    deep: true,
    immediate: true,
  }
);
// 选择用户操作
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_ref,
  form: state.form,
});
</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 {
  :deep(.el-table thead th) {
    background-color: #f5f6f9;
  }
}
.no-el-label {
  :deep(.el-form-item__content) {
    margin-left: 0 !important;
  }
}
:deep(.el-form-item .el-form-item) {
  margin-bottom: 0 !important;
}
</style>
