<template>
  <view class="plate-page">
    <uv-navbar title="我的车辆" bgColor="#C6171E" leftIconColor="#FFFFFF" :titleStyle="{ color: '#FFFFFF' }" :autoBack="true" :placeholder="true"></uv-navbar>

    <view class="plate-input-section">
      <view class="section-header">
        <text class="section-title">添加车辆</text>
      </view>
      <view class="plate-input-hint">
        <text>添加车牌后部分站点可享停车减免权益</text>
      </view>

      <!-- 车牌输入框 -->
      <view class="plate-input-container">
        <!-- 省份 -->
        <view class="plate-item plate-region"
              :class="{ 'plate-focus': cursorSlot === 0 }"
              @click="toggleRegionPicker">
          <text>{{ plateChars[0] || '' }}</text>
        </view>

        <!-- 城市 + 5位字母数字 = 6个字符区 + 分隔符 + 闪电位 -->
        <view class="plate-item"
              :class="{ 'plate-focus': cursorSlot === 1 }"
              @click="focusSlot(1)">
          <text>{{ plateChars[1] || '' }}</text>
        </view>

        <view class="plate-divider"><text>·</text></view>

        <view v-for="i in 5" :key="i"
              class="plate-item"
              :class="{ 'plate-focus': cursorSlot === (i + 1) }"
              @click="focusSlot(i + 1)">
          <text>{{ plateChars[i + 1] || '' }}</text>
        </view>

        <!-- 第8位：新能源闪电标识位 -->
        <view class="plate-item new-energy"
              :class="{ 'plate-focus': cursorSlot === 7 }"
              @click="focusSlot(7)">
          <text v-if="plateChars[7]" class="energy-char">{{ plateChars[7] }}</text>
          <image v-else class="energy-icon-inside" src="data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAyNCAyNCIgZmlsbD0iIzUyQzQxQSI+PHBhdGggZD0iTTEzIDJMMyAxNGg2bC0xIDggMTAtMTJoLTZsMS04eiIvPjwvc3ZnPg==" mode="aspectFit" />
        </view>
      </view>

      <!-- 隐藏输入框：统一接管键盘输入 -->
      <input class="ghost-input"
             v-model="restStr"
             :focus="inputFocused"
             :maxlength="7"
             adjust-position
             @input="onRestInput"
             @focus="onRestFocus"
             @blur="onRestBlur"/>

      <view class="save-btn-container">
        <uv-button type="primary" color="#C6171E" shape="circle" :disabled="!isPlateValid" @click="savePlate">保存</uv-button>
      </view>

      <!-- 地区选择器 -->
      <view v-if="showRegionPicker" class="region-picker-mask" @click="toggleRegionPicker">
        <view class="region-picker-container" @click.stop>
          <view class="region-picker-header">
            <text class="region-picker-title">选择省份</text>
            <view class="region-picker-close" @click="toggleRegionPicker">
              <text>完成</text>
            </view>
          </view>
          <view class="region-grid">
            <view v-for="region in regions" :key="region"
                  class="region-item"
                  :class="{ 'region-selected': plateChars[0] === region }"
                  @click="selectRegion(region)">
              <text>{{ region }}</text>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 已添加车辆列表 -->
    <view class="car-list-section">
      <view class="section-header">
        <text class="section-title">已添加车辆</text>
        <text class="section-count" v-if="carList.length > 0">{{ carList.length }}辆</text>
      </view>

      <view v-if="carList.length === 0" class="empty-state">
        <image class="empty-icon-svg" src="data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSI2NCIgaGVpZ2h0PSI2NCIgdmlld0JveD0iMCAwIDY0IDY0IiBmaWxsPSJub25lIj48cmVjdCB4PSIxMCIgeT0iMjYiIHdpZHRoPSI0NCIgaGVpZ2h0PSIyMCIgcng9IjQiIHN0cm9rZT0iIzk5OSIgc3Ryb2tlLXdpZHRoPSIyLjUiLz48cmVjdCB4PSIxNiIgeT0iMTYiIHdpZHRoPSIzMiIgaGVpZ2h0PSIxNCIgcng9IjYiIHN0cm9rZT0iIzk5OSIgc3Ryb2tlLXdpZHRoPSIyLjUiLz48Y2lyY2xlIGN4PSIyMiIgY3k9IjQ4IiByPSI2IiBzdHJva2U9IiM5OTkiIHN0cm9rZS13aWR0aD0iMi41Ii8+PGNpcmNsZSBjeD0iNDIiIGN5PSI0OCIgcj0iNiIgc3Ryb2tlPSIjOTk5IiBzdHJva2Utd2lkdGg9IjIuNSIvPjxsaW5lIHgxPSIxMCIgeTE9IjI4IiB4Mj0iNiIgeTI9IjI4IiBzdHJva2U9IiM5OTkiIHN0cm9rZS13aWR0aD0iMi41IiBzdHJva2UtbGluZWNhcD0icm91bmQiLz48bGluZSB4MT0iNTQiIHkxPSIyOCIgeDI9IjU4IiB5Mj0iMjgiIHN0cm9rZT0iIzk5OSIgc3Ryb2tlLXdpZHRoPSIyLjUiIHN0cm9rZS1saW5lY2FwPSJyb3VuZCIvPjwvc3ZnPg==" mode="aspectFit" />
        <text class="empty-title">暂无绑定车辆</text>
        <text class="empty-hint">在上方输入车牌号开始绑定</text>
      </view>

      <view v-else>
        <view v-for="(car, index) in carList" :key="car.id" class="car-item" :class="{ 'car-item-last': index === carList.length - 1 }">
          <view class="car-info">
            <view class="car-plate-row">
              <text class="car-plate">{{ car.plateNo }}</text>
              <view v-if="car.isDefault" class="default-tag"><text>默认</text></view>
            </view>
          </view>
          <view class="car-actions">
            <view v-if="!car.isDefault" class="action-btn set-default-btn" @click="handleSetDefault(car)"><text>设为默认</text></view>
            <view class="action-btn delete-btn" @click="handleDelete(car)"><text>删除</text></view>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import {onLoad, onShow} from "@dcloudio/uni-app";
