<template>
  <div class="grace-year-input">
    <el-input
      :model-value="inputValue"
      placeholder="请输入"
      :formatter="(value: string) => value"
      :parser="(value: string) => value.replace(/\D/g, '')"
      @input="inputChange"
      v-bind="$attrs"
    >
      <template #prepend>
        <el-select
          :model-value="graceType"
          placeholder="请选择"
          style="width: 88px"
          :disabled="$attrs.disabled as boolean"
          @change="graceTypeChange"
        >
          <el-option label="公元前" :value="-1" />
          <el-option label="公元" :value="1" />
        </el-select>
      </template>
    </el-input>
  </div>
</template>

<script setup lang="ts" name="GraceYear">
import { ref, defineEmits, defineProps, watch } from "vue";

// 公元年份输入组件，负数表示公元前
const props = defineProps({
  modelValue: {
    type: Number
  }
});
const emit = defineEmits(["update:modelValue"]);
const graceType = ref(-1);
const inputValue = ref("");
watch(
  () => props.modelValue,
  val => {
    if (val) {
      graceType.value = convertToSign(val);
    }
    inputValue.value = val ? Math.abs(val).toString() : "";
  }
);

function convertToSign(num: number) {
  return num > 0 ? 1 : num < 0 ? -1 : 0;
}

function graceTypeChange(val: number) {
  if (inputValue.value) {
    emit("update:modelValue", val * parseInt(inputValue.value));
  } else {
    graceType.value = val;
  }
}

function inputChange(val: string) {
  emit("update:modelValue", val ? graceType.value * parseInt(val) : undefined);
}
</script>

<style scoped lang="scss">
@import "./index.scss";
</style>
