<template>
    <div class="p-5">
        <n-form ref="formRef" :model="form" :rules="rules">
            <n-form-item
                v-for="(item, index) in fileds"
                :key="index"
                :path="'field_' + (index + 1)"
                :label="index + 1 + '.' + item.name"
            >
                <n-input
                    v-if="item.formType === 'singleLineText'"
                    v-model:value="form[String(`field_${index + 1}`)]"
                    :placeholder="item.placeholder || '请输入...'"
                    :allow-input="onlyAllowNumber"
                >
                </n-input>

                <n-radio-group
                    v-else-if="item.formType === 'radio'"
                    v-model:value="form[String(`field_${index + 1}`)]"
                    :name="`field_${index + 1}`"
                >
                    <n-space>
                        <n-radio v-for="(option, optionIndex) in item.options" :key="optionIndex" :value="option.value">
                            {{ option.label }}
                        </n-radio>
                    </n-space>
                </n-radio-group>

                <n-checkbox-group
                    v-else-if="item.formType === 'checkbox'"
                    v-model:value="form[String(`field_${index + 1}`)]"
                >
                    <n-space item-style="display: flex;">
                        <n-checkbox
                            v-for="(option, optionIndex) in item.options"
                            :key="optionIndex"
                            :value="option.value"
                            :label="option.label"
                        />
                    </n-space>
                </n-checkbox-group>
            </n-form-item>
            <div class="mt-3 flex justify-center">
                <n-button
                    class="h-10 max-w-[320px] mx-auto"
                    @click="submit"
                    block
                    type="primary"
                    size="large"
                    :loading="loading"
                    circle
                >
                    确认
                </n-button>
            </div>
        </n-form>
    </div>
</template>

<script setup lang="ts">
import {
    NForm,
    NFormItem,
    NInput,
    FormInst,
    NButton,
    NRadioGroup,
    NSpace,
    NRadio,
    NCheckboxGroup,
    NCheckbox,
    useMessage
} from 'naive-ui'
import { ref, computed, Ref } from 'vue'
import { fetchGetUserFileds, fetchUserFileds } from '@/api'
import { useUserStore, useCompanyStore } from '@/store'
import { emitter } from '@/plugins'
import { refDebounced } from '@vueuse/core'
import { AnyARecord } from 'dns'

const rules = ref({})
const onlyAllowNumber = (value: string) => !value || /^\d+$/.test(value)

const loading = ref(false)

const userStore = useUserStore()
const companyStore = useCompanyStore()
const userInfo = computed(() => {
    return userStore.userInfo
})

const company = computed(() => {
    return companyStore.company
})

const fileds = ref(<any>[])

type stringkey = Record<any, any>

const form = ref(<stringkey>{})
const unitForm = ref(<any>{})
fetchGetUserFileds(userInfo.value.id, company.value.id).then((res: any) => {
    if (res.code === 0) {
        emitter.emit('updateInfoTitle', res.form.name)
        unitForm.value = res.form
        fileds.value = res.fileds.map((item: any) => {
            if (
                item.formType === 'radio' ||
                item.formType === 'select' ||
                item.formType === 'multiSelect' ||
                item.formType === 'checkbox'
            ) {
                return {
                    ...item,
                    options: JSON.parse(item.optionsValue)
                }
            }
            return item
        })

        let _form = <stringkey>{}
        let _rules = <stringkey>{}
        res.fileds.forEach((item: any, index: any) => {
            let _name = String(`field_${index + 1}`)
            _form[_name] = ''
            if (item.required) {
                _rules[_name] = [
                    {
                        required: true,
                        message: '请输入',
                        trigger: 'blur'
                    }
                ]
            }
        })
        rules.value = _rules
        form.value = _form
    }
})

const formRef: Ref<FormInst | null> = ref(null)

const message = useMessage()
function submit() {
    console.log('验证')
    formRef.value?.validate((errors: any) => {
        if (!errors) {
            console.log(form.value)

            let datas = []
            datas = fileds.value.map((item: any, index: number) => {
                return {
                    userId: userInfo.value.id,
                    formId: unitForm.value.id,
                    filedId: item.id,
                    value:
                        item.formType === 'multiSelect' || item.formType === 'checkbox'
                            ? form.value[`field_${index + 1}`].join(',')
                            : form.value[`field_${index + 1}`]
                }
            })
            fetchUserFileds(datas).then(res => {
                message.success('填写成功')
                emitter.emit('backChat')
            })
        } else {
            console.log(errors)
        }
    })
}
</script>
