<script setup lang="ts">
    import { reactive, toRefs, ref } from 'vue'
    import { onLoad, onShow } from '@dcloudio/uni-app'
    import { useUserStore } from '@/store/modules/user'
    import { useGlobSetting } from '/@/hooks/setting'
    import * as LinghuoyonggongAPI from '@/api/model/linghuoyonggong'
    import * as UserInfoAPI from '@/api/model/userInfo'
    import { getCodeByText } from '@/utils/areaData'
    import { useDictStore } from '@/store/modules/dict'
    import { getText } from '@/utils/dict/area'
    import AreaPicker from '@/components/AreaPicker/index.vue'

    const dictStore = useDictStore()
    const userStore = useUserStore()
    const globSetting = useGlobSetting()
    
    const isSave = ref(false)

    onLoad((option) => {
        if (option.id) {
            isSave.value = false
            getDetails(option.id)
            uni.setNavigationBarTitle({ title: '用工需求详情' })
        } else {
            isSave.value = true
            getCurrentAddressInfo()
            uni.setNavigationBarTitle({ title: '发布招聘需求' })
        }
    })

    onShow(() => {
        initDict()
    })

    const pageData = reactive({
        loading: false,
        show: {
            time1: false,
            time2: false,
            area: false,
            urgentdegree: false,
            type: false,
        },
        options: {
            urgentdegree: [],
            type: [],
        },
        form: {
            id: '',
            name: '',
            content: '',
            workers: '',
            price: '',
            typeText: '',
            type: null,
            area: '',
            areaText: '',
            province: '',
            city: '',
            country: '',
            address: '',
            urgentdegreeText: '',
            urgentdegree: null,
            starttime: '',
            estimatedendtime: '',
            picture: null,
            pictureObj: null,
            longitude: '',
            latitude: '',
        },
        position: [],
        rules: [
            { name: 'type', rule: ['required'], msg: ['请选择用工类型'] },
            { name: 'name', rule: ['required'], msg: ['请输入招聘标题'] },
            { name: 'workers', rule: ['required'], msg: ['请输入招聘人数'] },
            { name: 'price', rule: ['required'], msg: ['请输入用工单价'] },
            { name: 'starttime', rule: ['required'], msg: ['请选择开始日期'] },
            { name: 'estimatedendtime', rule: ['required'], msg: ['请选择结束日期'] },
            { name: 'content', rule: ['required'], msg: ['请输入工作内容详情'] },
            { name: 'area', rule: ['required'], msg: ['请选择工作地区'] },
            { name: 'address', rule: ['required'], msg: ['请输入详细地址'] },
            { name: 'urgentdegree', rule: ['required'], msg: ['请选择紧急程度'] },
            { name: 'picture', rule: ['required'], msg: ['请上传招聘现场或环境图'] },
        ],
    })

    const { show, options, form } = toRefs(pageData)

    async function initDict() {
        pageData.options.urgentdegree = dictStore.getDictList.employment_urgent.map(i => ({ value: i.value, text: i.text }))
        pageData.options.type = dictStore.getDictList.employment_type.map(i => ({ value: i.value, text: i.text }))
    }

    function getCurrentAddressInfo() {
        const loc = uni.getStorageSync('location')
        if (!loc) return
        pageData.position = [loc.lon, loc.lat]
        UserInfoAPI.location({ lon: loc.lon, lat: loc.lat }).then((res) => {
            pageData.form.province = res.province
            pageData.form.city = res.city
            pageData.form.country = res.country
            pageData.form.areaText = `${res.province}/${res.city}/${res.country}`
            pageData.form.area = `${getCodeByText(res.province)},${getCodeByText(res.city)},${getCodeByText(res.country)}`
        })
    }

    function getDetails(id) {
        pageData.loading = true
        LinghuoyonggongAPI.employmentDetails({ id }).then((res) => {
            pageData.form = res
            pageData.form.areaText = getText(pageData.form.area, '/')
            pageData.form.urgentdegreeText = pageData.options.urgentdegree.find(i => i.value == res.urgentdegree)?.text
            pageData.form.typeText = pageData.options.type.find(i => i.value == res.type)?.text
            pageData.form.pictureObj = res.picture && parseUrlInfo(res.picture)
        }).finally(() => pageData.loading = false)
    }

    function parseUrlInfo(url) {
        const pathParts = url.split('/')
        const fileName = pathParts[pathParts.length - 1]
        const fileParts = fileName.split('.')
        const extname = fileParts[fileParts.length - 1]
        return { name: fileName, extname, url }
    }

    function handleAreaConfirm(e) {
        pageData.form.areaText = e.fullText
        pageData.form.area = e.fullCode
    }

    function handleChangeTime1(e) {
        pageData.form.starttime = e.result
        pageData.show.time1 = false
    }
    function handleChangeTime2(e) {
        pageData.form.estimatedendtime = e.result
        pageData.show.time2 = false
    }
    function handleChangetype(e) {
        pageData.form.type = e.value
        pageData.form.typeText = e.text
        pageData.show.type = false
    }
    function handleChangeUrgentdegree(e) {
        pageData.form.urgentdegree = e.value
        pageData.form.urgentdegreeText = e.text
        pageData.show.urgentdegree = false
    }
    
    function handleContact() {
        uni.makePhoneCall({
            phoneNumber: '10086' // 示例
        })
    }

    const toastRef = ref()
    const uploadRef = ref()
    function handleUpload(file) {
        uni.uploadFile({
            url: `${globSetting.apiUrl + globSetting.urlPrefix}/sys/common/upload`,
            filePath: file.tempFiles[0].path,
            name: 'file',
            formData: { biz: 'temp' },
            header: { 'X-Access-Token': userStore.getToken },
            success: (res) => {
                const data = JSON.parse(res.data)
                if (data.code === 200 || data.code === 0) {
                    toastRef.value.show({ type: 'success', text: '上传成功' })
                    pageData.form.picture = data.message
                }
            }
        })
    }
    function handleDelete() {
        pageData.form.picture = null
    }
    const formRef = ref()
    function submit() {
        if (!pageData.position.length && isSave.value) {
            toastRef.value.show({ type: 'error', text: '获取当前位置失败' })
            return
        }
        pageData.form.longitude = pageData.position[0]
        pageData.form.latitude = pageData.position[1]
        formRef.value.validator(pageData.form, pageData.rules, true).then((res) => {
            if (res.isPassed) {
                LinghuoyonggongAPI.employmentAdd(pageData.form).then(() => {
                    toastRef.value.show({ type: 'success', text: '招聘信息已发布' })
                    setTimeout(() => uni.navigateBack(), 1500)
                })
            }
        })
    }

    function getCurrentDate() {
        const date = new Date()
        return `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`
    }
