<script setup lang="ts">
    import { computed, reactive, ref, watch } from 'vue'
    import { useDictStore } from '@/store/modules/dict'
    import * as NongchangAPI from '@/api/model/nongchang'

    // 定义Props
    interface Props {
        show: boolean
        editData?: any
    }

    const props = withDefaults(defineProps<Props>(), {
        show: false,
        editData: null,
    })

    // 定义Emits
    const emit = defineEmits<{
        'update:show': [value: boolean]
        submit: [data: any]
        close: []
    }>()

    // 表单引用
    const formRef = ref()
    const loading = ref(false)
    const showDeviceTypePicker = ref(false)

    // 字典存储
    const dictStore = useDictStore()

    // 表单数据
    const formData = reactive({
        deviceName: '',
        deviceType: '',
        deviceTypeText: '',
        deviceIdentifier: '',
    })

    // 设备类型选项 - 使用字典数据
    const deviceTypeOptions = computed(() => {
        return (
            dictStore.getDictList.deviceType?.map((item: any) => ({
                value: item.value,
                text: item.text,
            })) || []
        )
    })

    // 设备类型选择器数据 (不再需要，因为fui-picker使用options属性)

    // 计算属性
    const dialogTitle = computed(() => {
        return props.editData ? '编辑设备' : '添加设备'
    })

    const submitButtonText = computed(() => {
        return props.editData ? '保存' : '确认'
    })

    // 表单验证规则
    const rules = {
        deviceName: [
            { required: true, message: '请输入设备名称', trigger: 'blur' },
            { min: 2, max: 50, message: '设备名称长度在2-50个字符之间', trigger: 'blur' },
        ],
        deviceType: [{ required: true, message: '请选择设备类型', type: 'number', trigger: 'change' }],
        deviceIdentifier: [
            { required: true, message: '请输入设备唯一标识', trigger: 'blur' },
            { min: 6, max: 100, message: '设备标识长度在6-100个字符之间', trigger: 'blur' },
            {
                validator: (rule: any, value: any, callback: any) => {
                    if (!/^[a-zA-Z0-9\-_:]+$/.test(value)) {
                        callback(new Error('设备标识只能包含字母、数字、下划线、中划线和冒号'))
                    } else {
                        callback()
                    }
                },
                trigger: 'blur',
            },
        ],
    }

    // 监听显示状态
    watch(
        () => props.show,
        (newVal) => {
            if (newVal && props.editData) {
                // 编辑模式，填充数据
                resetFormData()
                loadEditData()
            } else if (newVal) {
                // 添加模式，重置表单
                resetFormData()
            }
        },
    )

    // 重置表单数据
    function resetFormData() {
        formData.deviceName = ''
        formData.deviceType = ''
        formData.deviceTypeText = ''
        formData.deviceIdentifier = ''

        // 清除验证状态
        if (formRef.value) {
            formRef.value.resetFields()
        }
    }

    // 加载编辑数据
    function loadEditData() {
        if (!props.editData)
return

        formData.deviceName = props.editData.deviceName || ''
        formData.deviceType = props.editData.deviceType || ''
        formData.deviceIdentifier = props.editData.deviceIdentifier || ''

        // 设置设备类型文本
        if (props.editData.deviceType) {
            const typeOption = deviceTypeOptions.value.find((item) => item.value === props.editData.deviceType)
            if (typeOption) {
                formData.deviceTypeText = typeOption.text
            } else {
                // 如果字典中没有找到对应的文本，使用原始数据中的文本
                formData.deviceTypeText = props.editData.deviceType_dictText || ''
            }
        } else {
            formData.deviceTypeText = ''
        }
    }

    // 设备类型选择确认
    function handleDeviceTypeConfirm(e: any) {
        formData.deviceType = e.value
        formData.deviceTypeText = e.text
        showDeviceTypePicker.value = false
    }

    // 提交表单
    async function handleSubmit() {
        try {
            console.log(formData)
            // 先进行表单验证
            const valid = await formRef.value.validate()
            if (!valid) {
                return
            }

            loading.value = true

            // 准备提交数据
            const submitData = {
                ...formData,
            }

            // 根据 editData 判断是新增还是修改
            let result
            if (props.editData && props.editData.id) {
                // 编辑设备，需要传递设备ID
                result = await NongchangAPI.editDevice({
                    ...submitData,
                    id: props.editData.id,
                })
                console.log('修改设备数据:', submitData)
            } else {
                // 新增设备
                result = await NongchangAPI.addDevice(submitData)
                console.log('新增设备数据:', submitData)
            }

            uni.showToast({ title: '操作成功', icon: 'success' })
            emit('update:show', false)
            emit('submitSuccess')
        } catch (error) {
            console.log('提交失败:', error)
            uni.showToast({
                title: '操作失败',
                icon: 'none',
                duration: 2000,
            })
        } finally {
            loading.value = false
        }
    }

    // 关闭弹窗
    function handleClose() {
        emit('update:show', false)
        emit('close')
    }

    // 暴露方法给父组件
    defineExpose({
        resetFormData,
        setLoading: (value: boolean) => {
            loading.value = value
        },
    })