import {ref, computed, nextTick} from "vue";
import {body, get} from "@/utils/https";

const plateChars = ref(['粤', '', '', '', '', '', '', '']);
const restStr = ref('');
const cursorSlot = ref(1);
const inputFocused = ref(false);
const showRegionPicker = ref(false);
const carList = ref([]);

const regions = ['京', '津', '渝', '沪', '冀', '晋', '辽', '吉', '黑', '苏', '浙', '皖', '闽', '赣', '鲁', '豫', '鄂', '湘', '粤', '琼', '川', '贵', '云', '陕', '甘', '青', '蒙', '桂', '宁', '新', '藏', '使', '领', '警', '学', '港', '澳'];

const filledCount = computed(() => {
  return plateChars.value.filter(c => c !== '').length;
});

const isPlateValid = computed(() => {
  return filledCount.value >= 7;
});

const syncPlateFromRest = (str) => {
  const s = str || restStr.value;
  for (let i = 1; i <= 7; i++) {
    plateChars.value[i] = s[i - 1] || '';
  }
  cursorSlot.value = Math.min(s.length + 1, 7);
};

const onRestInput = () => {
  restStr.value = restStr.value.toUpperCase();
  syncPlateFromRest(restStr.value);
};

const focusSlot = (slot) => {
  cursorSlot.value = slot;
  inputFocused.value = true;
};

const onRestFocus = () => {
  inputFocused.value = true;
};

const onRestBlur = () => {
  inputFocused.value = false;
};

const toggleRegionPicker = () => {
  showRegionPicker.value = !showRegionPicker.value;
};

const selectRegion = (region) => {
  plateChars.value[0] = region;
  toggleRegionPicker();
  cursorSlot.value = 1;
  nextTick(() => {
    inputFocused.value = true;
  });
};

