<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 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: 2,
            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="header-banner">
            <view class="banner-title">农贸入驻申请</view>
            <view class="banner-subtitle">加入可信农资平台，拓展优质销路</view>
        </view>

        <!-- 步骤引导 -->
        <view class="step-guide">
            <view class="step-item active">
                <view class="step-num">1</view>
                <text class="step-text">资料填写</text>
            </view>
            <view class="step-line active"></view>
            <view class="step-item">
                <view class="step-num">2</view>
                <text class="step-text">资料审核</text>
            </view>
            <view class="step-line"></view>
            <view class="step-item">
                <view class="step-num">3</view>
                <text class="step-text">入驻成功</text>
            </view>
        </view>

        <view class="form-container">
            <fui-form ref="formRef" top="0">
                <!-- 企业基本信息 -->
                <view class="section-card">
                    <view class="section-header">
                        <view class="header-line"></view>
                        <text class="section-title">企业身份信息</text>
                    </view>
                    <view class="form-group">
                        <fui-input label="公司名称" placeholder="请与营业执照一致" v-model="form.enterpriseName" required label-size="28" />
                        <fui-input label="企业编码" placeholder="统一社会信用代码" v-model="form.enterpriseCode" required label-size="28" />
                        <fui-input label="经营业务" placeholder="如：种子、化肥、农机具销售等" v-model="form.businessScope" required label-size="28" />
                        
                        <view class="textarea-box">
                            <view class="textarea-label"><text class="red">*</text>企业简介</view>
                            <fui-textarea placeholder="请简要介绍您的经营规模、品牌优势等..." v-model="form.profile" height="180rpx" size="28" background="#f9f9f9" :padding="['20rpx', '24rpx']" radius="12" />
                        </view>

                        <view class="upload-field">
                            <view class="upload-label"><text class="red">*</text>企业Logo</view>
                            <view class="upload-box">
                                <uni-file-picker :value="pageData.enterpriseLogoArr" limit="1" @select="handleUpload($event, 'logo')" @delete="handleDelete($event, 'logo')" />
                                <text class="upload-tips">建议尺寸 200x200，支持 jpg/png</text>
                            </view>
                        </view>
                    </view>
                </view>

                <!-- 经营地点与联系人 -->
                <view class="section-card">
                    <view class="section-header">
                        <view class="header-line"></view>
                        <text class="section-title">经营联系信息</text>
                    </view>
                    <view class="form-group">
                        <fui-input label="所属地区" placeholder="点击选择省/市/区" v-model="form.areaText" @click="show.area = true" disabled required label-size="28" />
                        <fui-input label="详细地址" placeholder="街道、门牌号等" v-model="form.addr" required label-size="28" />
                        <fui-input label="联系人" placeholder="请输入负责人姓名" v-model="form.contactPerson" required label-size="28" />
                        <fui-input label="联系电话" type="tel" placeholder="请输入手机号码" v-model="form.contactMobile" required label-size="28" />
                    </view>
                </view>

                <!-- 资质证照 -->
                <view class="section-card">
                    <view class="section-header">
                        <view class="header-line"></view>
                        <text class="section-title">资质证照上传</text>
                        <text class="section-sub">（必填）</text>
                    </view>
                    <view class="upload-field-v">
                        <view class="cert-tips">请上传清晰的营业执照、经营许可证或品牌授权书</view>
                        <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="agreement-section">
                    <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="link-text" @click.stop="handleViewProtocol">《农贸入驻服务协议》</text>
                                </view>
                            </view>
                        </fui-label>
                    </fui-checkbox-group>
                </view>

                <!-- 提交区域 -->
                <view class="submit-area">
                    <fui-button text="确认并提交申请" radius="100rpx" @click="submit" :loading="pageData.loading" background="#5db66f" border-color="#5db66f" />
                    <view class="secure-tips">
                        <fui-icon name="safe" :size="24" color="#ccc"></fui-icon>
                        <text>您的信息将被严格保密，仅用于入驻审核</text>
                    </view>
                </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: #f4f7f5;
        padding-bottom: 80rpx;
        font-family: 'DingTalk Sans', system-ui, -apple-system, sans-serif;
    }

    .header-banner {
        background-color: #5db66f;
        padding: 60rpx 40rpx 100rpx;
        color: #fff;
        .banner-title {
            font-size: 48rpx;
            font-weight: bold;
            letter-spacing: 2rpx;
        }
        .banner-subtitle {
            font-size: 26rpx;
            opacity: 0.9;
            margin-top: 12rpx;
        }
    }

    .step-guide {
        display: flex;
        align-items: center;
        justify-content: center;
        padding: 40rpx 30rpx;
        background-color: #fff;
        margin: -40rpx 24rpx 0;
        border-radius: 20rpx;
        box-shadow: 0 8rpx 20rpx rgba(0, 0, 0, 0.05);
        position: relative;
        z-index: 10;

        .step-item {
            display: flex;
            flex-direction: column;
            align-items: center;
            flex-shrink: 0;
            .step-num {
                width: 48rpx;
                height: 48rpx;
                background-color: #f0f0f0;
                color: #999;
                border-radius: 50%;
                display: flex;
                align-items: center;
                justify-content: center;
                font-size: 26rpx;
                font-weight: bold;
                margin-bottom: 12rpx;
            }
            .step-text { font-size: 22rpx; color: #999; }
            &.active {
                .step-num { background-color: #5db66f; color: #fff; }
                .step-text { color: #333; font-weight: bold; }
            }
        }
        .step-line {
            width: 60rpx;
            height: 2rpx;
            background-color: #eee;
            margin: 0 16rpx;
            margin-top: -36rpx;
            &.active { background-color: #5db66f; }
        }
    }

    .form-container {
        padding: 24rpx;
        margin-top: 10rpx;
    }

    .section-card {
        background-color: #fff;
        border-radius: 24rpx;
        padding: 32rpx;
        margin-bottom: 24rpx;
        box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.02);

        .section-header {
            margin-bottom: 32rpx;
            display: flex;
            align-items: center;
            .header-line {
                width: 8rpx;
                height: 32rpx;
                background-color: #5db66f;
                border-radius: 4rpx;
                margin-right: 16rpx;
            }
            .section-title {
                font-size: 32rpx;
                font-weight: bold;
                color: #333;
            }
            .section-sub {
                font-size: 24rpx;
                color: #ff4d4f;
                margin-left: 8rpx;
            }
        }
    }

    .textarea-box {
        padding: 24rpx 0;
        .textarea-label {
            font-size: 28rpx;
            color: #333;
            margin-bottom: 20rpx;
            .red { color: #ff4d4f; margin-right: 4rpx; }
        }
    }

    .upload-field {
        padding: 20rpx 0;
        .upload-label {
            font-size: 28rpx;
            color: #333;
            margin-bottom: 24rpx;
            .red { color: #ff4d4f; margin-right: 4rpx; }
        }
        .upload-box {
            display: flex;
            flex-direction: column;
            .upload-tips {
                font-size: 22rpx;
                color: #ccc;
                margin-top: 12rpx;
            }
        }
    }

    .upload-field-v {
        .cert-tips {
            font-size: 24rpx;
            color: #999;
            background-color: #f9f9f9;
            padding: 16rpx 20rpx;
            border-radius: 8rpx;
            line-height: 1.5;
        }
        .mt-20 { margin-top: 24rpx; }
    }

    .agreement-section {
        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;
        }
        .link-text {
            font-size: 24rpx;
            color: #5db66f;
            font-weight: 500;
        }
    }

    .submit-area {
        margin-top: 20rpx;
        padding: 0 20rpx;
        .secure-tips {
            display: flex;
            align-items: center;
            justify-content: center;
            margin-top: 24rpx;
            text {
                font-size: 22rpx;
                color: #ccc;
                margin-left: 8rpx;
            }
        }
    }

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

    /* 覆盖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>
