<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 * as NongzhiAPI from '@/api/model/nongzhi'
	
    import { useDictStore } from '@/store/modules/dict'

    const dictStore = useDictStore()
    const userStore = useUserStore()
    const globSetting = useGlobSetting()
    onLoad((option) => {
        // 获取数据详情
		getProvince(0,null);
    })

	
	//勾选协议校验
	function checkAgree(agree) {
		return agree
	}
	const areaPopupRef = ref(null);
    const pageData = reactive({
        loading: false,
        show: {
            time1: false,
            time2: false,
            area: false,
            urgentdegree: false,
            type: false,
        },
        options: {
            area: [],
			areaVal:[],
			
            urgentdegree: [],
            type: [],
        },
		
		cersImageIndex:0,
		cersImageArr:[],
		enterpriseLogoArr:[],
		
		selectAreaVal:[],
		
        form: {
            id: '',
			enterpriseName:"",// 企业名称
			enterpriseCode:"",// 企业编码
			businessScope:"", // 企业经营范围
			contactPerson:"", // 联系人
			contactMobile:"", // 联系人手机号
			profile:"", // 企业简介
			
			provinceName:"", // 省
			cityName:"", // 市
			districtName:"", // 区县
			townName:"", // 乡镇
			
			provinceCode:"", // 省
			cityCode:"", // 市
			districtCode:"", // 区县
			townCode:"", // 乡镇
			
			
			addr:"", // 详细地址
			lon:"", // 经度
			lat:'', // 纬度
			bizCategory: 3, // 业务分类【1:代理记账、2:农资、3:农机、4:金融】
			enterpriseLogoUrl:null, // 企业logo url
			enterpriseCers:null, // 企业资质url
			
			
			areaText: '',
			agree:false,
        },
        position: [],
        rules: [
			{
                name: 'enterpriseName',
                rule: ['required'],
                msg: ['请输入公司名称'],
            }, {
                name: 'enterpriseCode',
                rule: ['required'],
                msg: ['请输入企业编码'],
            }, {
                name: 'businessScope',
                rule: ['required'],
                msg: ['请输入经营业务'],
            },{
                name: 'profile',
                rule: ['required'],
                msg: ['请输入平台介绍'],
            },{
                name: 'areaText',
                rule: ['required'],
                msg: ['请选择地区'],
            },{
                name: 'addr',
                rule: ['required'],
                msg: ['请输入详细地址'],
            },{
                name: 'contactPerson',
                rule: ['required'],
                msg: ['请输入联系人'],
            },{
				name: "contactMobile",
				rule: ["required", "isMobile"],
				msg: ["请输入联系电话", "请输入正确的联系电话"]
			},{
                name: 'enterpriseLogoUrl',
                rule: ['required'],
                msg: ['请上传公司logo'],
            },{
                name: 'enterpriseCers',
                rule: ['required'],
                msg: ['请上传公司资质证件'],
            },{
				name: "agree",
				validator: [{
					msg: "请勾选并同意《入驻协议》与《服务条款》",
					method: checkAgree
				}]
			}
			
        ],
    })

	function agreeChange(e) {
		pageData.form.agree = e.checked;
	}
	// 选择地区完成
	function selectCompleteArea(e){
		let areaAttr = ['province','city','district','town'];
		let text = e.text;
		let value = e.value;
		let formData = pageData.form;
		for(let i = 0; i < text.length;i++){
			formData[areaAttr[i]+'Name'] = text[i];
			formData[areaAttr[i]+'Code'] = value[i];
		}
		pageData.form.areaText= text.join('');
		pageData.show.area = 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.area.length){
					pageData.options.area = dataArr;
				}else{
					areaPopupRef.value.setRequestData(dataArr, e.layer);
				}
			}else{
				areaPopupRef.value.end();
			}
		})
	}
	
    const { show, options, form } = toRefs(pageData)
    const toastRef = ref()
    const uploadLogoRef = ref()
	const uploadCersRef = ref()
    // 文件上传
    function handleUpload(file,type) {
		const tempFilePaths = file.tempFilePaths;
		// 处理每张选中的图片
		for(let i = 0; i < tempFilePaths.length; i++){
			uni.uploadFile({
			    url: `${globSetting.apiUrl + globSetting.urlPrefix}/sys/common/upload`, // 直接使用上传接口URL
			    filePath: tempFilePaths[i],
			    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: '上传成功',
			                })
							if(type == 'logo'){
								pageData.enterpriseLogoArr[0] = data.message // 保存返回的图片信息
							}else{
								pageData.cersImageIndex++;
								pageData.cersImageArr.push(data.message);
							}
			                
			            }
			        }
			    },
			    fail: (err) => {
			        toastRef.value.show({
			            type: 'error',
			            text: '上传失败',
			        })
					if(type == 'logo'){
						uploadLogoRef.value.clearFiles()
						pageData.enterpriseLogoArr[0] = null
					}else{
						uploadCersRef.value.clearFiles(pageData.cersImageIndex)
						pageData.form.enterpriseCers = null
					}
			        
			    },
			})
		}
    }
    // 文件删除
    function handleDelete(file,type) {
		if(type="logo"){
			uploadLogoRef.value.clearFiles()
			pageData.enterpriseLogoArr[0] = null
		}else{
			const num = pageData.cersImageArr.findIndex(v => v.url === file.tempFilePath);
			pageData.cersImageArr.splice(num, 1);
		}
    }
    const formRef = ref()
    function submit() {
		const { lon, lat } = uni.getStorageSync('location')
		pageData.position = [lon, lat];
		pageData.form.enterpriseLogoUrl = pageData.enterpriseLogoArr.join('');
		pageData.form.enterpriseCers = pageData.cersImageArr.join(',');
        if (pageData.position.length == 0) {
            toastRef.value.show({
                type: 'error',
                text: '无法获取位置',
            })
            return
        }
        pageData.form.lon = pageData.position[0]
        pageData.form.lat = pageData.position[1]
        formRef.value.validator(pageData.form, pageData.rules, true).then((res) => {
            if (res.isPassed) {
                NongzhiAPI.postEnterpriseAdd(pageData.form).then((res) => {
                    toastRef.value.show({
                        type: 'success',
                        text: '发布成功',
                    })
                	setTimeout(()=>{
                		uni.navigateBack({
                		    delta: 1 // 返回的页面数
                		})
                	},1000)
                })
            }
        })
    }

    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.enterpriseName" labelSize="28" label-width="180" size="28"/>
					<fui-input required label="企业编码" placeholder="请输入企业编码" v-model="form.enterpriseCode" labelSize="28" label-width="180" size="28"/>
					<fui-input required label="经营业务" placeholder="请输入经营业务" v-model="form.businessScope" labelSize="28" label-width="180" size="28"/>
					<fui-form-item asterisk label="平台介绍" :bottomBorder="false" prop="descr" error-align="left">
						<template v-slot:vertical>
							<fui-textarea isCounter maxlength="-1" :padding="['0','32rpx','32rpx']" :border-bottom="false" :border-top="false" size="28"
								placeholder="请输入平台介绍..." v-model="form.profile"></fui-textarea>
						</template>
					</fui-form-item>
                </view>
                <view class="mt20">
                    <fui-input required label="地区" placeholder="请选择地区" v-model="form.areaText" labelSize="28" label-width="180" @click="show.area = true" size="28" disabled/>
                    <fui-input required label="详细地址" placeholder="请输入详细地址" v-model="form.addr" labelSize="28" label-width="180" size="28"/>
                    <fui-input required label="联系人" placeholder="请输入联系人" v-model="form.contactPerson" labelSize="28" label-width="180" size="28"/>
                    <fui-input type="tel" required label="联系电话" placeholder="请输入联系电话" v-model="form.contactMobile" labelSize="28" label-width="180" size="28"></fui-input>
				</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> 公司logo </view>
                    <uni-file-picker :value="pageData.enterpriseLogoArr" ref="uploadLogoRef" limit="1" :auto-upload="false" @select="handleUpload($event,'logo')" @delete="handleDelete($event,'logo')"/>
                </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>
				    <view class="mb-1 flex justify-start" style="font-size: 24rpx;color: #CCCCCC;">前6张资质证件将展示在详情页，拖拽图片可自定义排序。</view>
				    <uni-file-picker limit="9" :value="pageData.cersImageArr" ref="uploadCersRef" :auto-upload="false" @select="handleUpload($event,'cers')" @delete="handleDelete($event,'cers')"/>
				</view>
				<view class="fui-clause--cell fui-clause--wrap">
					<fui-label>
						<view class="fui-clause--cell">
							<fui-checkbox :scaleRatio="0.8" @change="agreeChange"></fui-checkbox>
							<text class="fui-clause--text">我已阅读并同意</text>
						</view>
					</fui-label>
					<fui-text class="fui-color__link">《入驻协议》</fui-text>
					<text>与</text>
					<fui-text class="fui-color__link">《服务条款》</fui-text>
				</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-bottom-popup :show="show.area">
		<view class="fui-scroll__wrap">
			<view class="fui-title">请选择</view>
			<fui-cascader ref="areaPopupRef" :value="pageData.options.areaVal" stepLoading @change="changeArea" @complete="selectCompleteArea" :options="pageData.options.area"></fui-cascader>
			<view class="fui-icon__close" @tap.stop="pageData.show.area=false">
				<fui-icon name="close" :size="48"></fui-icon>
			</view>
		</view>
	</fui-bottom-popup>
	
	
    <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;
    }
	
	
	
	.fui-clause--cell {
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 24rpx;
		color:#999999;
	}
	.fui-clause--wrap {
		width: 100%;
		margin-top: 64rpx;
	}
	.fui-clause--text {
		padding-left: 16rpx;
		/* #ifdef H5 */
		cursor: pointer;
		/* #endif */
	}
	.fui-color__link {
		color: #5FB771;
		/* #ifdef H5 */
		cursor: pointer;
		/* #endif */
	}
	
	.fui-color__link:active {
		opacity: .5;
	}
	.fui-scroll__wrap {
		padding-top: 30rpx;
		position: relative;
	}
	
	.fui-title {
		font-size: 30rpx;
		font-weight: bold;
		text-align: center;
		padding-bottom: 24rpx;
	}
	
	.fui-icon__close {
		position: absolute;
		top: 24rpx;
		right: 24rpx;
	}
</style>