const savePlate = () => {
  const plateNo = plateChars.value[0] + restStr.value;
  if (plateNo.length < 7) {
    uni.showToast({ title: '请输入完整车牌号', icon: 'none' });
    return;
  }

  uni.showLoading({ title: "保存中" });
  body(`/cars/save`, { plateNo }).then((data) => {
    uni.hideLoading();
    if (data && data.isNew === false) {
      uni.showToast({ icon: "none", title: "车牌已存在，已设为默认" });
    } else {
      uni.showToast({ icon: "success", title: "保存成功" });
    }
    plateChars.value = ['粤', '', '', '', '', '', '', ''];
    restStr.value = '';
    cursorSlot.value = 1;
    fetchCarList();
  }).catch(() => {
    uni.hideLoading();
  });
};

const fetchCarList = () => {
  get(`/cars/list`).then((data) => {
    carList.value = data || [];
    const defaultCar = carList.value.find(c => c.isDefault);
    if (defaultCar && getApp().globalData.user) {
      getApp().globalData.user.defaultPlateNo = defaultCar.plateNo;
    }
  }).catch(() => {});
};

const handleSetDefault = (car) => {
  uni.showLoading({ title: "设置中" });
  body(`/cars/setDefault/${car.id}`).then(() => {
    uni.hideLoading();
    uni.showToast({ icon: "success", title: "已设为默认" });
    fetchCarList();
  }).catch(() => uni.hideLoading());
};

const handleDelete = (car) => {
  uni.showModal({
    title: '确认删除',
    content: `确定要删除车辆 ${car.plateNo} 吗？`,
    success: (res) => {
      if (res.confirm) {
        uni.showLoading({ title: "删除中" });
        body(`/cars/delete/${car.id}`).then(() => {
          uni.hideLoading();
          uni.showToast({ icon: "success", title: "已删除" });
          fetchCarList();
        }).catch(() => uni.hideLoading());
      }
    }
  });
};

onLoad(() => fetchCarList());
onShow(() => fetchCarList());
</script>

<style lang="scss" scoped>
.plate-page {
  background-color: $uni-bg-color-page;
  min-height: 100vh;
  box-sizing: border-box;
  padding-bottom: 60rpx;
}

// Section shared
.section-header {
  display: flex;
  align-items: baseline;
  justify-content: space-between;
  margin-bottom: 12rpx;
}

.section-title {
  font-size: 28rpx;
  font-weight: 600;
  color: $uni-text-color;
}

.section-count {
  font-size: 24rpx;
  color: $uni-text-color-hint;
}

.plate-input-section {
  background-color: $uni-bg-color-card;
  padding: 28rpx;
  box-sizing: border-box;
  margin-bottom: 20rpx;
  border-radius: 24rpx;
}

.plate-input-hint {
  margin-bottom: 28rpx;
}

.plate-input-hint text {
  font-size: 24rpx;
  color: $uni-text-color-hint;
  line-height: 1.5;
}

.plate-input-container {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 24rpx;
  gap: 8rpx;
}

.plate-item {
  width: 68rpx;
  height: 88rpx;
  border: 2rpx solid $uni-border-color;
  border-radius: 12rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 34rpx;
  font-weight: 600;
  color: $uni-text-color;
  background-color: $uni-bg-color-card;
  box-sizing: border-box;
  transition: border-color 0.15s ease, box-shadow 0.15s ease;
}

.plate-item.plate-focus {
  border-color: $uni-color-primary;
  box-shadow: 0 0 0 4rpx rgba(198, 23, 30, 0.12);
  z-index: 1;
}

.plate-item.new-energy {
  border-color: #52C41A;
  background-color: rgba(82, 196, 26, 0.06);
  position: relative;
}

.plate-item.new-energy.plate-focus {
  border-color: #52C41A;
  box-shadow: 0 0 0 4rpx rgba(82, 196, 26, 0.16);
}

.energy-char {
  position: relative;
  z-index: 1;
}

.energy-icon-inside {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 48rpx;
  height: 48rpx;
  pointer-events: none;
}

.plate-region {
  background-color: $uni-bg-color-page;
}

