<template>
    <view class="bind-page">
        <view v-if="loading" class="state-wrap">
            <text class="state-text">加载中...</text>
        </view>
        <template v-else>
            <view v-if="simSerialNumber" class="section">
                <view class="section-title">
                    设备
                    <text v-if="hasBindDevice" class="tag-bound">(已绑定)</text>
                </view>
                <view class="info-card">
                    <text class="info-main">{{ deviceDisplay }}</text>
                </view>
            </view>

            <view v-if="childId" class="section">
                <view class="section-title">
                    孩子
                    <text v-if="hasBindChild" class="tag-bound">(已绑定)</text>
                </view>
                <view class="info-card child-card">
                    <image
                        v-if="childAvatar"
                        class="child-avatar"
                        :src="childAvatar"
                        mode="aspectFill"
                    />
                    <view class="child-meta">
                        <text class="info-main">{{ childDisplayName }}</text>
                        <text v-if="childAccountText" class="info-sub">账号：{{ childAccountText }}</text>
                    </view>
                </view>
            </view>

            <view class="section">
                <view class="section-title">请选择您的身份</view>
                <view class="identity-grid">
                    <view
                        v-for="item in PARENT_IDENTITY_LIST"
                        :key="item.id"
                        class="identity-item"
                        :class="{ active: identityType === item.id, disabled: !canBind }"
                        @click="selectIdentity(item.id)"
                    >
                        <image class="identity-icon" :src="item.icon" mode="aspectFit" />
                        <text class="identity-name">{{ item.name }}</text>
                        <view v-if="identityType === item.id" class="identity-check">✓</view>
                    </view>
                </view>
            </view>

            <view class="footer">
                <view
                    class="submit-btn"
                    :class="{ disabled: !canSubmit || hasAllBound }"
                    @click="submitBind"
                >
                    {{ hasAllBound ? '已绑定' : submitting ? '提交中...' : '申请绑定' }}
                </view>
            </view>
        </template>
    </view>
</template>

<script setup lang="ts">
import { computed, ref } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import { storeToRefs } from 'pinia';
import {
    getBindParentsByChildId,
    getBindParentsByDevice,
    parentBindApply,
    type ParentBindChildItem,
} from '@/api/parent';
import { useUserStore } from '@/state/modules/user';
import {
    PARENT_IDENTITY_LIST,
    PARENT_TYPE_OTHER,
} from '../utils/parentIdentity';

const userStore = useUserStore();
const { userInfo } = storeToRefs(userStore);

const loading = ref(true);
const submitting = ref(false);
const childId = ref('');
const childAccount = ref('');
const simSerialNumber = ref('');
const identityType = ref(PARENT_TYPE_OTHER);

const bindChildRow = ref<ParentBindChildItem | null>(null);
const bindDeviceRow = ref<any | null>(null);
const hasBindChild = ref(false);
const hasBindDevice = ref(false);

const childDisplayName = computed(() => {
    if (bindChildRow.value?.child?.name || bindChildRow.value?.child?.nickname) {
        return bindChildRow.value.child.name || bindChildRow.value.child.nickname || '孩子';
    }
    return childAccount.value || '孩子';
});

const childAccountText = computed(() => bindChildRow.value?.child?.account || childAccount.value || '');
const childAvatar = computed(() => bindChildRow.value?.child?.avatar || '');

const deviceDisplay = computed(() => {
    if (bindDeviceRow.value?.simSerialNumber) return bindDeviceRow.value.simSerialNumber;
    return simSerialNumber.value;
});

const needBoth = computed(() => !!(childId.value && simSerialNumber.value));

const hasAllBound = computed(() => {
    if (needBoth.value) return hasBindChild.value && hasBindDevice.value;
    if (simSerialNumber.value) return hasBindDevice.value;
    return hasBindChild.value;
});

const bindChildIdToApply = computed(() => {
    if (!childId.value || hasBindChild.value) return undefined;
    return childId.value;
});

const bindDeviceSnToApply = computed(() => {
    if (!simSerialNumber.value || hasBindDevice.value) return undefined;
    return simSerialNumber.value;
});

const canBind = computed(() => !!(bindChildIdToApply.value || bindDeviceSnToApply.value));

const canSubmit = computed(() => canBind.value && !submitting.value);

const checkBindStatus = async () => {
    const parentId = userInfo.value.id;
    if (!parentId) {
        await userStore.fetchParentUserInfo().catch(() => { /* ignore */ });
    }
    const currentParentId = userInfo.value.id;

    if (childId.value) {
        const res = await getBindParentsByChildId(childId.value);
        const rows = res.data?.rows || [];
        if (rows.length) {
            bindChildRow.value = rows[0];
        }
        hasBindChild.value = rows.some(
            (item) => String(item.parent?.id) === String(currentParentId),
        );
    }

    if (simSerialNumber.value) {
        const res = await getBindParentsByDevice(simSerialNumber.value);
        const rows = res.data?.rows || [];
        if (rows.length) {
            bindDeviceRow.value = rows[0];
        }
        hasBindDevice.value = rows.some(
            (item) => String(item.parent?.id) === String(currentParentId),
        );
    }
};

