<template>
  <view :style="themeStyles.container.value">
    <!-- 标题 -->
    <FlexRow v-if="props.title" :padding="[ 8, 0 ]" justify="space-between" align="center">
      <text :style="themeStyles.title.value">{{ props.title }}</text>
    </FlexRow>
    <FlexRow v-else justify="center" :padding="[ 6, 12 ]">
      <Button 
        type="text" 
        :innerStyle="{ width: '100%' }"
        :pressedColor="keyPressedColor"
        icon="arrow-down" 
        @click="onCancel" 
      />
    </FlexRow>
    <!-- 新能源选择区域 -->
    <FlexRow justify="space-between" :padding="[0, 20]" align="center">
      <FlexRow center>
        <RadioGroup v-model="isNewPlate">
          <Radio :name="false" text="普通车牌" />
          <Radio :name="true"  text="新能源车牌" />
        </RadioGroup>
      </FlexRow>
      <FlexRow center>
        <Button v-if="showDeleteButton" type="danger" size="small" shape="round" plain @click="onDelete">{{deleteButtonText}}</Button>
        <Width :size="10" />
        <Button v-if="showFinishButton" type="primary" size="small" shape="round" plain @click="() => onFinish()">{{finishButtonText}}</Button>
      </FlexRow>
    </FlexRow>
    <!-- 输入框区域 -->
    <FlexRow center :padding="20">
      <InputBox :text="currentText" :selfIndex="0" :activeIndex="currentText.length" />
      <InputBox :text="currentText" :selfIndex="1" :activeIndex="currentText.length" />
      <view :style="themeStyles.dot.value" />
      <InputBox :text="currentText" :selfIndex="2" :activeIndex="currentText.length" />
      <InputBox :text="currentText" :selfIndex="3" :activeIndex="currentText.length" />
      <InputBox :text="currentText" :selfIndex="4" :activeIndex="currentText.length" />
      <InputBox :text="currentText" :selfIndex="5" :activeIndex="currentText.length" />
      <InputBox :text="currentText" :selfIndex="6" :activeIndex="currentText.length" />
      <InputBox v-if="isNewPlate" :text="currentText" :selfIndex="7" :activeIndex="currentText.length" />
    </FlexRow>
    <!-- 键盘区域 -->
    <view v-if="currentText.length === 0" :style="{ ...themeStyles.keyPad.value, ...heightStyle }">
      <Key v-for="(key) in keysProvinceText" :key="key" :text="key" :icon="false" :action="''" @click="onKeyClick" />
    </view>
    <view v-else-if="currentText.length === 1" :style="{ ...themeStyles.keyPad.value, ...heightStyle }">
      <Key v-for="(key) in keysWordText" :key="key" :text="key" :icon="false" :action="''" @click="onKeyClick" />
    </view> 
    <view v-else-if="currentText.length > 1 && currentText.length < (isNewPlate ? 7 : 6)" :style="{ ...themeStyles.keyPad.value, ...heightStyle }">
      <Key v-for="(key) in keysWordText" :key="key" :text="key" :icon="false" :action="''" @click="onKeyClick" />
      <Key v-for="(key) in keysNumberText" :key="key" :text="key" :icon="false" :action="''" @click="onKeyClick" />
    </view> 
    <view v-if="currentText.length >= (isNewPlate ? 7 : 6) " :style="{ ...themeStyles.keyPad.value, ...heightStyle }">
      <Key v-for="(key) in keysWordText" :key="key" :text="key" :icon="false" :action="''" @click="onKeyClick" />
      <Key v-for="(key) in keysNumberText" :key="key" :text="key" :icon="false" :action="''" @click="onKeyClick" />
      <Key v-for="(key) in keysLastWordText" :key="key" :text="key" :icon="false" :action="''" @click="onKeyClick" />
    </view>
    <Height :size="40" />
  </view>
</template>

