<template>
  <div v-if="modelValue" class="add-subject-panel">
    <div class="panel-title">{{ isEdit ? "编辑主体信息" : "新增主体" }}</div>

    <div class="form-box">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="80px" class="subject-form">
        <el-form-item label="类型：" prop="type">
          <el-select v-model="form.type" placeholder="权属人/区域服务人" clearable style="width: 100%">
            <el-option
              v-for="item in typeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="姓名：" prop="name">
          <el-input v-model="form.name" placeholder="请输入姓名" clearable maxlength="20" />
        </el-form-item>

        <el-form-item label="手机号：" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入手机号" clearable maxlength="11" />
        </el-form-item>

        <el-form-item label="区域面积：" prop="areaSize">
          <el-input v-model="form.areaSize" placeholder="自动填入" readonly />
        </el-form-item>

        <el-form-item label="执行类别：" prop="categories">
          <el-select
            v-model="form.categories"
            multiple
            collapse-tags
            collapse-tags-tooltip
            placeholder="执行类别"
            style="width: 100%"
          >
            <el-option
              v-for="item in categoryOptions"
              :key="item"
              :label="item"
              :value="item"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="负责农机：" prop="machines">
          <el-select
            v-model="form.machines"
            multiple
            collapse-tags
            collapse-tags-tooltip
            placeholder="请选择农机"
            style="width: 100%"
          >
            <el-option
              v-for="item in machineOptions"
              :key="item"
              :label="item"
              :value="item"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="常驻地址：" prop="location">
          <template v-if="isEdit">
            <el-input v-model="form.location" placeholder="请选择点位" readonly />
          </template>
          <el-button class="btn-select-point" @click="handleSelectPoint">
            {{ isEdit ? "修改点位" : "选择点位" }}
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <div class="panel-footer">
      <el-button class="btn-cancel" @click="handleCancel">取消</el-button>
      <el-button class="btn-save" type="warning" :loading="saving" @click="handleSave">保存</el-button>
    </div>
  </div>
</template>

<script setup>
import { computed, reactive, ref, watch } from "vue";
import { ElMessage } from "element-plus";

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false,
  },
  /** add | edit */
  mode: {
    type: String,
    default: "add",
  },
  /** 编辑时回显的人员数据 */
  person: {
    type: Object,
    default: null,
  },
});

const emit = defineEmits(["update:modelValue", "save", "cancel"]);

const formRef = ref(null);
const saving = ref(false);
const isEdit = computed(() => props.mode === "edit");

const typeOptions = [
  { label: "权属人", value: "owner" },
  { label: "区域服务人员", value: "staff" },
];

const categoryOptions = ["类别一", "类别二", "类别三"];
const machineOptions = ["设备一", "设备二", "设备三", "农机一"];

const createForm = () => ({
  id: null,
  type: "",
  name: "",
  phone: "",
  areaSize: "",
  categories: [],
  machines: [],
  location: "",
  locationWkt: "",
});

const form = reactive(createForm());

const rules = {
  type: [{ required: true, message: "请选择类型", trigger: "change" }],
  name: [{ required: true, message: "请输入姓名", trigger: "blur" }],
  phone: [
    { required: true, message: "请输入手机号", trigger: "blur" },
    { pattern: /^1\d{10}$/, message: "手机号格式不正确", trigger: "blur" },
  ],
};

/** 将「a、b、c」转成数组并去重 */
const splitTags = (val) => {
  if (Array.isArray(val)) return [...val];
  if (!val || typeof val !== "string") return [];
  return [...new Set(val.split(/[、,，]/).map((s) => s.trim()).filter(Boolean))];
};

const fillForm = () => {
  if (isEdit.value && props.person) {
    const p = props.person;
    Object.assign(form, {
      id: p.id ?? null,
      type: p.role || p.type || "",
      name: p.name || "",
      phone: p.phone || "",
      areaSize: p.areaSize || "",
      categories: splitTags(p.categories),
      machines: splitTags(p.machines),
      location: p.location || "",
      locationWkt: p.locationWkt || "",
    });
  } else {
    Object.assign(form, createForm());
  }
  formRef.value?.clearValidate?.();
};

watch(
  () => [props.modelValue, props.mode, props.person],
  ([visible]) => {
    if (visible) fillForm();
  }
);

const handleSelectPoint = () => {
  ElMessage.info(isEdit.value ? "修改点位功能待接入" : "选择点位功能待接入");
};

const handleCancel = () => {
  emit("update:modelValue", false);
  emit("cancel");
};

const handleSave = async () => {
  if (!formRef.value) return;
  try {
    await formRef.value.validate();
  } catch {
    return;
  }

  saving.value = true;
  try {
    emit("save", {
      mode: props.mode,
      ...form,
      categories: [...form.categories],
      machines: [...form.machines],
    });
    emit("update:modelValue", false);
  } finally {
    saving.value = false;
  }
};
</script>

<style lang="scss" scoped>
$primary: $warning-color;

.add-subject-panel {
  position: absolute;
  top: 25px;
  right: 20px;
  bottom: 25px;
  z-index: 11;
  display: flex;
  flex-direction: column;
  width: 380px;
  box-sizing: border-box;
  padding: 20px;
  background: #fff;
  border-radius: 10px;

  .panel-title {
    flex-shrink: 0;
    margin-bottom: 16px;
    font-size: 18px;
    font-weight: 500;
    color: #060606;
    line-height: 1.2;
  }

  .form-box {
    flex-shrink: 0;
    padding: 12px;
    border: 0.5px solid #e5e6eb;
    border-radius: 8px;
  }
}

.subject-form {
  :deep(.el-form-item) {
    margin-bottom: 16px;
  }

  :deep(.el-form-item__label) {
    color: #333;
    font-size: 13px;
    padding-right: 4px;
  }

  :deep(.el-input__wrapper),
  :deep(.el-select__wrapper) {
    border-radius: 4px;
  }

  .btn-select-point {
    margin-top: 0;
    padding: 5px 16px;
    color: $primary;
    background: #fff;
    border: 1px solid $primary;
    border-radius: 4px;

    &:hover,
    &:focus {
      color: #fff;
      background: $primary;
      border-color: $primary;
    }
  }
}

.panel-footer {
  flex-shrink: 0;
  margin-top: auto;
  display: flex;
  justify-content: flex-end;
  gap: 16px;
  padding-top: 20px;

  .btn-cancel {
    min-width: 72px;
    color: #333;
    background: #f3f3f3;
    border: none;

    &:hover,
    &:focus {
      color: #333;
      background: #e8e8e8;
      border: none;
    }
  }

  .btn-save {
    min-width: 72px;
    border: none;
    background: $primary;
  }
}
</style>
