<template>
    <div class="page">
        <NavBar :showIcon="false" :showTitle="false" title="" backgroundBox="#FFFFFF"></NavBar>
        <div class="form">
            <div class="from-item" v-for="(item, index) in postItem" :key="index + Math.random()">
                <div class="title">
                    <view>添加岗位信息{{ index + 1 }}</view>
                    <wd-icon v-if="index > 0" @click="deleteItem(index)" name="close-outline" size="34rpx"></wd-icon>
                </div>
                <formItem full title="岗位名称">
                    <input
                        type="text"
                        @input="changeInput($event, 'jobName', index)"
                        v-model="item.jobName"
                        placeholder="请填写岗位名称"
                    />
                </formItem>
                <formItem title="招聘人数">
                    <input
                        type="number"
                        @input="changeInput($event, 'recruitmentNumber', index)"
                        v-model="item.recruitmentNumber"
                        placeholder="请填写招聘的人数"
                    />
                </formItem>
                <formItem title="年龄要求">
                    <wd-col-picker
                        v-model="age"
                        :columns="ageColumns"
                        :close-on-click-modal="false"
                        :column-change="changeAge"
                        @confirm="confirmAge"
                        use-default-slot
                    >
                        <view :class="`inner flex-between ${item.ageText ? '' : 'placeholder'}`" @tap="changePicker(index)">
                            {{ item.ageText || "请选择年龄要求" }}
                            <view class="arrow"></view>
                        </view>
                    </wd-col-picker>
                </formItem>
                <formItem title="学历要求">
                    <wd-picker
                        :columns="educationColumns"
                        value-key="code"
                        label-key="text"
                        v-model="item.educationRequirement"
                        @confirm="confirmEducation"
                        use-default-slot
                    >
                        <view :class="`inner flex-between ${item.educationText ? '' : 'placeholder'}`" @tap="changePicker(index)">
                            <view class="flex-align-center" bind:tap="onShowIdentitySelect">
                                {{ item.educationText || "请选择学历" }}
                            </view>
                            <view class="arrow"></view>
                        </view>
                    </wd-picker>
                </formItem>

                <formItem title="薪资待遇"
                    ><view :class="`inner flex-between ${item.salaryText ? '' : 'placeholder'}`" @click="onOpen(index)">
                        {{ item.salaryText || "请选择月薪范围" }}
                        <!-- <checkbox class="checkbox" @click="onChecked" :checked="my">面议</checkbox> -->
                    </view>
                    <wd-popup
                        v-model="show"
                        position="bottom"
                        custom-style="height:40%;border-radius: 20rpx;z-index:999;"
                        @close="handleClose"
                    >
                        <view class="title-box"
                            ><view></view>
                            <view class="title">薪资选择</view>
                            <wd-icon @click="handleClose" name="close" size="30rpx"></wd-icon>
                        </view>
                        <wd-picker-view
                            @change="handleConfirm"
                            use-default-slot
                            :columns="salaryColumns"
                            v-model="moneyValue"
                        ></wd-picker-view>
                        <view style="width: 100%; display: flex; justify-content: center"
                            ><wd-button :data-index="index" style="width: 80%" @click="handleClose" block :round="false"
                                >确定</wd-button
                            ></view
                        >
                    </wd-popup>
                    <!-- <wd-col-picker
                        v-model="salary"
                        :columns="salaryColumns"
                        :column-change="changeSalary"
                        @confirm="confirmSalary"
                        use-default-slot
                    >
                        <view :class="`inner flex-between ${salaryText ? '' : 'placeholder'}`" bind:tap="onOpen">
                            {{ salaryText || "请选择薪资" }}
                            <view class="arrow"></view>
                        </view>
                    </wd-col-picker> -->
                </formItem>
                <formItem title="是否提供食宿" full>
                    <wd-radio-group shape="dot" inline v-model="item.accommodation">
                        <wd-radio v-for="v in EnumAccommodation" :key="v.code" :value="v.code">{{ v.text }}</wd-radio>
                    </wd-radio-group>
                </formItem>
                <formItem title="是否缴纳五险一金" full>
                    <wd-radio-group shape="dot" inline v-model="item.socialInsurance">
                        <wd-radio value="1">是</wd-radio>
                        <wd-radio value="0">否</wd-radio>
                    </wd-radio-group>
                </formItem>
                <formItem title="岗位专业(技能)要求" full>
                    <textarea v-model="item.skills" placeholder="请输入岗位专业(技能)要求" />
                </formItem>
                <!-- <formItem title="备注" full>
                    <input v-model="postItem.socialInsurance" placeholder="请填写" />
                </formItem> -->
            </div>
        </div>
        <wd-tabbar
            @tap="next"
            custom-style="display: flex;justify-content: center !important;z-index:1;"
            fixed
            placeholder
            safeAreaInsetBottom
        >
            <view class="footer">
                <button class="foot-btn1" @click="addPost">继续添加</button>
                <button class="foot-btn" @click="openMask">提交报名</button></view
            >
        </wd-tabbar>
    </div>