onLoad(async (query) => {
    childId.value = query?.childId ? String(query.childId) : '';
    childAccount.value = query?.account ? decodeURIComponent(String(query.account)) : '';
    simSerialNumber.value = query?.simSerialNumber
        ? decodeURIComponent(String(query.simSerialNumber))
        : '';

    if (!childId.value && !simSerialNumber.value) {
        uni.showModal({
            title: '提示',
            content: '参数错误',
            showCancel: false,
            success: () => uni.navigateBack(),
        });
        return;
    }

    loading.value = true;
    try {
        await checkBindStatus();
    } catch (e: any) {
        uni.showToast({ title: e?.message || '加载失败', icon: 'none' });
    } finally {
        loading.value = false;
    }
});

const selectIdentity = (id: number) => {
    if (!canBind.value) return;
    identityType.value = id;
};

const submitBind = async () => {
    if (hasAllBound.value || !canSubmit.value) return;
    if (!identityType.value) {
        uni.showToast({ title: '请选择您与孩子的关系', icon: 'none' });
        return;
    }

    submitting.value = true;
    try {
        await parentBindApply({
            childId: bindChildIdToApply.value,
            simSerialNumber: bindDeviceSnToApply.value,
            identityType: identityType.value,
        });
        uni.showToast({ title: '已发出绑定申请', icon: 'success' });
        setTimeout(() => {
            uni.navigateBack();
        }, 1200);
    } catch (e: any) {
        uni.showToast({ title: e?.message || '申请失败', icon: 'none' });
    } finally {
        submitting.value = false;
    }
};
</script>

<style lang="scss" scoped>
.bind-page {
    min-height: 100vh;
    padding: 24rpx 24rpx 180rpx;
    background: linear-gradient(180deg, #ecfeff 0%, #f8fafc 40%);
    box-sizing: border-box;
}

.state-wrap {
    padding: 120rpx 0;
    text-align: center;
}

.state-text {
    color: #94a3b8;
    font-size: 28rpx;
}

.section {
    margin-bottom: 32rpx;
}

.section-title {
    margin-bottom: 16rpx;
    color: #64748b;
    font-size: 26rpx;
    font-weight: 700;
}

.tag-bound {
    color: #ef4444;
    margin-left: 8rpx;
}

.info-card {
    padding: 28rpx;
    border-radius: 28rpx;
    background: rgba(255, 255, 255, 0.95);
    box-shadow: 0 12rpx 32rpx rgba(8, 145, 178, 0.08);
}

.child-card {
    display: flex;
    align-items: center;
    gap: 20rpx;
}

.child-avatar {
    width: 96rpx;
    height: 96rpx;
    border-radius: 24rpx;
    background: #ecfeff;
    flex-shrink: 0;
}

.child-meta {
    flex: 1;
    min-width: 0;
}

.info-main {
    display: block;
    color: #164e63;
    font-size: 32rpx;
    font-weight: 900;
}

.info-sub {
    display: block;
    margin-top: 8rpx;
    color: #94a3b8;
    font-size: 24rpx;
}

.identity-grid {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 16rpx;
}

.identity-item {
    position: relative;
    padding: 24rpx 20rpx;
    border-radius: 24rpx;
    background: #fff;
    display: flex;
    align-items: center;
    gap: 16rpx;
    border: 2rpx solid transparent;
    box-shadow: 0 8rpx 24rpx rgba(8, 145, 178, 0.06);

    &.active {
        border-color: #0891b2;
        background: #ecfeff;
    }

    &.disabled {
        opacity: 0.55;
    }
}

.identity-icon {
    width: 72rpx;
    height: 72rpx;
    flex-shrink: 0;
}

.identity-name {
    color: #164e63;
    font-size: 28rpx;
    font-weight: 700;
}

.identity-check {
    position: absolute;
    top: 16rpx;
    right: 16rpx;
    width: 36rpx;
    height: 36rpx;
    border-radius: 50%;
    background: #0891b2;
    color: #fff;
    font-size: 22rpx;
    display: flex;
    align-items: center;
    justify-content: center;
}

.footer {
    position: fixed;
    left: 0;
    right: 0;
    bottom: 0;
    padding: 20rpx 24rpx calc(20rpx + env(safe-area-inset-bottom));
    background: rgba(255, 255, 255, 0.96);
    box-shadow: 0 -8rpx 24rpx rgba(15, 23, 42, 0.06);
}

.submit-btn {
    height: 88rpx;
    border-radius: 24rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    color: #fff;
    font-size: 30rpx;
    font-weight: 900;
    background: linear-gradient(135deg, #0891b2, #06b6d4);

    &.disabled {
        opacity: 0.5;
    }
}
</style>
