<template>
    <AppLayout
        title="个人信息"
        :sub-title="`完成度${percent}`"
        border
        back-gorund-color="#ffffff"
        :show-bg-image="false"
    >
        <template #headerleft>
            <view class="btn mar_le20 button-click" @click="navBack">取消</view>
        </template>
        <template #headerright>
            <view class="btn mar_ri20 button-click" @click="confirm">确认</view>
        </template>
        <view class="content">
            <view class="content-avatar">
                <view class="avatar-title">编辑头像</view>
                <view @click="selectAvatar">
                    <image class="avatar" v-if="fromValue.avatar" :src="fromValue.avatar" />
                    <image class="avatar" v-else-if="fromValue.sex == '0'" src="@/static/icon/boy.png" />
                    <image class="avatar" v-else="fromValue.sex == '1'" src="@/static/icon/girl.png" />
                </view>
            </view>
            <view class="content-input">
                <view class="input-titile">姓名</view>
                <input class="input-con" v-model="fromValue.name" placeholder="请输入您的姓名" />
            </view>
            <view class="content-sex">
                <view class="sex-titile">性别</view>
                <view class="sext-ri">
                    <view class="sext-box" :class="{ 'sext-boxactive': fromValue.sex === 0 }" @click="changeSex(0)">
                        男
                    </view>
                    <view class="sext-box" :class="{ 'sext-boxactive': fromValue.sex === 1 }" @click="changeSex(1)">
                        女
                    </view>
                </view>
            </view>
            <view class="content-input" @click="changeDateBirt">
                <view class="input-titile">出生年月</view>
                <input
                    class="input-con triangle pointEveNone"
                    v-model="fromValue.birthDate"
                    disabled
                    placeholder="请选择您的出生年月"
                />
            </view>
            <view class="content-input" @click="changeEducation">
                <view class="input-titile">学历</view>
                <input
                    class="input-con triangle pointEveNone"
                    v-model="state.educationText"
                    disabled
                    placeholder="请选择您的学历"
                />
            </view>
            <view class="content-input" @click="changePoliticalAffiliation">
                <view class="input-titile">政治面貌</view>
                <input
                    class="input-con triangle pointEveNone"
                    v-model="state.politicalAffiliationText"
                    disabled
                    placeholder="请选择您的政治面貌"
                />
            </view>
            <view class="content-input">
                <view class="input-titile">手机号码</view>
                <input class="input-con" v-model="fromValue.phone" placeholder="请输入您的手机号码" />
            </view>
        </view>
    </AppLayout>
</template>

<script setup>
import { reactive, inject, watch, ref, onMounted } from 'vue';
import { onLoad, onShow } from '@dcloudio/uni-app';
const { $api, navTo, navBack, checkingPhoneRegExp } = inject('globalFunction');
import { storeToRefs } from 'pinia';
import useUserStore from '@/stores/useUserStore';
import useDictStore from '@/stores/useDictStore';
const { userInfo } = storeToRefs(useUserStore());
const { getUserResume } = useUserStore();
const { dictLabel, oneDictData } = useDictStore();
const openSelectPopup = inject('openSelectPopup');

const percent = ref('0%');
const state = reactive({
    educationText: '',
    politicalAffiliationText: '',
});
const fromValue = reactive({
    name: '',
    sex: 0,
    birthDate: '',
    education: '',
    politicalAffiliation: '',
    avatar: '',
});
onLoad(() => {
    initLoad();
    // setTimeout(() => {
    //     const { age, birthDate } = useUserStore().userInfo;
    //     const newAge = calculateAge(birthDate);
    //     // 计算年龄是否对等
    //     if (age != newAge) {
    //         completeResume();
    //     }
    // }, 1000);
});