</template>

<script setup>
import { ref } from "vue";
import { getEumData } from "@/utils/utils";
import formItem from "./formItem.vue";
import { useStore } from "./store";
const pinias = useStore();
import { jobFairRegisterApi } from "@/api/article";
let my = ref(false);
let moneyValue = ref([]);
let currentIndex = ref(0);
const show = ref(false);
const postItem = ref([
    {
        jobName: "",
        recruitmentNumber: 1, //身份
        minAgeRequirement: 0, //最小年龄
        maxAgeRequirement: 0, //最大年龄
        educationRequirement: "0", //学历要求EnumEducationRequirement
        minSalary: 1000, //最低薪资
        maxSalary: 1000, //最高薪资
        socialInsurance: "1",
        ageText: null,
        educationText: null,
        accommodation: "0", //是否提供食宿EnumAccommodation
        skills: "" //"岗位专业(技能)要求
    }
]);
/* 年龄 */
const age = ref([]);
const ageText = ref("不限");
const ageColumns = ref([]);
const changeAge = ({ selectedItem, resolve, finish }) => {
    if (selectedItem.next) {
        const temp = [];
        for (let i = 16; i < 50; i++) {
            temp.push({
                value: i + selectedItem.value,
                label: i + selectedItem.value + "岁",
                next: false
            });
            resolve(temp);
        }
    } else {
        postItem.value[currentIndex.value].minAgeRequirement = 0;
        postItem.value[currentIndex.value].maxAgeRequirement = 0;
        postItem.value[currentIndex.value].ageText = "不限";
        finish();
    }
};
function deleteItem(index) {
    postItem.value.splice(index, 1);
}
function onOpen(index) {
    currentIndex.value = index;
    show.value = true;
    my.value = false;
}
function changePicker(index) {
    currentIndex.value = index;
    console.log("currentIndex.value", currentIndex.value);
}
function onChecked() {
    my.value = !my.value;
    // 如果勾选了面议
    if (my.value) {
        // postItem
        salaryText.value = "";
        postItem.value[currentIndex.value].minSalary = 0;
        postItem.value[currentIndex.value].maxSalary = 0;
    } else {
        postItem.value[currentIndex.value].minSalary = "";
        postItem.value[currentIndex.value].maxSalary = "";
    }
}
const confirmAge = ({ value, selectedItems }) => {
    const [min, max] = value;
    if (max) {
        postItem.value[currentIndex.value].minAgeRequirement = min;
        postItem.value[currentIndex.value].maxAgeRequirement = max;
    } else {
        postItem.value[currentIndex.value].minAgeRequirement = 0;
        postItem.value[currentIndex.value].maxAgeRequirement = 0;
        postItem.value[currentIndex.value].ageText = "不限";
    }
    postItem.value[currentIndex.value].ageText = selectedItems.map(v => v.label).join("~");
};
function changeInput(e, type, index) {
    let { value } = e.detail;
    currentIndex.value = index;
    postItem.value[index][type] = value;
}
const initAgeColumns = () => {
    const temp = [
        {
            value: 0,
            label: "不限",
            next: false
        }
    ];
    for (let i = 16; i < 50; i++) {
        temp.push({
            value: i,
            label: i + "岁",
            next: true
        });
    }
    ageColumns.value.push(temp);
};
initAgeColumns();

