<script setup lang="ts">
import { reactive, ref } from "vue";
import { getStationDetail, addStation, modifyStation } from "@/api/station";
import { ElMessage } from "element-plus";

const emit = defineEmits(["refresh"]);

const formRef = ref();
const dialogVisible = ref(false);
const dialogType = ref<"add" | "edit" | "view">("add");
const loading = ref(false);

const state = reactive({
  ruleForm: {
    id: null as number | null,
    stationId: "",
    stationName: "",
    address: "",
    stationStatus: "1",
    stationType: "1",
    parkingFee: "",
    parkingQrCode: "",
    parkingCouponMinAmount: 6.0,
    remark: "",
    pictures: [] as string[],
    stationLng: "",
    stationLat: ""
  },
  rules: {
    stationName: [{ required: true, message: "请输入站点名称", trigger: "blur" }],
    address: [{ required: true, message: "请输入站点地址", trigger: "blur" }]
  }
});

const resetForm = () => {
  state.ruleForm = {
    id: null,
    stationId: "",
    stationName: "",
    address: "",
    stationStatus: "1",
    stationType: "1",
    parkingFee: "",
    parkingQrCode: "",
    parkingCouponMinAmount: 6.0,
    remark: "",
    pictures: [],
    stationLng: "",
    stationLat: ""
  };
  formRef.value?.resetFields();
};

const open = async (type: "add" | "edit" | "view", row?: any) => {
  dialogType.value = type;
  resetForm();
  
  if (type !== "add" && row) {
    loading.value = true;
    try {
      const res = await getStationDetail(row.id);
      Object.assign(state.ruleForm, res);
      state.ruleForm.parkingCouponMinAmount = (res.parkingCouponMinAmount || 600) / 100;
    } catch (e) {
      ElMessage.error("加载站点详情失败");
    } finally {
      loading.value = false;
    }
  }
  
  dialogVisible.value = true;
};

const handleClose = () => {
  dialogVisible.value = false;
  resetForm();
};

const handleSubmit = async () => {
  const valid = await formRef.value?.validate().catch(() => false);
  if (!valid) return;
  
  loading.value = true;
  try {
    const payload = {
      ...state.ruleForm,
      parkingCouponMinAmount: Math.round(state.ruleForm.parkingCouponMinAmount * 100)
    };
    if (dialogType.value === "add") {
      await addStation(payload);
      ElMessage.success("新增成功");
    } else {
      await modifyStation(payload);
      ElMessage.success("修改成功");
    }
    handleClose();
    emit("refresh");
  } catch (e) {
    ElMessage.error("操作失败");
  } finally {
    loading.value = false;
  }
};

const isView = () => dialogType.value === "view";

const getTitle = () => {
  const map = { add: "新增站点", edit: "编辑站点", view: "站点详情" };
  return map[dialogType.value];
};

defineExpose({ open });
</script>

<template>
  <el-dialog
    v-model="dialogVisible"
    :title="getTitle()"
    width="700px"
    :close-on-click-modal="false"
    destroy-on-close
  >
    <el-form
      ref="formRef"
      :model="state.ruleForm"
      :rules="state.rules"
      label-width="120px"
      :disabled="isView()"
    >
      <el-form-item label="站点ID" prop="stationId">
        <el-input v-model="state.ruleForm.stationId" placeholder="请输入站点ID" />
      </el-form-item>
      <el-form-item label="站点名称" prop="stationName">
        <el-input v-model="state.ruleForm.stationName" placeholder="请输入站点名称" />
      </el-form-item>
      <el-form-item label="站点地址" prop="address">
        <el-input v-model="state.ruleForm.address" placeholder="请输入站点地址" />
      </el-form-item>
      <el-form-item label="站点状态" prop="stationStatus">
        <ext-d-select v-model="state.ruleForm.stationStatus" type="Station.status" placeholder="请选择站点状态" />
      </el-form-item>
      <el-form-item label="站点类型" prop="stationType">
        <ext-d-select v-model="state.ruleForm.stationType" type="Station.type" placeholder="请选择站点类型" />
      </el-form-item>
      <el-form-item label="停车券最低消费金额（元）" prop="parkingCouponMinAmount">
        <el-input-number v-model="state.ruleForm.parkingCouponMinAmount" :min="0" :precision="2" placeholder="默认6元" />
      </el-form-item>
      <el-form-item label="停车减免规则" prop="parkingFee">
        <el-input
          v-model="state.ruleForm.parkingFee"
          type="textarea"
          :rows="2"
          placeholder="洗车费用满10元减免1小时停车费"
        />
      </el-form-item>
      <el-form-item label="停车二维码文本" prop="parkingQrCode">
        <el-input
          v-model="state.ruleForm.parkingQrCode"
          type="textarea"
          :rows="2"
          placeholder="停车费减免二维码文本"
        />
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input
          v-model="state.ruleForm.remark"
          type="textarea"
          :rows="2"
          placeholder="请输入备注"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button v-if="!isView()" :loading="loading" type="primary" @click="handleSubmit">
          确定
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<style scoped lang="scss">
.el-select {
  width: 100%;
}
</style>