function initLoad() {
    fromValue.name = userInfo.value.name;
    fromValue.sex = Number(userInfo.value.sex);
    fromValue.phone = userInfo.value.phone;
    fromValue.birthDate = userInfo.value.birthDate;
    fromValue.education = userInfo.value.education;
    fromValue.politicalAffiliation = userInfo.value.politicalAffiliation;
    fromValue.avatar = userInfo.value.avatar;
    // 回显
    state.educationText = dictLabel('education', userInfo.value.education);
    state.politicalAffiliationText = dictLabel('affiliation', userInfo.value.politicalAffiliation);
    const result = getFormCompletionPercent(fromValue);
    percent.value = result;
}
const confirm = () => {
    if (!fromValue.name) {
        return $api.msg('请输入姓名');
    }
    if (!fromValue.birthDate) {
        return $api.msg('请选择出生年月');
    }
    if (!fromValue.education) {
        return $api.msg('请选择学历');
    }
    if (!fromValue.politicalAffiliation) {
        return $api.msg('请选择政治面貌');
    }
    // if (!checkingPhoneRegExp(fromValue.phone)) {
    //     return $api.msg('请输入正确手机号');
    // }
    const params = {
        ...fromValue,
        age: calculateAge(fromValue.birthDate),
    };
    $api.createRequest('/app/user/resume', params, 'post').then((resData) => {
        $api.msg('完成');
        state.disbleDate = true;
        getUserResume().then(() => {
            navBack();
        });
    });
};

const changeDateBirt = () => {
    const datearray = generateDatePickerArrays();
    let defaultIndex = [0, 0, 0];
    if (fromValue.birthDate) {
        const defaultIndex = getDatePickerIndexes(fromValue.birthDate);
    }
    console.log(defaultIndex);
    openSelectPopup({
        title: '年龄段',
        maskClick: true,
        data: datearray,
        defaultIndex,
        success: (_, value) => {
            const [year, month, day] = value;
            const dateStr = `${year.value}-${month.value}-${day.value}`;
            if (isValidDate(dateStr)) {
                fromValue.birthDate = dateStr;
            } else {
                $api.msg('没有这一天');
            }
        },
    });
};
const changeEducation = () => {
    openSelectPopup({
        title: '学历',
        maskClick: true,
        data: [oneDictData('education')],
        success: (_, [value]) => {
            fromValue.education = value.value;
            state.educationText = value.label;
        },
    });
};
const changeSex = (sex) => {
    fromValue.sex = sex;
};

const changePoliticalAffiliation = () => {
    openSelectPopup({
        title: '政治面貌',
        maskClick: true,
        data: [oneDictData('affiliation')],
        success: (_, [value]) => {
            fromValue.politicalAffiliation = value.value;
            state.politicalAffiliationText = value.label;
        },
    });
};

function generateDatePickerArrays(startYear = 1975, endYear = new Date().getFullYear()) {
    const years = [];
    const months = [];
    const days = [];

    for (let y = startYear; y <= endYear; y++) {
        years.push(y.toString());
    }
    for (let m = 1; m <= 12; m++) {
        months.push(m.toString().padStart(2, '0'));
    }
    for (let d = 1; d <= 31; d++) {
        days.push(d.toString().padStart(2, '0'));
    }

    return [years, months, days];
}

function isValidDate(dateString) {
    const [year, month, day] = dateString.split('-').map(Number);

    const date = new Date(year, month - 1, day); // 月份从0开始
    return date.getFullYear() === year && date.getMonth() === month - 1 && date.getDate() === day;
}

const calculateAge = (birthDate) => {
    const birth = new Date(birthDate);
    const today = new Date();
    let age = today.getFullYear() - birth.getFullYear();
    const monthDiff = today.getMonth() - birth.getMonth();
    const dayDiff = today.getDate() - birth.getDate();

    // 如果生日的月份还没到，或者刚到生日月份但当天还没过，则年龄减 1
    if (monthDiff < 0 || (monthDiff === 0 && dayDiff < 0)) {
        age--;
    }

    return age;
};