</script>

<template>
    <view class="page">
        <!-- 发布编辑模式 -->
        <view v-if="isSave" class="container">
            <view class="form-banner">
                <text class="title">发布招聘需求</text>
                <text class="subtitle">填写精准信息，快速匹配优质劳动力</text>
            </view>

            <view class="form-content">
                <fui-form ref="formRef">
                    <!-- 基本职位信息 -->
                    <view class="section-card">
                        <view class="card-header">
                            <view class="line"></view>
                            <text>职位基础信息</text>
                        </view>
                        <fui-input label="用工类型" placeholder="请选择" v-model="form.typeText" @click="show.type = true" disabled required />
                        <fui-input label="招聘标题" placeholder="例如：水稻收割临时工" v-model="form.name" required maxlength="20" />
                        <fui-input label="招聘人数" type="number" placeholder="所需人员数量" v-model="form.workers" required>
                            <template #suffix><text class="unit">人</text></template>
                        </fui-input>
                        <fui-input label="用工薪资" type="number" placeholder="单人日薪" v-model="form.price" required>
                            <template #suffix><text class="unit">元/天</text></template>
                        </fui-input>
                    </view>

                    <!-- 时间与地点 -->
                    <view class="section-card">
                        <view class="card-header">
                            <view class="line"></view>
                            <text>作业时间与地点</text>
                        </view>
                        <view class="form-row-item">
                            <text class="item-label"><text class="red">*</text>用工周期</text>
                            <view class="date-range-box">
                                <view class="date-picker" @click="show.time1 = true">
                                    <text :class="{ placeholder: !form.starttime }">{{ form.starttime || '开始日期' }}</text>
                                </view>
                                <text class="sep">至</text>
                                <view class="date-picker" @click="show.time2 = true">
                                    <text :class="{ placeholder: !form.estimatedendtime }">{{ form.estimatedendtime || '结束日期' }}</text>
                                </view>
                            </view>
                        </view>
                        <fui-input label="所在地区" v-model="form.areaText" @click="show.area = true" disabled required />
                        <fui-input label="详细地址" placeholder="作业的具体街道、村组" v-model="form.address" required />
                        <fui-input label="紧急程度" v-model="form.urgentdegreeText" @click="show.urgentdegree = true" disabled required />
                    </view>

                    <!-- 详情与图片 -->
                    <view class="section-card">
                        <view class="card-header">
                            <view class="line"></view>
                            <text>工作内容描述</text>
                        </view>
                        <fui-textarea placeholder="请详细描述工作内容、技能要求、供餐情况等..." v-model="form.content" height="200rpx" background="#f9f9f9" radius="16" :padding="['24rpx','24rpx']" />
                        
                        <view class="upload-box">
                            <text class="upload-label"><text class="red">*</text>工作环境图片</text>
                            <uni-file-picker limit="1" @select="handleUpload" @delete="form.picture = null" />
                        </view>
                    </view>

                    <view class="submit-area">
                        <fui-button text="确认并发布" radius="100rpx" background="#5db66f" @click="submit" />
                    </view>
                </fui-form>
            </view>
        </view>

        <!-- 招聘详情模式 -->
        <view v-else class="job-detail">
            <view class="detail-banner">
                <image v-if="form.picture" :src="form.picture" mode="aspectFill" class="banner-img" />
                <view v-else class="banner-placeholder"><fui-icon name="picture" :size="80" color="#ddd"></fui-icon></view>
                <view class="urgent-badge" v-if="form.urgentdegree > 3">急聘</view>
            </view>
            <view class="info-card">
                <view class="price-row">
                    <text class="price">¥{{ form.price }}</text>
                    <text class="unit">元/人/天</text>
                </view>
                <text class="job-title">{{ form.name }}</text>
                <view class="tags-row">
                    <view class="tag green">{{ form.typeText }}</view>
                    <view class="tag blue">需{{ form.workers }}人</view>
                    <view class="tag orange">{{ form.urgentdegreeText }}</view>
                </view>
            </view>
            <view class="detail-section">
                <view class="section-title">工作内容</view>
                <text class="content-text">{{ form.content }}</text>
            </view>
            <view class="detail-section">
                <view class="section-title">招工信息</view>
                <view class="meta-list">
                    <view class="meta-item">
                        <fui-icon name="time" :size="32" color="#999"></fui-icon>
                        <view class="meta-body">
                            <text class="label">用工周期</text>
                            <text class="value">{{ form.starttime }} 至 {{ form.estimatedendtime }}</text>
                        </view>
                    </view>
                    <view class="meta-item">
                        <fui-icon name="location" :size="32" color="#999"></fui-icon>
                        <view class="meta-body">
                            <text class="label">工作地点</text>
                            <text class="value">{{ form.areaText }} {{ form.address }}</text>
                        </view>
                    </view>
                </view>
            </view>
            <view class="bottom-bar">
                <view class="apply-btn" @click="handleContact">立即应聘</view>
            </view>
        </view>

        <!-- 选择器组件 -->
        <fui-date-picker :show="show.time1" type="3" @change="handleChangeTime1" @cancel="show.time1 = false" />
        <fui-date-picker :show="show.time2" type="3" @change="handleChangeTime2" @cancel="show.time2 = false" />
        <fui-picker :show="show.type" :options="options.type" @change="handleChangetype" @cancel="show.type = false" />
        <fui-picker :show="show.urgentdegree" :options="options.urgentdegree" @change="handleChangeUrgentdegree" @cancel="show.urgentdegree = false" />
        <AreaPicker v-model:show="show.area" :layer="3" title="选择工作地区" @confirm="handleAreaConfirm" />
        <fui-toast ref="toastRef" />
    </view>
