<script setup lang="ts">
    import { reactive, ref, toRefs } from 'vue'
    import { onLoad } from '@dcloudio/uni-app'
    import { useUserStore } from '@/store/modules/user'
    import { useGlobSetting } from '/@/hooks/setting'
    import * as LinghuoyonggongAPI from '@/api/model/linghuoyonggong'
    import * as NongzhiAPI from '@/api/model/nongzhi'
    import AreaPicker from '@/components/AreaPicker/index.vue'

    const userStore = useUserStore()
    const globSetting = useGlobSetting()
    
    const pageData = reactive({
        loading: false,
        show: {
            area: false,
        },
        cersImageArr: [],
        enterpriseLogoArr: [],
        form: {
            id: '',
            enterpriseName: '',
            enterpriseCode: '',
            businessScope: '',
            contactPerson: '',
            contactMobile: '',
            profile: '',
            provinceName: '',
            cityName: '',
            districtName: '',
            townName: '',
            provinceCode: '',
            cityCode: '',
            districtCode: '',
            townCode: '',
            addr: '',
            lon: '',
            lat: '',
            bizCategory: 3,
            enterpriseLogoUrl: null,
            enterpriseCers: null,
            areaText: '',
            agree: false,
        },
        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: (a) => a }] },
        ],
    })

    const { show, form } = toRefs(pageData)
    const toastRef = ref()

    function handleAreaConfirm(e) {
        const areaAttr = ['province', 'city', 'district', 'town']
        const { text, value } = e
        for (let i = 0; i < text.length; i++) {
            pageData.form[`${areaAttr[i]}Name`] = text[i]
            pageData.form[`${areaAttr[i]}Code`] = value[i]
        }
        pageData.form.areaText = e.fullText
    }

    function handleUpload(file, type) {
        const tempFilePath = file.tempFiles[0].path
        uni.uploadFile({
            url: `${globSetting.apiUrl + globSetting.urlPrefix}/sys/common/upload`,
            filePath: tempFilePath,
            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: '上传成功' })
                    if (type == 'logo') {
                        pageData.enterpriseLogoArr = [{ url: data.message }]
                        pageData.form.enterpriseLogoUrl = data.message
                    } else {
                        pageData.cersImageArr.push({ url: data.message })
                    }
                }
            }
        })
    }

    function handleDelete(e, type) {
        if (type == 'logo') {
            pageData.enterpriseLogoArr = []
            pageData.form.enterpriseLogoUrl = null
        } else {
            const index = pageData.cersImageArr.findIndex(i => i.url === e.tempFilePath)
            if (index > -1) pageData.cersImageArr.splice(index, 1)
        }
    }

    function handleViewProtocol() {
        uni.showModal({
            title: '农机服务平台入驻协议',
            content: '协议内容预览...',
            showCancel: false
        })
    }

    const formRef = ref()
    function submit() {
        const { lon, lat } = uni.getStorageSync('location') || { lon: '', lat: '' }
        pageData.form.lon = lon
        pageData.form.lat = lat
        pageData.form.enterpriseCers = pageData.cersImageArr.map(i => i.url).join(',')

        formRef.value.validator(pageData.form, pageData.rules, true).then((res) => {
            if (res.isPassed) {
                pageData.loading = true
                NongzhiAPI.postEnterpriseAdd(pageData.form).then(() => {
                    toastRef.value.show({ type: 'success', text: '申请提交成功' })
                    setTimeout(() => uni.navigateBack(), 1500)
                }).finally(() => {
                    pageData.loading = false
                })
            }
        })
    }
</script>