</script>

<template>
    <u-modal
        :show="show"
        :title="dialogTitle"
        :showConfirmButton="false"
        :showCancelButton="false"
        @close="handleClose"
        :closeOnClickOverlay="false"
    >
        <view class="dialog-content">
            <u-form :model="formData" :rules="rules" ref="formRef" label-width="180rpx">
                <!-- 设备基本信息 -->
                <view class="section-title">设备基本信息</view>

                <u-form-item label="设备名称" prop="deviceName" required>
                    <u-input v-model="formData.deviceName" placeholder="请输入设备名称" border="bottom" />
                </u-form-item>

                <u-form-item label="设备类型" prop="deviceType" required>
                    <view class="address-display" @click="showDeviceTypePicker = true">
                        <text :class="{ 'placeholder-text': !formData.deviceTypeText }">
                            {{ formData.deviceTypeText || '请选择设备类型' }}
                        </text>
                    </view>
                    <!-- <u-input v-model="formData.deviceTypeText" placeholder="请选择设备类型" border="bottom"
                        @click="showDeviceTypePicker = true" /> -->
                </u-form-item>

                <u-form-item label="设备标识" prop="deviceIdentifier" required>
                    <u-input v-model="formData.deviceIdentifier" placeholder="序列号/MAC地址等" border="bottom" />
                </u-form-item>

                <!-- 操作按钮 -->
                <view class="dialog-buttons">
                    <u-button
                        type="primary"
                        @click="handleSubmit"
                        :loading="loading"
                        size="normal"
                        class="submit-btn"
                        color="var(--fui-color-success)"
                    >
                        {{ submitButtonText }}
                    </u-button>
                    <u-button @click="handleClose" size="normal" class="cancel-btn">取消</u-button>
                </view>
            </u-form>

            <!-- 设备类型选择器 -->
            <fui-picker
                :show="showDeviceTypePicker"
                :options="deviceTypeOptions"
                :layer="1"
                :linkage="true"
                @change="handleDeviceTypeConfirm"
                @cancel="showDeviceTypePicker = false"
            />
        </view>
    </u-modal>
</template>

<style lang="scss" scoped>
    .dialog-content {
        padding: 10rpx 30rpx;
        width: 90%;
        max-height: 80vh;
        overflow-y: auto;
    }

    .section-title {
        font-size: 32rpx;
        font-weight: 600;
        color: #333;
        margin: 20rpx 0 30rpx 0;
        padding-left: 20rpx;
        border-left: 6rpx solid #5db66f;
    }

    .dialog-buttons {
        display: flex;
        gap: 20rpx;
        margin-top: 40rpx;

        .submit-btn {
            flex: 1;

            ::v-deep .u-button {
                background-color: #5db66f;
                border-color: #5db66f;
            }
        }

        .cancel-btn {
            flex: 1;

            ::v-deep .u-button {
                background-color: #fff;
                color: #666;
                border: 2rpx solid #dcdfe6;
            }
        }
    }

    // uview-plus 表单样式调整
    ::v-deep .u-form-item {
        margin-bottom: 40rpx;

        .u-form-item__body {
            padding: 0;
            align-items: flex-start;
        }

        .u-form-item__body__left__content__label {
            font-size: 28rpx;
            color: #333;
            font-weight: 500;
            width: 180rpx;
            flex-shrink: 0;
            text-align: right;
            padding-right: 20rpx;
            line-height: 80rpx;
        }

        .u-form-item__body__right {
            flex: 1;
            min-width: 0;
        }
    }
    .address-display {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 12rpx 18rpx;
        background-color: transparent;
        border-bottom: 2rpx solid #e4e7ed;
        border-radius: 0;
        cursor: pointer;
        width: 100%;

        text {
            flex: 1;
            font-size: 28rpx;
            color: #333;
        }

        .placeholder-text {
            color: #c0c4cc;
        }
    }

    ::v-deep .u-form-item__body__left__content__required {
        position: static;
        padding-right: 10rpx;
    }

    // 输入框样式优化
    ::v-deep .u-input {
        .u-input__content {
            padding: 0;

            .u-input__content__field-wrapper {
                border: none;
                border-radius: 0;

                .u-input__content__field-wrapper__field {
                    font-size: 28rpx;
                    height: auto;
                }

                .u-input__content__field-wrapper__placeholder {
                    color: #c0c4cc;
                    font-size: 28rpx;
                }
            }

            &.u-input--focus {
                .u-input__content__field-wrapper {
                    border-bottom-color: #5db66f;
                }
            }
        }
    }

    // 模态框样式调整
    ::v-deep .u-modal {
        .u-modal__content {
            border-radius: 20rpx;
            padding: 20rpx 0rpx;
        }

        .u-modal__header {
            border-bottom: 2rpx solid #f0f0f0;
            padding: 30rpx;

            .u-modal__header__title {
                font-size: 32rpx;
                font-weight: 600;
                color: #333;
            }
        }
    }
</style>