</template>

<style lang="scss" scoped>
    .page {
        min-height: 100vh;
        background-color: #f4f7f5;
        font-family: 'DingTalk Sans', sans-serif;
    }

    /* 发布表单样式 */
    .container {
        .form-banner {
            background-color: #5db66f;
            padding: 60rpx 40rpx 100rpx;
            color: #fff;
            .title { font-size: 48rpx; font-weight: bold; display: block; letter-spacing: 2rpx; }
            .subtitle { font-size: 26rpx; opacity: 0.9; margin-top: 12rpx; display: block; }
        }
        .form-content { padding: 24rpx; margin-top: -80rpx; position: relative; z-index: 10; }
    }

    .section-card {
        background-color: #fff; border-radius: 28rpx; padding: 32rpx; margin-bottom: 28rpx;
        box-shadow: 0 8rpx 20rpx rgba(0,0,0,0.03);
        .card-header {
            margin-bottom: 32rpx; display: flex; align-items: center;
            .line { width: 8rpx; height: 32rpx; background-color: #5db66f; border-radius: 4rpx; margin-right: 16rpx; }
            text { font-size: 32rpx; font-weight: bold; color: #1a1a1a; }
        }
    }

    .form-row-item {
        padding: 32rpx 0; border-bottom: 1rpx solid #f8f8f8;
        .item-label { font-size: 28rpx; color: #333; margin-bottom: 24rpx; display: block; .red { color: #ff4d4f; margin-right: 4rpx; } }
        .date-range-box {
            display: flex; align-items: center; justify-content: space-between;
            .date-picker {
                flex: 1; height: 80rpx; background-color: #f9f9f9; border-radius: 16rpx;
                display: flex; align-items: center; padding: 0 24rpx; font-size: 28rpx;
                .placeholder { color: #ccc; }
            }
            .sep { margin: 0 24rpx; color: #94a3b8; font-size: 24rpx; font-weight: bold; }
        }
    }

    .upload-box {
        margin-top: 32rpx;
        .upload-label { font-size: 28rpx; color: #333; margin-bottom: 24rpx; display: block; .red { color: #ff4d4f; margin-right: 4rpx; } }
    }

    .submit-area { 
        padding: 60rpx 20rpx 100rpx;
        :deep(.fui-button) {
            box-shadow: 0 8rpx 24rpx rgba(93, 182, 111, 0.3);
        }
    }
    .unit { font-size: 26rpx; color: #999; margin-left: 12rpx; font-weight: 500; }

    /* 详情样式 (同步优化字体) */
    .job-detail {
        font-family: 'DingTalk Sans', sans-serif;
        .detail-banner {
            width: 750rpx; height: 450rpx; position: relative;
            .banner-img { width: 100%; height: 100%; }
            .urgent-badge { position: absolute; right: 30rpx; top: 30rpx; background: #ff4d4f; color: #fff; padding: 8rpx 24rpx; border-radius: 30rpx; font-size: 24rpx; font-weight: bold; box-shadow: 0 4rpx 12rpx rgba(255,77,79,0.4); }
        }
        .info-card {
            background: #fff; margin: -40rpx 24rpx 24rpx; padding: 40rpx 32rpx; border-radius: 32rpx; box-shadow: 0 8rpx 30rpx rgba(0,0,0,0.05); position: relative;
            .price-row { display: flex; align-items: baseline; margin-bottom: 20rpx; .price { font-size: 52rpx; color: #ff4d4f; font-weight: bold; } .unit { font-size: 24rpx; color: #999; margin-left: 10rpx; } }
            .job-title { font-size: 38rpx; font-weight: bold; color: #1a1a1a; line-height: 1.4; display: block; }
            .tags-row { margin-top: 28rpx; display: flex; flex-wrap: wrap; .tag { padding: 6rpx 20rpx; font-size: 22rpx; border-radius: 8rpx; margin-right: 16rpx; margin-bottom: 12rpx; &.green { background: #e6f5e8; color: #5db66f; } &.blue { background: #e6f7ff; color: #1890ff; } &.orange { background: #fff7e6; color: #fa8c16; } } }
        }
        .detail-section {
            background: #fff; margin: 0 24rpx 24rpx; padding: 32rpx; border-radius: 32rpx;
            .section-title { font-size: 30rpx; font-weight: bold; color: #1a1a1a; padding-left: 16rpx; border-left: 8rpx solid #5db66f; margin-bottom: 28rpx; }
            .content-text { font-size: 28rpx; color: #475569; line-height: 1.7; text-align: justify; }
            .meta-list { .meta-item { display: flex; align-items: center; padding: 24rpx 0; border-bottom: 1rpx solid #f8f8f8; &:last-child { border-bottom: none; } .meta-body { margin-left: 28rpx; .label { font-size: 22rpx; color: #94a3b8; display: block; } .value { font-size: 28rpx; color: #1e293b; margin-top: 6rpx; font-weight: 500; display: block; } } } }
        }
        .bottom-bar { position: fixed; bottom: 0; left: 0; right: 0; height: 110rpx; background: rgba(255,255,255,0.9); backdrop-filter: blur(10px); padding: 0 40rpx; display: flex; align-items: center; box-shadow: 0 -10rpx 30rpx rgba(0,0,0,0.05); z-index: 100; .apply-btn { flex: 1; height: 80rpx; background: #5db66f; color: #fff; border-radius: 40rpx; display: flex; align-items: center; justify-content: center; font-size: 28rpx; font-weight: bold; box-shadow: 0 8rpx 20rpx rgba(93, 182, 111, 0.3); } }
    }

    :deep(.fui-form__item) { background: transparent; border: none; padding: 0; }

    /* 统一字体穿透优化 */
    :deep(.fui-input__label), 
    :deep(.fui-input__input),
    :deep(.fui-textarea__textarea),
    :deep(.fui-textarea__label) {
        font-family: 'DingTalk Sans', system-ui !important;
        color: #333 !important;
    }
    
    :deep(.uni-input-placeholder),
    :deep(.uni-textarea-placeholder) {
        font-family: 'DingTalk Sans' !important;
        font-size: 28rpx !important;
    }

    :deep(.fui-button) {
        font-family: 'DingTalk Sans' !important;
        font-weight: bold !important;
    }
</style>