.plate-divider {
  width: 20rpx;
  height: 88rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 28rpx;
  color: $uni-text-color-hint;
}

// Hidden input capturing all keyboard input
.ghost-input {
  position: fixed;
  top: -200rpx;
  left: -200rpx;
  width: 1rpx;
  height: 1rpx;
  opacity: 0;
}

.save-btn-container {
  margin-top: 8rpx;
}

.save-btn-container :deep(.uv-button) {
  height: 80rpx;
  font-size: 30rpx;
  border-radius: 40rpx;
}

.save-btn-container :deep(.uv-button--disabled) {
  background-color: $uni-border-color;
  color: $uni-text-color-hint;
}

// Region picker
.region-picker-mask {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(26, 26, 26, 0.45);
  z-index: 1000;
}

.region-picker-container {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: $uni-bg-color-card;
  border-radius: 24rpx 24rpx 0 0;
  padding: 24rpx 20rpx;
  padding-bottom: calc(24rpx + env(safe-area-inset-bottom));
  box-sizing: border-box;
  box-shadow: 0 -4rpx 20rpx rgba(0, 0, 0, 0.08);
  height: 46vh;
  overflow-y: auto;
}

.region-picker-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 16rpx;
  padding: 0 8rpx;
}

.region-picker-title {
  font-size: 30rpx;
  font-weight: 600;
  color: $uni-text-color;
}

.region-picker-close text {
  font-size: 28rpx;
  color: $uni-color-primary;
}

.region-grid {
  display: flex;
  flex-wrap: wrap;
  gap: 12rpx;
  justify-content: flex-start;
}

.region-item {
  width: 88rpx;
  height: 72rpx;
  background-color: $uni-bg-color-page;
  border-radius: 12rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 36rpx;
  font-weight: 600;
  color: $uni-text-color;
  transition: all 0.15s ease;
  flex-shrink: 0;
}

.region-item.region-selected {
  background-color: $uni-color-primary;
  color: #FFFFFF;
}

.region-item:active {
  background-color: $uni-color-primary;
  color: #FFFFFF;
  transform: scale(0.95);
}

// Car list
.car-list-section {
  background-color: $uni-bg-color-card;
  padding: 28rpx;
  box-sizing: border-box;
  border-radius: 24rpx;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 48rpx 0 32rpx;
}

.empty-icon-svg {
  width: 104rpx;
  height: 104rpx;
  margin-bottom: 20rpx;
  opacity: 0.4;
}

.empty-title {
  font-size: 28rpx;
  font-weight: 600;
  color: $uni-text-color;
  margin-bottom: 8rpx;
}

.empty-hint {
  font-size: 24rpx;
  color: $uni-text-color-hint;
}

.car-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 24rpx 0;
  border-bottom: 1rpx solid $uni-border-color-light;

  &:last-child, &.car-item-last {
    border-bottom: none;
  }
}

.car-info {
  flex: 1;
  min-width: 0;
}

.car-plate-row {
  display: flex;
  align-items: center;
  gap: 12rpx;
}

.car-plate {
  font-size: 28rpx;
  font-weight: 600;
  color: $uni-text-color;
  letter-spacing: 1rpx;
}

.default-tag {
  background-color: rgba(82, 196, 26, 0.1);
  border-radius: 6rpx;
  padding: 2rpx 10rpx;
  flex-shrink: 0;
}

.default-tag text {
  font-size: 20rpx;
  font-weight: 500;
  color: #52C41A;
}

.car-actions {
  display: flex;
  align-items: center;
  gap: 12rpx;
  flex-shrink: 0;
  margin-left: 16rpx;
}

.action-btn {
  padding: 8rpx 20rpx;
  border-radius: 32rpx;
  font-size: 24rpx;
  font-weight: 500;
  display: flex;
  align-items: center;
  justify-content: center;
}

.set-default-btn {
  background-color: rgba($uni-color-primary, 0.08);
  color: $uni-color-primary;
}

.delete-btn {
  background-color: rgba(#F44336, 0.08);
  color: #F44336;
}

.action-btn:active {
  opacity: 0.6;
}
</style>
