<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-input" @click="changeSalary">
                <view class="input-titile">期望薪资</view>
                <input class="input-con triangle" v-model="state.salayText" disabled placeholder="请选择您的期望薪资" />
            </view>
            <view class="content-input" @click="changeArea">
                <view class="input-titile">期望工作地</view>
                <input
                    class="input-con triangle"
                    v-model="state.areaText"
                    disabled
                    placeholder="请选择您的期望工作地"
                />
            </view>
            <view class="content-input" @click="changeJobs">
                <view class="input-titile">求职岗位</view>
                <input
                    class="input-con triangle"
                    disabled
                    v-if="!state.jobsText || !state.jobsText.length"
                    placeholder="请选择您的求职岗位"
                />
                <view class="input-nx" @click="changeJobs" v-else>
                    <view class="nx-item button-click" v-for="item in state.jobsText">{{ item }}</view>
                </view>
            </view>
        </view>
        <SelectJobs ref="selectJobsModel"></SelectJobs>
        <SelectPopup ref="selectPopupRef"></SelectPopup>
    </AppLayout>
</template>

<script setup>
import { reactive, inject, watch, ref, onMounted, computed } from 'vue';
import { onLoad, onShow } from '@dcloudio/uni-app';
import SelectJobs from '@/components/selectJobs/selectJobs.vue';
import SelectPopup from '@/components/selectPopup/selectPopup.vue';
const { $api, navTo, navBack, config } = inject('globalFunction');

// 创建本地的 openSelectPopup 函数
const openSelectPopup = (config) => {
    if (selectPopupRef.value) {
        selectPopupRef.value.open(config);
    }
};
import { storeToRefs } from 'pinia';
import useUserStore from '@/stores/useUserStore';
import useDictStore from '@/stores/useDictStore';
const { userInfo } = storeToRefs(useUserStore());
const { getUserResume } = useUserStore();
const { dictLabel, oneDictData, getDictData } = useDictStore();

const selectJobsModel = ref();
const selectPopupRef = ref();
const percent = ref('0%');
const salay = [2000, 5000, 10000, 15000, 20000, 25000, 30000, 50000, 80000, 100000];
const state = reactive({
    lfsalay: [2000, 5000, 10000, 15000, 20000, 25000, 30000, 50000],
    risalay: JSON.parse(JSON.stringify(salay)),
    salayText: '',
    areaText: '',
    jobsText: [],
});
const fromValue = reactive({
    salaryMin: 0,
    salaryMax: 0,
    area: '',
    jobTitleId: [],
});
const needSkill = ref(false);

onLoad(async (options) => {
    // 初始化字典数据
    await getDictData();
    initLoad();
    // 检查是否需要继续跳转到技能页面
    if (options && options.needSkill === 'true') {
        needSkill.value = true;
    }
});
const confirm = () => {
    if (!fromValue.jobTitleId) {
        return $api.msg('请选择您的求职岗位');
    }
    $api.createRequest('/app/user/resume', fromValue, 'post').then((resData) => {
        $api.msg('完成');
        state.disbleDate = true;
        getUserResume().then(() => {
            // 如果需要继续跳转到技能页面，则跳转到个人信息页面（携带 needSkill 标记，便于返回两级）
            if (needSkill.value) {
                navTo('/packageA/pages/personalInfo/personalInfo?needSkill=true');
            } else {
                navBack();
            }
        });
    });
};

watch(userInfo, (newValue, oldValue) => {
    initLoad();
});

function initLoad() {
    fromValue.salaryMin = userInfo.value.salaryMin;
    fromValue.salaryMax = userInfo.value.salaryMax;
    fromValue.area = userInfo.value.area;
    fromValue.jobTitleId = userInfo.value.jobTitleId;
    // 回显
    state.areaText = dictLabel('area', Number(userInfo.value.area));
    if (userInfo.value.salaryMin && userInfo.value.salaryMax) {
        state.salayText = `${userInfo.value.salaryMin}-${userInfo.value.salaryMax}`;
    } else {
        state.salayText = '';
    }
    state.jobsText = userInfo.value.jobTitle || [];
    const result = getFormCompletionPercent(fromValue);
    percent.value = result;
}

const changeSalary = () => {
    let leftIndex = 0;
    openSelectPopup({
        title: '薪资',
        maskClick: true,
        data: [state.lfsalay, state.risalay],
        unit: '元',
        success: (_, [min, max]) => {
            fromValue.salaryMin = min.value;
            fromValue.salaryMax = max.value;
            state.salayText = `${fromValue.salaryMin}-${fromValue.salaryMax}`;
        },
        change(e) {
            const salayData = e.detail.value;
            if (leftIndex !== salayData[0]) {
                const copyri = JSON.parse(JSON.stringify(salay));
                const [lf, ri] = e.detail.value;
                const risalay = copyri.slice(lf, copyri.length);
                // 更新右侧选项
                state.risalay = risalay;
                leftIndex = salayData[0];
            }
        },
    });
};

function changeArea() {
    openSelectPopup({
        title: '区域',
        maskClick: true,
        data: [oneDictData('area')],
        success: (_, [value]) => {
            fromValue.area = value.value;
            state.areaText = config.appInfo.areaName + '-' + value.label;
        },
    });
}

function changeJobs() {
    selectJobsModel.value?.open({
        title: '添加岗位',
        defaultId: fromValue.jobTitleId,
        success: (ids, labels) => {
            console.log(ids, labels);
            fromValue.jobTitleId = ids;
            state.jobsText = labels.split(',');
        },
        cancel: (ids, labels) => {
            console.log(ids, labels);
            // fromValue.jobTitleId = ids;
            // state.jobsText = labels.split(',');
        },
    });
}

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) + '%'; // 取整，不要小数点
}
</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-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
    height: 110rpx;
    display: flex
    justify-content: space-between;
    align-items: flex-start;
    border-bottom: 2rpx solid #EBEBEB
    margin-bottom: 52rpx
    .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
.input-nx
    position: relative
    border-bottom: 2rpx solid #EBEBEB
    padding-bottom: 30rpx
    display: flex
    flex-wrap: wrap
    .nx-item
        padding: 20rpx 28rpx
        width: fit-content
        border-radius: 12rpx 12rpx 12rpx 12rpx;
        border: 2rpx solid #E8EAEE;
        margin-right: 24rpx
        margin-top: 24rpx
</style>
