<template>
  <el-dialog
    :model-value="modelValue"
    :title="isEdit ? '编辑设备' : '新增设备'"
    width="520px"
    align-center
    destroy-on-close
    class="device-form-dialog"
    @update:model-value="emit('update:modelValue', $event)"
    @closed="handleClosed"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="96px"
      label-position="right"
      class="device-form"
    >
      <el-form-item label="农机名称" prop="name">
        <el-input
          v-model="form.name"
          :placeholder="isEdit ? '' : '请输入农机'"
          maxlength="50"
        />
      </el-form-item>

      <el-form-item label="农机类型" prop="type">
        <el-select
          v-model="form.type"
          placeholder="请选择农机类型"
          style="width: 100%"
        >
          <el-option
            v-for="item in typeOptions"
            :key="item"
            :label="item"
            :value="item"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="农事类别" prop="categories">
        <el-select
          v-model="form.categories"
          multiple
          collapse-tags
          collapse-tags-tooltip
          :max-collapse-tags="3"
          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="location" required>
        <div class="field-block">
          <el-input
            v-if="isEdit || form.location"
            v-model="form.location"
            placeholder="请选择存放点位"
            readonly
          />
          <el-button class="btn-outline" @click="handleSelectLocation">
            {{ isEdit || form.location ? "修改点位" : "选择点位" }}
          </el-button>
        </div>
      </el-form-item>

      <el-form-item label="执行区域" prop="areaLabel" required>
        <div class="field-block">
          <div v-if="isEdit && form.areaLabel" class="area-preview">
            {{ form.areaLabel }}
          </div>
          <el-button class="btn-outline" @click="handleSelectArea">
            {{ isEdit ? "修改区域" : "选择区域" }}
          </el-button>
        </div>
      </el-form-item>

      <el-form-item label="负责人" prop="ownerName">
        <el-input
          v-model="form.ownerName"
          :placeholder="isEdit ? '' : '请输入姓名'"
          maxlength="20"
        />
      </el-form-item>

      <el-form-item label="手机号" prop="ownerPhone">
        <el-input
          v-model="form.ownerPhone"
          :placeholder="isEdit ? '' : '请输入手机号'"
          maxlength="11"
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="close">取消</el-button>
        <el-button type="primary" :loading="submitting" @click="handleSubmit">
          提交
        </el-button>
      </div>
    </template>
  </el-dialog>

  <SelectAreaDialog
    v-model="areaDialogVisible"
    :farm-id="101532"
    :selected-ids="form.selectedAreaIds"
    @confirm="handleAreaConfirm"
  />

  <SelectLocationDialog
    v-model="locationDialogVisible"
    :farm-id="101532"
    :location-wkt="form.locationWkt"
    @confirm="handleLocationConfirm"
  />
</template>

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

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false,
  },
  mode: {
    type: String,
    default: "add", // add | edit
  },
  data: {
    type: Object,
    default: null,
  },
});

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

const isEdit = computed(() => props.mode === "edit");
const formRef = ref();
const submitting = ref(false);
const areaDialogVisible = ref(false);
const locationDialogVisible = ref(false);

const typeOptions = ["肥水一体", "水肥一体", "植保无人机", "收割机", "播种机"];
const categoryOptions = ["类别一", "类别二", "类别三", "类别四", "类别五", "类别六", "类别七"];

const createEmptyForm = () => ({
  id: null,
  name: "",
  type: "",
  categories: [],
  location: "",
  locationWkt: "",
  areaLabel: "",
  selectedAreaIds: [],
  selectedAreas: [],
  ownerName: "",
  ownerPhone: "",
});

const form = reactive(createEmptyForm());