<script setup lang="ts">
import { computed, provide, ref, toRef, type Ref } from 'vue';
import { propGetThemeVar, useTheme, type TextStyle, type ViewStyle } from '../theme/ThemeDefine';
import { DynamicColor, DynamicSize } from '../theme/ThemeTools';
import InputBox from './PlateKeyBoardInputBox.vue';
import Key from './PlateKeyBoardKey.vue';
import FlexRow from '../layout/FlexRow.vue';
import Button from '../basic/Button.vue';
import RadioGroup from '../form/RadioGroup.vue';
import Radio from '../form/Radio.vue';
import Width from '../layout/space/Width.vue';
import { KeysLastWordText, KeysNumberText, KeysProvinceText, KeysWordText } from './PlateKeyBoardDefine';
import Height from '../layout/space/Height.vue';
import Feedback from '../utils/Feedback';

export interface PlateKeyBoardInnerProps {
  /**
   * 键盘标题
   */
  title?: string;
  /**
   * 是否显示完成按钮
   * @default true
   */
  showFinishButton?: boolean;
  /**
   * 是否显示删除按钮
   * @default true
   */
  showDeleteButton?: boolean;
  /**
   * 完成按钮文字
   * @default '完成'
   */
  finishButtonText?: string;
  /**
   * 删除按钮文字
   * @default '删除'
   */
  deleteButtonText?: string;
  /**
   * 按键高度
   * @default 50
   */
  keyHeight?: number;
  /**
   * 键盘高度(容纳多少行)
   * @default 8
   */
  keyboardHeight?: number;
  /**
   * 每行按键数
   * @default 7
   */
  keyColumCount?: number;
  /**
   * 自定义按键的样式
   */
  keyStyle?: ViewStyle;
  /**
   * 自定义按键文字的样式
   */
  keyTextStyle?: TextStyle;
  /**
   * 按键的背景颜色。
   * @default Color.white
   */
  keyColor?: string;
  /**
   * 完成按键的文字颜色。
   * @default black
   */
  keyTextColor?: string;
  /**
   * 自定义按键按下时的颜色
   * @default pressed.white
   */
  keyPressedColor?: string;
  /**
   * 按键按下时是否有触感反馈，默认是
   * @platform iOS
   * @default true
   */
  keyPressedImpactFeedback?: boolean;

  /**
   * 自定义车牌省选项
   * @default KeysProvinceText
   */
  keysProvinceText?: string[];
  /**
   * 自定义车牌数字选项
   * @default KeysNumberText
   */
  keysNumberText?: string[];
  /**
   * 自定义车牌字母选项
   * @default KeysWordText
   */
  keysWordText?: string[];
  /**
   * 自定义车牌尾字选项
   * @default KeysLastWordText
   */
  keysLastWordText?: string[];
}

const emit = defineEmits([ 'input', 'delete', 'finish', 'cancel' ])
const props = withDefaults(defineProps<PlateKeyBoardInnerProps>(), {
  showFinishButton: () => propGetThemeVar('PlateKeyBoardShowFinishButton', true),
  showDeleteButton: () => propGetThemeVar('PlateKeyBoardShowDeleteButton', true),
  finishButtonText: () => propGetThemeVar('PlateKeyBoardFinishButtonText', '完成'),
  deleteButtonText: () => propGetThemeVar('PlateKeyBoardDeleteButtonText', '删除'),
  keyHeight: () => propGetThemeVar('PlateKeyBoardKeyHeight', 100),
  keyColor: () => propGetThemeVar('PlateKeyBoardKeyColor', 'white'),
  keyTextColor: () => propGetThemeVar('PlateKeyBoardKeyTextColor', 'black'),
  keyPressedColor: () => propGetThemeVar('PlateKeyBoardKeyPressedColor', 'pressed.white'),
  keyPressedImpactFeedback: () => propGetThemeVar('PlateKeyBoardKeyPressedImpactFeedback', true),
  keyColumCount: 7,
  keyboardHeight: 8,
  keysProvinceText: () => KeysProvinceText,
  keysNumberText: () => KeysNumberText,
  keysWordText: () => KeysWordText,
  keysLastWordText: () => KeysLastWordText,
});

