<template>
  <view class="form_item" :class="{ 'wrap': !inline }">
    <view class="form_item_key font-bold" :class="{ 'require': required }">{{ label }}</view>
    <view class="form_item_val">
      <radio-group class="input radio-group" @change="onRadioChange">
        <label v-for="(item, index) in options" :key="index">
          <radio :value="item.value" :checked="value === item.value" :disabled="readOnly" />
          <text>{{ item.name }}</text>
        </label>
      </radio-group>
    </view>
  </view>
</template>

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

const props = defineProps({
  label: {
    type: String,
    default: ''
  },
  options: {
    type: Array,
    default: () => []
  },
  inline: {
    type: Boolean,
    default: true,
  },
  readOnly: {
    type: Boolean,
    default: false
  },
  required: {
    type: Boolean,
    default: false
  },
  errorMsg: {
    type: String,
    default: '选择不合法'
  },
  value: {
    type: String,
    default: ''
  }
});

const emit = defineEmits(['radioChange', 'validateRequest', 'update:value']);

const onRadioChange = (e: any) => {
  const val = e.detail.value;
  emit('radioChange', { value: val });
  emit('update:value', val);
  validateInput(val);
};

const validateInput = (value: string) => {
  emit('validateRequest', { value });
};

watch(() => props.value, (newVal) => {
  validateInput(newVal);
});
</script>

<style>
/* 表单 start */
.form_item {
  position: relative;
  width: inherit;
  padding: 0 10upx;
  font-size: 30upx;
  height: 120upx;
  display: flex;
  align-items: center;
}

.form_item.wrap {
  flex-direction: column;
  align-items: stretch;
  justify-content: stretch;
  height: fit-content;
}

.form_item.wrap .form_item_key,
.form_item.wrap .form_item_val {
  width: 100%;
  min-height: 120upx;
  line-height: 120upx;
}

.form_item + .form_item {
  border-top: 2upx solid #e5e5e5;
}

.form_item .form_item_key {
  padding-left: 20upx;
  position: relative;
  width: 220upx;
}

.form_item .form_item_val {
  flex: 1 0 0;
  text-align: right;
  height: inherit;
  padding: 0 20upx;
}

.form_item .form_item_val .input {
  height: inherit;
}

.form_item .form_item_val .radio-group {
  display: flex; 
  align-items: center; 
  flex-wrap: wrap; 
  justify-content: space-between;
}

.img_captcha {
  width: 160upx;
  height: inherit;
  background-color: var(--dominantColor);
  color: #fff;
  font-weight: bold;
  font-size: 38upx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.require::after {
  content: '*';
  position: absolute;
  color: #FF1D1F;
  top: 10%;
  left: 0;
}
/* 表单 end */

.font-bold {
  font-weight: bold;
}
</style>