function getFormCompletionPercent(form) {
    let total = Object.keys(form).length;
    let filled = 0;

    for (const key in form) {
        const value = form[key];
        if (value !== '' && value !== null && value !== undefined) {
            if (typeof value === 'number') {
                filled += 1;
            } else if (typeof value === 'string' && value.trim() !== '') {
                filled += 1;
            }
        }
    }

    if (total === 0) return '0%';
    const percent = (filled / total) * 100;
    return percent.toFixed(0) + '%'; // 取整，不要小数点
}
// 主函数
function getDatePickerIndexes(dateStr) {
    const [year, month, day] = dateStr.split('-');

    const [years, months, days] = generateDatePickerArrays();

    const yearIndex = years.indexOf(year);
    const monthIndex = months.indexOf(month);
    const dayIndex = days.indexOf(day);

    return [yearIndex, monthIndex, dayIndex];
}

function selectAvatar() {
    uni.chooseImage({
        sizeType: ['original', 'compressed'],
        sourceType: ['album', 'camera'],
        count: 1,
        success: ({ tempFilePaths, tempFiles }) => {
            $api.uploadFile(tempFilePaths[0], true)
                .then((res) => {
                    res = JSON.parse(res);
                    if (res.msg) fromValue.avatar = res.msg;
                })
                .catch((err) => {
                    $api.msg('上传失败');
                });
        },
        fail: (error) => {},
    });
}
</script>

<style lang="stylus" scoped>
.btn{
    margin-top: -30rpx
}
.content{
    padding: 28rpx;
    display: flex;
    flex-direction: column;
    justify-content: flex-start
    height: calc(100% - 120rpx)

}
.content-avatar{
    margin-bottom: 52rpx;
    padding-bottom: 28rpx
    display: flex;
    justify-content: space-between;
    align-items: center;
    border-bottom: 2rpx solid #EBEBEB
    .avatar-title{
        font-size: 30rpx;
        color #333;
    }
    .avatar{
        width:110rpx;
        height: 110rpx;
        border-radius: 50%;
    }
}
.content-input
    margin-bottom: 52rpx
    .input-titile
        font-weight: 400;
        font-size: 28rpx;
        color: #6A6A6A;
    .input-con
        font-weight: 400;
        font-size: 32rpx;
        color: #333333;
        line-height: 80rpx;
        height: 80rpx;
        border-bottom: 2rpx solid #EBEBEB
        position: relative;
    .triangle::before
        position: absolute;
        right: 20rpx;
        top: calc(50% - 2rpx);
        content: '';
        width: 4rpx;
        height: 18rpx;
        border-radius: 2rpx
        background: #697279;
        transform: translate(0, -50%) rotate(-45deg) ;
    .triangle::after
        position: absolute;
        right: 20rpx;
        top: 50%;
        content: '';
        width: 4rpx;
        height: 18rpx;
        border-radius: 2rpx
        background: #697279;
        transform: rotate(45deg)
.content-sex
    display: flex
    justify-content: space-between;
    align-items: flex-start;
    border-bottom: 2rpx solid #EBEBEB
    margin-bottom: 52rpx
    padding-bottom: 28rpx
    .sex-titile
        line-height: 80rpx;
    .sext-ri
        display: flex
        align-items: center;
        .sext-box
            height: 76rpx;
            width: 152rpx;
            text-align: center;
            line-height: 80rpx;
            border-radius: 12rpx 12rpx 12rpx 12rpx
            border: 2rpx solid #E8EAEE;
            margin-left: 28rpx
            font-weight: 400;
            font-size: 28rpx;
        .sext-boxactive
            color: #256BFA
            background: rgba(37,107,250,0.1);
            border: 2rpx solid #256BFA;
    .next-btn
        width: 100%;
        height: 90rpx;
        background: #256BFA;
        border-radius: 12rpx 12rpx 12rpx 12rpx;
        font-weight: 500;
        font-size: 32rpx;
        color: #FFFFFF;
        text-align: center;
        line-height: 90rpx
</style>
