<script setup lang="ts">
import WdButton from 'wot-design-uni/components/wd-button/wd-button.vue'
import WdInput from 'wot-design-uni/components/wd-input/wd-input.vue'
import WdPicker from 'wot-design-uni/components/wd-picker/wd-picker.vue'
import { ConfigProviderThemeVars } from 'wot-design-uni'
import { DataFormProps, DataFormSchema } from './data-form'
import { addUnit } from 'wot-design-uni/components/common/util'
import { omit } from 'radash'
import WdForm from 'wot-design-uni/components/wd-form/wd-form.vue'

const modelValue = defineModel({
  type: Object,
  default: () => ({}),
})
withDefaults(
  defineProps<{
    schema: DataFormSchema
    rules?: { [key: string]: { required: boolean; message: string }[] }
    direction?: 'horizontal' | 'vertical'
  }>(),
  { direction: 'vertical', labelShow: true },
)
const emits = defineEmits(['submit'])
const form = ref<InstanceType<typeof WdForm>>()
const types = {
  TextField: WdInput,
  Submit: WdButton,
  Select: WdPicker,
  // Radio: WdRadioGroup,
}
const defaultProps = {
  TextField: {
    noBorder: true,
    style: {},
    customClass: 'rounded border border-[#e1e1e1] border-solid p-1',
    placeholder: ' ',
  },
  Submit: {
    customClass: 'w-full! rounded-lg! my-4!',
    block: true,
  },
}
const verticalDefaultProps = {
  TextField: {
    noBorder: true,
    style: {},
    customClass: 'rounded border border-[#e1e1e1] border-solid p-1',
    placeholder: ' ',
  },
  Submit: {
    customClass: 'w-full! rounded-lg! my-4!',
    block: true,
  },
}
const horizontalDefaultProps = {
  TextField: {
    customClass: 'text-red!',
    placeholderClass: 'text-black/30',
    noBorder: true,
  },
  Select: {
    // customClass: 'text-black/30! border-b-1 border-b-[#e1e1e1] border-b-solid',
    customClass: 'text-black/30!',
  },
  Radio: {
    customClass: 'my--4!',
  },
  Checkbox: {
    customClass: 'my--4!',
  },
  TimePick: {
    customClass: 'm-0!',
  },
  Textarea: {
    customClass: 'p-0!',
  },
}
const themeVars: ConfigProviderThemeVars = {
  cellPadding: '0',
  cellWrapperPadding: '0px',
  radioButtonRadius: '8rpx',
  radioButtonBg: 'transparent',
  checkboxButtonRadius: '8rpx',
  checkboxButtonBg: 'transparent',
}
const submit = () => {
  emits('submit', modelValue)
}
const validate = async (): Promise<{ valid: boolean; errors: any[] }> => {
  return await form.value.validate()
}
defineExpose({
  validate,
})
</script>
<template>
  <wd-config-provider :theme-vars="themeVars">
    <wd-form ref="form" error-type="toast" :rules="rules" :model="modelValue">
      <!-- <wd-cell-group border> -->
      <template
        v-for="(
          [prop, { type, label, labelWidth, hiddenLabel, existing, required, props }], index
        ) in Object.entries(schema)"
        :key="index"
      >
        <div
          v-if="existing ?? true"
          class="grid mb-4"
          :class="[direction === 'horizontal' ? 'items-start' : '']"
          :style="
            direction === 'horizontal'
              ? { 'grid-template-columns': `${addUnit(labelWidth || 100)} auto` }
              : {}
          "
        >
          <label
            v-if="type !== 'Submit' && !hiddenLabel"
            class="text-sm font-normal leading-relaxed"
            :class="[direction === 'horizontal' ? 'text-black/60' : 'mb-1 text-black/40']"
            :for="prop"
          >
            <span
              v-if="required"
              class="text-[#ef4343] text-base font-normal font-['PingFang_SC'] leading-normal"
            >
              *
            </span>
            {{ label || prop }}
          </label>
          <wd-input
            v-if="type === 'TextField'"
            v-bind="{
              ...(direction === 'vertical'
                ? verticalDefaultProps[type]
                : horizontalDefaultProps[type]),
              ...omit(props, []),
            }"
            v-model="modelValue[prop]"
          ></wd-input>
          <wd-datetime-picker
            v-model="modelValue[prop]"
            v-if="type === 'TimePick'"
            v-bind="{
              ...(direction === 'vertical'
                ? verticalDefaultProps[type]
                : horizontalDefaultProps[type]),
              cell: false,
              ...props,
            }"
          />
          <div v-if="type === 'Textarea'" class="textarea-evo relative">
            <wd-textarea
              v-model="modelValue[prop]"
              v-bind="{
                ...(direction === 'vertical'
                  ? verticalDefaultProps[type]
                  : horizontalDefaultProps[type]),
                cell: false,
                ...props,
              }"
            />
            <div v-if="props?.maxlength" class="absolute bottom-0 right-0">
              <div
                class="w-10 h-5 text-right text-black/40 text-xs font-normal font-['PingFang_SC'] leading-tight"
              >
                {{ modelValue[prop]?.length }}/{{ props?.maxlength }}
              </div>
            </div>
          </div>
          <wd-picker
            v-if="type === 'Select'"
            v-bind="{
              ...(direction === 'vertical'
                ? verticalDefaultProps[type]
                : horizontalDefaultProps[type]),
              cell: false,
              ...props,
            }"
            v-model="modelValue[prop]"
          ></wd-picker>

          <wd-radio-group
            v-if="type === 'Radio'"
            v-bind="{
              ...(direction === 'vertical'
                ? verticalDefaultProps[type]
                : horizontalDefaultProps[type]),
              ...props,
              cell: true,
              shape: 'button',
            }"
            v-model="modelValue[prop]"
          >
            <template v-for="{ label, value } of props.columns" :key="value">
              <wd-radio :value="value">{{ label }}</wd-radio>
            </template>
          </wd-radio-group>

          <wd-checkbox-group
            v-if="type === 'Checkbox'"
            v-bind="{
              ...(direction === 'vertical'
                ? verticalDefaultProps[type]
                : horizontalDefaultProps[type]),
              ...props,
              cell: true,
              shape: 'button',
            }"
            v-model="modelValue[prop]"
          >
            <template v-for="{ label, value } of props.columns" :key="value">
              <wd-checkbox custom-class="mr-4!" :modelValue="value">{{ label }}</wd-checkbox>
            </template>
          </wd-checkbox-group>
          <wd-button
            v-if="type === 'Submit'"
            v-bind="{
              ...(direction === 'vertical' ? verticalDefaultProps[type] : {}),
              ...omit(props, []),
              formType: 'submit',
            }"
            @click="submit"
          >
            <span v-if="type === 'Submit'">提交</span>
          </wd-button>
        </div>
      </template>
      <!-- </wd-cell-group> -->
    </wd-form>
  </wd-config-provider>
</template>
<style lang="scss">
.textarea-evo {
  .wd-textarea__inner {
    height: 250rpx !important;
  }
}
</style>
