<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 nongjifuwu from '@/api/model/nongjifuwu'
    import { getDictData, getText } from '@/utils/dict/area'
    
    const userStore = useUserStore()
    const globSetting = useGlobSetting()
    onLoad((option) => {
        pageData.form.type = option.type
        // 获取数据详情
        if (option.id) {
            pageData.title = '查看农活详情'
            getDetails(option.id)
        } else {
            pageData.title = '新增农活作业'
        }
		getProvince(43,null);
        uni.setNavigationBarTitle({
            title: pageData.title,
        })
    })

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

    const pageData = reactive({
        title: '农活表单',
        loading: false,
        show: {
            time1: false,
            time2: false,
            address: false,
        },
		options: [],
		optionsVal:[],
		optionsValText:"",
		
        form: {
            id: '',
            name: '',
            type: '',
            scope: '',
            address: '',
            phone: '',
            demand: '',
            startTime: '',
            endTime: '',
            picture: '',
            pictureObj: null,
        },
        rules: [
            {
                name: 'name',
                rule: ['required'],
                msg: ['请填写服务名称'],
            },
            {
                name: 'scope',
                rule: ['required'],
                msg: ['请选择服务范围'],
            },
            {
                name: 'address',
                rule: ['required'],
                msg: ['请填写详细地址'],
            },
            {
                name: 'phone',
                rule: ['required'],
                msg: ['请填写联系方式'],
            },
            {
                name: 'demand',
                rule: ['required'],
                msg: ['请填写作业需求'],
            },
            {
                name: 'startTime',
                rule: ['required'],
                msg: ['请选择开始时间'],
            },
            {
                name: 'endTime',
                rule: ['required'],
                msg: ['请选择结束时间'],
            },
        ],
    })

    const { show, options, form } = toRefs(pageData)
	
	const areaPopupRef = ref(null);
	// 选择地区完成
	function selectCompleteArea(e){
		let text = e.text;
		let value = e.value;
		let areaText = "",areaVal="";
		for(let i = 0; i < (text.length-1);i++){
			areaText += text[i]+'/';
			areaVal += value[i]+',';
		}
		pageData.form.scope = areaVal.slice(0, -1);; // code
		pageData.optionsValText = areaText.slice(0, -1);;
		pageData.show.address = false;
	}
	// 在选择地区
	function changeArea(e){
		let val = e.value;
		getProvince(val,e);
	}
	// 获取下一级地区
	function getProvince(code,e) {
		LinghuoyonggongAPI.queryConditions({ parentCode : code}).then(res=>{
			if(res.length){
				let dataArr = [];
				for(let i = 0; i < res.length; i++){
					let obj = {text:"",value:""};
					obj.text = res[i].name;
					obj.value = res[i].code;
					dataArr.push(obj);
				}
				if(!pageData.options.length){
					pageData.options = dataArr;
				}else{
					console.log("e.layer= "+ e.layer);
					areaPopupRef.value.setRequestData(dataArr, e.layer);
					if(e.layer >= 2){
						areaPopupRef.value.end();
					}
				}
			}else{
				areaPopupRef.value.end();
			}
		})
	}

    function getDetails(id) {
        pageData.loading = true
        nongjifuwu
            .farmMachineDetails({ id })
            .then((res) => {
                console.log(res)
                pageData.form = res
                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.endTime = e.result
        pageData.show.time2 = false
    }

    function handleChangeAddress(e) {
        pageData.form.scope = e.value.join(',')
        pageData.show.address = 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: () => {
                toastRef.value.show({
                    type: 'error',
                    text: '上传失败',
                })
                uploadRef.value.clearFiles()
                pageData.form.picture = null
            },
        })
    }
    // 文件删除
    function handleDelete() {
        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) {
                nongjifuwu.farmMachineAddFarm(pageData.form).then(() => {
                    toastRef.value.show({
                        type: 'success',
                        text: '发布成功',
                    })
                    uni.redirectTo({
                        url: '/pages/nongjifuwu/nongjifuwu',
                    })
                })
            }
        })
    }

    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.name" labelSize="28" label-width="180" maxlength="16" />
                    <view class="form-item required flex align-center" style="padding: 20rpx 10rpx">
                        <text class="label">服务范围</text>
                        <view class="time-input" @click="show.address = true">
                            <text class="select-text" :class="{ placeholder: !pageData.form.scope }">
                                {{ pageData.optionsValText || '请选择市/区县/乡镇' }}
                            </text>
                        </view>
                    </view>
                    <fui-input required label="详细地址" placeholder="请输入详细地址" v-model="form.address" labelSize="28" label-width="180" size="28"/>
                    <fui-input required type="number" label="联系方式" placeholder="请填写联系方式" v-model="form.phone" labelSize="28" label-width="180" :maxlength="11" />
                </view>
                <view class="mt20">
                    <fui-textarea flexStart required label="作业需求" placeholder="请输入作业需求" v-model="form.demand" labelSize="28" label-width="180" placeholder-style="font-size: 28rpx;"/>
                    <!-- 作业时间 -->
                    <view class="form-section" style="padding: 0 10rpx">
                        <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.endTime }">
                                        {{ form.endTime || '结束时间' }}
                                    </text>
                                </view>
                            </view>
                        </view>
                    </view>
                </view>

                <view class="bg-white mt20" style="padding: 0.875rem 1rem">
                    <view class="mb-1 flex justify-start" style="font-size:28rpx;"><span class="text-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>
            <fui-date-picker :show="show.time1" type="3" @change="handleChangeTime1" @cancel="show.time1 = false" :minDate="getCurrentDate()" />
            <fui-date-picker :show="show.time2" type="3" @change="handleChangeTime2" @cancel="show.time2 = false" :minDate="getCurrentDate()" />
            <fui-toast ref="toastRef" />
            <fui-loading isFixed v-if="pageData.loading" backgroundColor="rgba(0, 0, 0, 0.4)" />
			
			
            <!-- <fui-picker :show="show.address" :options="options.address" :linkage="true" :layer="3" @change="handleChangeAddress" @cancel="show.address = false" />
			 -->
			 <fui-bottom-popup :show="pageData.show.address">
				<view class="fui-scroll__wrap yr-select-area">
					<view class="fui-title">请选择</view>
					<fui-cascader ref="areaPopupRef" :value="pageData.optionsVal" stepLoading @change="changeArea" @complete="selectCompleteArea" :options="pageData.options"></fui-cascader>
					<view class="fui-icon__close" @tap.stop="pageData.show.address = false">
						<fui-icon name="close" :size="48"></fui-icon>
					</view>
				</view>
			</fui-bottom-popup>
			
        </view>
    </view>
</template>

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

    .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: #5db66f;
            border-radius: 44rpx;
            color: #ffffff;
            font-size: 32rpx;
            font-weight: 500;
            border: none;

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

    :deep(.fui-button) {
        border-color: #5db66f !important;
        background: #5db66f !important;
    }

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

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

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

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

        &.placeholder {
            color: #999999;
        }
    }

    .select-input {
        flex: 1;
        border-radius: 8rpx;
        padding: 0 20rpx;
        display: flex;
        align-items: center;
        justify-content: space-between;
        cursor: pointer;
    }

    .select-text {
        font-size: 28rpx;
        color: #333333;
        padding: 0 20rpx;
        &.placeholder {
            color: #999999;
        }
    }
</style>