/* 学历 */
const educationColumns = ref([]);
const educationText = ref("不限");
const initEducationColumns = async () => {
    educationColumns.value = await getEumData("EnumEducationRequirement");
};
const confirmEducation = ({ selectedItems }) => {
    postItem.value[currentIndex.value].educationText = selectedItems.text;
};
initEducationColumns();

/* 薪水 */
const salary = ref([]);
const salaryText = ref("1K");
const salaryColumns = ref([]);
const changeSalary = ({ selectedItem, resolve, finish }) => {
    if (selectedItem.next) {
        const temp = [];
        for (let i = 1; i < 50; i++) {
            temp.push({
                value: i * 1000 + selectedItem.value,
                label: i * 1000 + selectedItem.value,
                next: false
            });
            resolve(temp);
        }
    } else {
        finish();
    }
};
const initsalaryColumns = () => {
    let multiple = 1000;
    const temp = [];

    // 生成序列
    for (let i = 1; i <= 50; i++) {
        const currentValue = i * multiple;
        temp.push({
            value: currentValue,
            label: currentValue / multiple + "K",
            next: true
        });
    }

    // 确保 columns.value 是一个数组
    if (!Array.isArray(salaryColumns.value)) {
        salaryColumns.value = [];
    }

    // 清空原来的数组，以确保只包含新的数据
    salaryColumns.value.length = 0;

    // 将 temp 复制两次，推入 columns.value
    salaryColumns.value.push([...temp], [...temp]);
};