<template>
    <view class="page">
        <!-- 头部背景 -->
        <view class="banner">
            <view class="banner-title">农机服务入驻</view>
            <view class="banner-tips">专业平台，连接万千农户</view>
        </view>

        <!-- 进度条 -->
        <view class="step-container">
            <view class="step-item active">
                <view class="num">1</view>
                <text>提交资料</text>
            </view>
            <view class="line active"></view>
            <view class="step-item">
                <view class="num">2</view>
                <text>后台审核</text>
            </view>
            <view class="line"></view>
            <view class="step-item">
                <view class="num">3</view>
                <text>完成入驻</text>
            </view>
        </view>

        <view class="form-body">
            <fui-form ref="formRef">
                <!-- 基本信息卡片 -->
                <view class="card">
                    <view class="card-header">
                        <view class="tag-line"></view>
                        <text>基本信息</text>
                    </view>
                    <fui-input label="服务队名称" placeholder="请输入农机服务队或公司名称" v-model="form.enterpriseName" required />
                    <fui-input label="统一代码" placeholder="营业执照信用代码" v-model="form.enterpriseCode" required />
                    <fui-input label="服务内容" placeholder="如：耕整、播种、植保等" v-model="form.businessScope" required />
                    
                    <view class="field-item">
                        <view class="field-label"><text class="req">*</text>服务队介绍</view>
                        <fui-textarea placeholder="介绍您的设备实力、服务经验等..." v-model="form.profile" height="160rpx" background="#fcfcfc" radius="12" />
                    </view>

                    <view class="field-item">
                        <view class="field-label"><text class="req">*</text>形象照片/Logo</view>
                        <uni-file-picker :value="pageData.enterpriseLogoArr" limit="1" @select="handleUpload($event, 'logo')" @delete="handleDelete($event, 'logo')" />
                    </view>
                </view>

                <!-- 经营地点卡片 -->
                <view class="card">
                    <view class="card-header">
                        <view class="tag-line"></view>
                        <text>联系与位置</text>
                    </view>
                    <fui-input label="常驻地区" placeholder="点击选择" v-model="form.areaText" @click="show.area = true" disabled required />
                    <fui-input label="详细地址" placeholder="村组、街道门牌号" v-model="form.addr" required />
                    <fui-input label="负责人" placeholder="联系人姓名" v-model="form.contactPerson" required />
                    <fui-input label="联系电话" type="tel" placeholder="请输入手机号" v-model="form.contactMobile" required />
                </view>

                <!-- 证照上传卡片 -->
                <view class="card">
                    <view class="card-header">
                        <view class="tag-line"></view>
                        <text>资质证照</text>
                    </view>
                    <view class="cert-box">
                        <text class="tips">请上传营业执照、农机驾驶证或相关作业资质</text>
                        <view class="mt-20">
                            <uni-file-picker limit="9" :value="pageData.cersImageArr" @select="handleUpload($event, 'cers')" @delete="handleDelete($event, 'cers')" />
                        </view>
                    </view>
                </view>

                <!-- 协议勾选 -->
                <view class="agree-wrap">
                    <fui-checkbox-group @change="e => form.agree = e.detail.value.length > 0">
                        <fui-label class="agree-label">
                            <view class="agree-inner">
                                <fui-checkbox :value="true" :scaleRatio="0.7" color="#5db66f" />
                                <view class="agree-text-content">
                                    <text class="agree-text">我已阅读并同意</text>
                                    <text class="agree-link" @click.stop="handleViewProtocol">《农机服务平台入驻协议》</text>
                                </view>
                            </view>
                        </fui-label>
                    </fui-checkbox-group>
                </view>

                <view class="btn-area">
                    <fui-button text="提交申请" radius="100rpx" @click="submit" :loading="pageData.loading" background="#5db66f" border-color="#5db66f" />
                </view>
            </fui-form>
        </view>

        <AreaPicker v-model:show="show.area" :layer="4" @confirm="handleAreaConfirm" />

        <fui-toast ref="toastRef" />
    </view>
</template>

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

    .banner {
        background-color: #5db66f;
        padding: 60rpx 40rpx 120rpx;
        color: #fff;
        .banner-title { font-size: 44rpx; font-weight: bold; }
        .banner-tips { font-size: 24rpx; opacity: 0.8; margin-top: 10rpx; }
    }

    .step-container {
        background-color: #fff;
        margin: -60rpx 30rpx 0;
        border-radius: 24rpx;
        padding: 40rpx 20rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        box-shadow: 0 10rpx 30rpx rgba(0,0,0,0.05);
        position: relative;
        z-index: 5;
        .step-item {
            display: flex;
            flex-direction: column;
            align-items: center;
            .num {
                width: 44rpx;
                height: 44rpx;
                background-color: #f0f0f0;
                color: #999;
                border-radius: 50%;
                display: flex;
                align-items: center;
                justify-content: center;
                font-size: 24rpx;
                margin-bottom: 10rpx;
            }
            text { font-size: 20rpx; color: #999; }
            &.active {
                .num { background-color: #5db66f; color: #fff; }
                text { color: #333; font-weight: bold; }
            }
        }
        .line {
            width: 80rpx;
            height: 2rpx;
            background-color: #f0f0f0;
            margin: 0 20rpx;
            margin-top: -30rpx;
            &.active { background-color: #5db66f; }
        }
    }

    .form-body {
        padding: 24rpx;
    }

    .card {
        background-color: #fff;
        border-radius: 24rpx;
        padding: 30rpx;
        margin-bottom: 24rpx;
        .card-header {
            display: flex;
            align-items: center;
            margin-bottom: 30rpx;
            .tag-line { width: 8rpx; height: 30rpx; background-color: #5db66f; border-radius: 4rpx; margin-right: 16rpx; }
            text { font-size: 30rpx; font-weight: bold; color: #333; }
        }
    }

    .field-item {
        padding: 20rpx 0;
        .field-label {
            font-size: 28rpx;
            color: #333;
            margin-bottom: 20rpx;
            .req { color: #ff4d4f; margin-right: 4rpx; }
        }
    }

    .cert-box {
        .tips { font-size: 22rpx; color: #999; background-color: #f9f9f9; padding: 16rpx; border-radius: 8rpx; }
        .mt-20 { margin-top: 24rpx; }
    }

    .agree-wrap {
        display: flex;
        justify-content: center;
        padding: 40rpx 0 20rpx;
        .agree-label {
            display: block;
        }
        .agree-inner {
            display: flex;
            align-items: center;
        }
        .agree-text-content {
            display: flex;
            align-items: center;
            flex-wrap: wrap;
            margin-left: 12rpx;
        }
        .agree-text {
            font-size: 24rpx;
            color: #999;
        }
        .agree-link {
            font-size: 24rpx;
            color: #5db66f;
            font-weight: 500;
        }
    }

    .btn-area {
        padding: 20rpx 30rpx;
    }

    .area-pop {
        background-color: #fff;
        padding: 30rpx;
        border-radius: 32rpx 32rpx 0 0;
        .pop-title { font-size: 32rpx; font-weight: bold; text-align: center; margin-bottom: 30rpx; }
    }

    /* 覆盖FirstUI的部分样式以统一字体 */
    :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>