const themeContext = useTheme();
const themeStyles = themeContext.useThemeStyles({
  container: {
    display: 'flex',
    position: 'relative',
    flexDirection: 'column',
  },
  keyPad: {
    display: 'flex',
    backgroundColor: DynamicColor('PlateKeyBoardKeyPadBackgroundColor', 'light'),
    position: 'relative',
    flexDirection: 'row',
    flexWrap: 'wrap',
    alignItems: 'flex-start',
    alignContent: 'flex-start',
    width: '100%',
    paddingLeft: DynamicSize('PlateKeyBoardKeyMargin', 10),
    paddingVertical: DynamicSize('PlateKeyBoardKeyMargin', 10),
  },
  title: {
    color: DynamicColor('PlateKeyBoardTitleColor', 'black'),
    fontSize: DynamicSize('PlateKeyBoardTitleFontSize', 32),
  },
  keyText: {
    fontSize: DynamicSize('PlateKeyBoardKeyFontSize', 34),
  },
  dot: {
    margin: DynamicSize('PlateKeyBoardDotMargin', 10),
    width: DynamicSize('PlateKeyBoardDotWidth', 10),
    height: DynamicSize('PlateKeyBoardDotHeight', 10),
    backgroundColor: DynamicColor('PlateKeyBoardDotBackgroundColor', 'text.second'),
    borderRadius: DynamicSize('PlateKeyBoardDotBorderRadius', 10),
  },
});

const currentText = ref('');
const isNewPlate = ref(false);

const keyMargin = computed(() => themeContext.getVar('PlateKeyBoardKeyMargin', 7));
const keyTextStyle = computed(() => ({
  ...themeStyles.keyText.value,
  ...props.keyTextStyle,
  color: themeContext.resolveThemeColor(props.keyTextColor),
}));
const heightStyle = computed(() => ({
  height: themeContext.resolveSize(props.keyHeight * props.keyboardHeight + keyMargin.value)
}));

//传递到子组件使用
export type PlateKeyBoardContext = {
  keyTextStyle: Ref<TextStyle>,
  keyColumCount: Ref<number>,
  keyMargin: Ref<number>,
  keyColor: Ref<string>,
  keyPressedColor: Ref<string>,
  keyStyle: Ref<ViewStyle|undefined>,
  keyHeight: Ref<number>,
};
provide<PlateKeyBoardContext>('PlateKeyBoardContext', {
  keyTextStyle,
  keyMargin: toRef(keyMargin),
  keyColumCount: toRef(props.keyColumCount),
  keyColor: toRef(props.keyColor),
  keyPressedColor: toRef(props.keyPressedColor),
  keyHeight: toRef(props.keyHeight),
  keyStyle: toRef(props.keyStyle),
});

function onKeyClick(text: string) {
  if (!text)
    return;
  if (props.keyPressedImpactFeedback)
    Feedback.impactSelectionFeedbackGenerator();
  emit('input', text);

  currentText.value += text;
  
  if (currentText.value.length >= (isNewPlate.value ? 8 : 7)) {
    setTimeout(() => onFinish(currentText.value), 400);
  }
}
function onFinish(text?: string) {
  if ((text || currentText.value).length < (isNewPlate.value ? 8 : 7)) {
    uni.showToast({
      title: '请输入完整的车牌号哦！',
      icon: 'none',
    });
    return;
  }
  emit('finish', text || currentText.value);
}
function onDelete() {
  currentText.value = currentText.value.length >= 1 ? currentText.value.substring(0, currentText.value.length - 1) : '';
  emit('delete');
}
function onCancel() {
  emit('cancel');
}


</script>