const rules = {
  name: [{ required: true, message: "请输入农机名称", trigger: "blur" }],
  type: [{ required: true, message: "请选择农机类型", trigger: "change" }],
  categories: [
    {
      type: "array",
      required: true,
      min: 1,
      message: "请选择农事类别",
      trigger: "change",
    },
  ],
  location: [
    {
      validator: (_rule, _value, callback) => {
        if (!form.location) callback(new Error("请选择存放点位"));
        else callback();
      },
      trigger: "change",
    },
  ],
  areaLabel: [
    {
      validator: (_rule, _value, callback) => {
        if (!form.selectedAreaIds?.length) callback(new Error("请选择执行区域"));
        else callback();
      },
      trigger: "change",
    },
  ],
  ownerName: [{ required: true, message: "请输入负责人", trigger: "blur" }],
  ownerPhone: [
    { required: true, message: "请输入手机号", trigger: "blur" },
    {
      pattern: /^1\d{10}$/,
      message: "请输入正确的手机号",
      trigger: "blur",
    },
  ],
};

const fillForm = (data) => {
  Object.assign(form, createEmptyForm(), {
    id: data?.id ?? null,
    name: data?.name || "",
    type: data?.type || "",
    categories: [...(data?.categories || [])],
    location: data?.location || "",
    locationWkt: data?.locationWkt || "",
    areaLabel: data?.areaLabel || "",
    selectedAreaIds: [...(data?.selectedAreaIds || [])],
    selectedAreas: [...(data?.selectedAreas || [])],
    ownerName: data?.ownerName || "",
    ownerPhone: data?.ownerPhone || "",
  });
};

watch(
  () => props.modelValue,
  (visible) => {
    if (!visible) return;
    if (isEdit.value && props.data) {
      fillForm(props.data);
    } else {
      Object.assign(form, createEmptyForm());
    }
  }
);

const close = () => emit("update:modelValue", false);

const handleClosed = () => {
  submitting.value = false;
  areaDialogVisible.value = false;
  locationDialogVisible.value = false;
  formRef.value?.resetFields?.();
  Object.assign(form, createEmptyForm());
};

const handleSelectLocation = () => {
  locationDialogVisible.value = true;
};

const handleLocationConfirm = (point) => {
  form.locationWkt = point.wkt;
  form.location = point.label;
  formRef.value?.validateField?.("location");
};

const handleSelectArea = () => {
  areaDialogVisible.value = true;
};

const handleAreaConfirm = ({ areas, ids, label }) => {
  form.selectedAreas = areas;
  form.selectedAreaIds = ids;
  form.areaLabel = label;
  formRef.value?.validateField?.("areaLabel");
};

const handleSubmit = async () => {
  await formRef.value?.validate?.(async (valid) => {
    if (!valid) return;
    submitting.value = true;
    try {
      const payload = {
        id: form.id,
        name: form.name,
        type: form.type,
        categories: [...form.categories],
        location: form.location,
        locationWkt: form.locationWkt,
        areaLabel: form.areaLabel,
        selectedAreaIds: [...form.selectedAreaIds],
        selectedAreas: [...form.selectedAreas],
        ownerName: form.ownerName,
        ownerPhone: form.ownerPhone,
      };
      emit("submit", { mode: props.mode, data: payload });
      ElMessage.success(isEdit.value ? "编辑成功" : "新增成功");
      close();
    } finally {
      submitting.value = false;
    }
  });
};
</script>

<style lang="scss" scoped>
.device-form {
  padding: 20px 24px 0 8px;
  border-top: 1px solid #E5E6EB;

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

.field-block {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  gap: 10px;
  width: 100%;
}

.btn-outline {
  height: 32px;
  padding: 0 16px;
  color: $base-color;
  background: #fff;
  border-color: $base-color;
  border-radius: 4px;

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

.area-preview {
  min-width: 148px;
  max-width: 100%;
  padding: 10px 12px;
  border: 1px solid #e5e5e5;
  border-radius: 2px;
  background: #f7f7f7;
  color: #666;
  font-size: 13px;
  line-height: 1.5;
  word-break: break-all;
}

.dialog-footer {
  display: flex;
  justify-content: center;
  gap: 16px;
  padding-bottom: 8px;
}
</style>
