<script setup lang="ts">
    import { reactive, toRefs } 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 { areaTree, getCodeByText, getTextByCode } from '@/utils/areaData'
    import { useDictStore } from '@/store/modules/dict'
    import { getDictData } from '@/utils/dict/area'

    const dictStore = useDictStore()
    const userStore = useUserStore()
    const globSetting = useGlobSetting()
    onLoad((option) => {
        // 获取数据详情
        if (option.id) {
            getDetails(option.id)
        } else {
            // 获取当前位置
            getCurrentAddressInfo()
        }
    })

    onShow(() => {
        // 数据字典赋值
        initDict()
    })

    const pageData = reactive({
        loading: false,
        show: {
            time1: false,
            time2: false,
            area: false,
            urgentdegree: false,
            type: false,
        },
        options: {
            area: [],
            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,
        },
        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.area = await getDictData()
        pageData.options.urgentdegree = dictStore.getDictList.employment_urgent.map((item) => {
            return {
                value: item.value,
                text: item.text,
            }
        })
        pageData.options.type = dictStore.getDictList.employment_type.map((item) => {
            return {
                value: item.value,
                text: item.text,
            }
        })
    }

    function getCurrentAddressInfo() {
        if (!uni.getStorageSync('location')) 
    return

        const { lon, lat } = uni.getStorageSync('location')
        UserInfoAPI.location({
            lon,
            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) => {
                console.log(res)
                pageData.form = res
                const areaCopy = pageData.form.area.split(',')
                pageData.form.areaText = `${getTextByCode(areaCopy[0])}/${getTextByCode(areaCopy[1])}/${getTextByCode(areaCopy[2])}`
                pageData.form.urgentdegreeText = pageData.options.urgentdegree.find(
                    (item) => item.value == pageData.form.urgentdegree,
                )?.text
                pageData.form.typeText = pageData.options.type.find((item) => item.value == pageData.form.type)?.text
                pageData.form.pictureObj = pageData.form.picture && parseUrlInfo(pageData.form.picture)
            })
            .finally(() => {
                pageData.loading = false
            })
    }

    function parseUrlInfo(url) {
        // 从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 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 handleChangeAddress(e) {
        pageData.form.areaText = e.text.join('/')
        pageData.form.area = e.value.join(',')
        pageData.show.area = false
    }
    const toastRef = ref()
    const uploadRef = ref()
    // 文件上传
    function handleUpload(file) {
        uni.uploadFile({
            url: `${globSetting.apiUrl + globSetting.urlPrefix}/sys/common/upload`, // 直接使用上传接口URL
            filePath: file.tempFiles[0].path,
            name: 'file',
            formData: {
                biz: 'temp',
            },
            header: {
                'X-Access-Token': userStore.getToken,
            },
            success: (res) => {
                if (res.statusCode === 200) {
                    const data = JSON.parse(res.data)
                    if (data.code === 200 || data.code === 0) {
                        toastRef.value.show({
                            type: 'success',
                            text: '上传成功',
                        })
                        pageData.form.picture = data.message // 保存返回的图片信息
                    }
                }
            },
            fail: (err) => {
                toastRef.value.show({
                    type: 'error',
                    text: '上传失败',
                })
                uploadRef.value.clearFiles()
                pageData.form.picture = null
            },
        })
    }
    // 文件删除
    function handleDelete(file) {
        uploadRef.value.clearFiles()
        pageData.form.picture = null
    }
    const formRef = ref()
    function submit() {
        formRef.value.validator(pageData.form, pageData.rules, true).then((res) => {
            if (res.isPassed) {
                LinghuoyonggongAPI.employmentAdd(pageData.form).then((res) => {
                    toastRef.value.show({
                        type: 'success',
                        text: '用工发布成功',
                    })
                    uni.switchTab({
                        url: '/pages/chanxiao/chanxiao',
                    })
                })
            }
        })
    }

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

<template>
    <view class="page">
        <view class="formBox">
            <fui-form ref="formRef" label-weight="auto" top="60" :disabled="form.id ? true : false">
                <view class="mt20">
                    <fui-input required label="用工类型" placeholder="请选择用工类型" v-model="form.typeText" labelSize="28" size="28" label-width="180" @click="show.type = true" />
                    <fui-input required label="标题" placeholder="请输入标题" v-model="form.name" labelSize="28" label-width="180" maxlength="16" size="28"/>
                </view>
                <view class="mt20">
                    <fui-input required type="number" :min="0" label="工人数量" placeholder="请输入工人数量" v-model="form.workers" labelSize="28" label-width="180" maxlength="4" size="28">
                        <view slot="suffix" class="unit-slot">人</view>
                    </fui-input>
                    <fui-input required type="number" label="用工单价" :min="0" placeholder="请输入用工单价" v-model="form.price" labelSize="28" label-width="180" maxlength="6" size="28">
                        <view slot="suffix" class="unit-slot">元/人</view>
                    </fui-input>
                    <!-- 时间范围 -->
                    <view class="form-section" style="padding: 0 30rpx">
                        <view class="form-item flex align-center">
                            <text class="label">用工时间</text>
                            <view class="time-range">
                                <view class="time-input" @click="show.time1 = true">
                                    <text class="time-text" :class="{ placeholder: !form.starttime }">
                                        {{ form.starttime || '开始时间' }}
                                    </text>
                                </view>
                                <text class="time-separator">至</text>
                                <view class="time-input" @click="show.time2 = true">
                                    <text class="time-text" :class="{ placeholder: !form.estimatedendtime }">
                                        {{ form.estimatedendtime || '结束时间' }}
                                    </text>
                                </view>
                            </view>
                        </view>
                    </view>
                    <fui-input required label="工作内容" placeholder="请输入工作内容" v-model="form.content" labelSize="28" label-width="180" maxlength="32" size="28" />
                </view>
                <view class="mt20">
                    <fui-input required label="地区" placeholder="请选择地区" v-model="form.areaText" labelSize="28" label-width="180" @click="show.area = true" size="28"/>
                    <fui-input required label="详细地址" placeholder="请输入详细地址" v-model="form.address" labelSize="28" label-width="180" size="28"/>
                    <fui-input required label="紧急程度" placeholder="请选择紧急程度" v-model="form.urgentdegreeText" labelSize="28" label-width="180" size="28" @click="show.urgentdegree = true" />
                </view>
                <view class="bg-white mt20" style="padding: 0.875rem 1rem">
                    <view class="mb-1 flex justify-start" style="font-size: 28rpx;"><span style="color: red;">*&nbsp;</span> 图片 </view>
                    <uni-file-picker :value="form.pictureObj" ref="uploadRef" limit="1" :auto-upload="false" @select="handleUpload" @delete="handleDelete"/>
                </view>
                <view class="fui-btn__box" v-if="!form.id" style="margin-top: 30rpx">
                    <fui-button text="发布用工" bold radius="96rpx" @click="submit" />
                </view>
            </fui-form>
        </view>
    </view>

    <fui-date-picker :show="show.time1" type="3" @change="handleChangeTime1" :min-date="getCurrentDate()" @cancel="show.time1 = false" />
    <fui-date-picker :show="show.time2" type="3" @change="handleChangeTime2" :min-date="getCurrentDate()" @cancel="show.time2 = false" />
    <fui-picker :show="show.type" :layer="1" :linkage="true" :options="options.type" @change="handleChangetype" @cancel="show.type = false" />
    <fui-picker :show="show.urgentdegree" :layer="1" :linkage="true" :options="options.urgentdegree" @change="handleChangeUrgentdegree" @cancel="show.urgentdegree = false"/>
    <fui-picker :show="show.area" :options="options.area" :linkage="true" :layer="3" @change="handleChangeAddress" @cancel="show.area = false" />
    <fui-toast ref="toastRef" />
    <fui-loading isFixed v-if="pageData.loading" backgroundColor="rgba(0, 0, 0, 0.4)" />
</template>

<style lang="scss" scoped>
    body {
        background-color: #e6f5e8;
    }

    .page {
        background-color: #e6f5e8;
        width: 750rpx;
        overflow-x: hidden;
        .mt20 {
            margin-top: 30rpx;
            background: #fff;
            padding: 20rpx;
            border-radius: 10rpx;
        }

        .formBox {
            width: 690rpx;
            margin: 30rpx auto;
        }

        .form-section {
            // border-bottom: 1rpx solid #f5f5f5;
        }

        .form-item {
            padding: 30rpx 0;
            border-bottom: 1rpx solid #f5f5f5;

            &:last-child {
                border-bottom: none;
            }

            &.required .label::before {
                content: '*';
                color: #ff4d4f;
                margin-right: 8rpx;
            }
        }

        .form-row {
            display: flex;
            justify-content: space-between;
        }

        .half-width {
            width: 48%;
        }

        .align-center {
            align-items: center;
        }

        .label {
            display: block;
            font-size: 28rpx;
            color: #333333;
            font-weight: 500;
            width: 180rpx;
        }

        .input {
            width: 100%;
            height: 80rpx;
            background: #f8f9fa;
            border-radius: 8rpx;
            padding: 0 20rpx;
            font-size: 28rpx;
            color: #333333;

            &::placeholder {
                color: #999999;
            }
        }

        .time-range {
            display: flex;
            align-items: center;
            justify-content: space-between;
        }

        .time-input {
            width: 45%;
            border-radius: 8rpx;
            display: flex;
            align-items: center;
        }

        .time-text {
            font-size: 28rpx;
            color: #333333;

            &.placeholder {
                color: #999999;
            }
        }

        .time-separator {
            color: #666666;
            font-size: 28rpx;
            margin: 0 10rpx;
        }

        .upload-area {
            margin-top: 10rpx;
        }

        .custom-uploader {
            :deep(.uni-file-picker__container) {
                border: 2rpx dashed #d9d9d9;
                border-radius: 8rpx;
                background: #f8f9fa;
            }
        }

        .upload-placeholder {
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            height: 200rpx;
            color: #999999;
        }

        .upload-icon {
            font-size: 48rpx;
            margin-bottom: 10rpx;
        }

        .upload-text {
            font-size: 24rpx;
        }

        .submit-section {
            background: transparent;
            padding: 40rpx 0;
        }

        .submit-btn {
            width: 100%;
            height: 88rpx;
            background: #ff9800;
            border-radius: 44rpx;
            color: #ffffff;
            font-size: 32rpx;
            font-weight: 500;
            border: none;

            &:active {
                background: #e68900;
                opacity: 0.9;
            }
        }
    }
    ::v-deep .uni-input-placeholder {
        font-size: 28rpx !important;
        color: #999999 !important;
    }

    // 移除fui-form的默认样式
    :deep(.fui-form) {
        background: transparent;
    }

    :deep(.fui-form__item) {
        background: transparent;
        border: none;
        margin-bottom: 0;
        padding: 0;
    }
    .unit-slot {
        padding: 0 16rpx;
        color: #333;
        font-size: 28rpx;
    }
</style>