function handleClose() {
    if (moneyValue.value[1] < moneyValue.value[0]) {
        xma.showToast({
            title: "最高薪资不能小于最低薪资",
            icon: "none"
        });
        return;
    }
    postItem.value[currentIndex.value].maxSalary = moneyValue.value[1];
    postItem.value[currentIndex.value].minSalary = moneyValue.value[0];

    show.value = false;
}
function changeIndex(index) {
    currentIndex = index;
    console.log("currentIndex", currentIndex);
}
const handleConfirm = ({ selectedItem, value }) => {
    if (value[1] < value[0]) {
        xma.showToast({
            title: "最高薪资不能小于最低薪资",
            icon: "none"
        });
        return;
    } else {
        postItem.value[currentIndex.value].maxSalary = moneyValue.value[1];
        postItem.value[currentIndex.value].minSalary = moneyValue.value[0];
    }

    // my.value = false;

    postItem.value[currentIndex.value].salaryText = value.map(num => `${num / 1000}k`).join("~");
};
initsalaryColumns();
/* 是否提供食宿  */
const EnumAccommodation = ref([]);
const initEnumAccommodation = async () => {
    EnumAccommodation.value = await getEumData("EnumAccommodation");
};
initEnumAccommodation();
/* 添加 */
const addPost = () => {
    /* 数据清空 */
    postItem.value.push({
        jobName: "",
        recruitmentNumber: 1, //身份
        minAgeRequirement: 0, //最小年龄
        maxAgeRequirement: 0, //最大年龄
        educationRequirement: "0", //学历要求EnumEducationRequirement
        minSalary: 1000, //最低薪资
        maxSalary: 1000, //最高薪资
        socialInsurance: "1",
        ageText: null,
        educationText: null,
        accommodation: "0", //是否提供食宿EnumAccommodation
        skills: "" //"岗位专业(技能)要求
    });
};
/* 提交 */
const openMask = () => {
    console.log("postItem.value", postItem.value);
    const result = postItem.value.every(item => {
        return validateForm(item, [
            "accommodation",
            "educationRequirement",
            "jobName",
            "maxAgeRequirement",
            "maxSalary",
            "minAgeRequirement",
            "minSalary",
            "recruitmentNumber",
            "skills",
            "socialInsurance"
        ]);
    });
    if (!result) {
        // 如果有任意一个 item 验证失败，则提示用户
        uni.showToast({
            title: `请填写完整`,
            icon: "none",
            duration: 2000
        });
        return false;
    } else {
        pinias.setFormDataKey("positionList", postItem.value);
        console.log("pinias.formData", pinias.formData);
        jobFairRegisterApi(pinias.formData).then(res => {
            if (res.code == 200) {
                postItem.value = [
                    {
                        jobName: "",
                        recruitmentNumber: 1, //身份
                        minAgeRequirement: 0, //最小年龄
                        maxAgeRequirement: 0, //最大年龄
                        educationRequirement: "0", //学历要求EnumEducationRequirement
                        minSalary: 1000, //最低薪资
                        maxSalary: 1000, //最高薪资
                        socialInsurance: "1",
                        ageText: null,
                        educationText: null,
                        accommodation: "0", //是否提供食宿EnumAccommodation
                        skills: "" //"岗位专业(技能)要求
                    }
                ];
                pinias.resetForm();
                xma.reLaunch({
                    url: "/pages/dynamic/index"
                });
            }
        });
    }
};
const validateForm = (formData, requiredFields) => {
    for (const field of requiredFields) {
        const value = formData[field];
        // 排除 0 和 "0" 的值，不作为空值校验
        if (value === undefined || value === null || value === "") {
            uni.showToast({
                title: `请填写${field}字段`,
                icon: "none",
                duration: 2000
            });
            return false;
        }
    }
    return true;
};
</script>

<style lang="scss" scoped>
@import "./index.scss";
.form {
    .grid {
        display: grid;
        grid-template-columns: 1fr 1fr;
        column-gap: 50rpx;
    }
    textarea {
        width: 100%;
        height: 140rpx;
    }
    .title-box {
        display: flex;
        align-items: center;
        justify-content: space-between;
        box-sizing: border-box;
        padding: 0 32rpx;
        .title {
            font-weight: bold;
            font-size: 32rpx;
        }
    }
    :deep(.uni-checkbox-input) {
        border-radius: 50% !important;
    }
}
.foot-btn {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 296rpx;
    height: 80rpx;
    color: #ffffff;
    background: #1f86ff;
    border-radius: 12rpx;
}
.foot-btn1 {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 296rpx;
    height: 80rpx;
    color: #1f86ff;
    background: #e8f2ff;
    border-radius: 12rpx;
}
.wrapper {
    width: 100%;
    height: 100%;
    .block {
        width: 600rpx;
        height: 496rpx;
        text-align: center;
        background: #ffffff;
        border-radius: 16rpx;
        img {
            width: 274rpx;
            height: 192rpx;
            margin-top: 50rpx;
            margin-bottom: 6;
        }
        p {
            font-size: 28rpx;
            font-weight: normal;
            line-height: 48rpx;
            color: #000000;
        }
        .btn {
            display: flex;
            margin-top: 40rpx;
            button {
                width: 236rpx;
                height: 80rpx;
                line-height: 80rpx;
            }
            .b1 {
                font-size: 30rpx;
                font-weight: 600;
                color: #1f86ff;
                background: #1f86ff0f;
                &::after {
                    border: 0;
                }
            }
            .b2 {
                font-size: 30rpx;
                font-weight: 600;
                color: #ffffff;
                background: #1f86ff;
            }
        }
    }
}
</style>
