<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="header-banner">
            <view class="banner-bg">
                <view class="circle circle-1"></view>
                <view class="circle circle-2"></view>
                <view class="circle circle-3"></view>
            </view>
            <view class="banner-content">
                <view class="banner-icon">
                    <fui-icon name="shop" :size="48" color="#fff"></fui-icon>
                </view>
                <view class="banner-title">农机服务入驻</view>
                <view class="banner-desc">专业平台 · 连接万千农户</view>
            </view>
        </view>

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

        <!-- 表单主体 -->
        <view class="form-body">
            <!-- 基本信息卡片 -->
            <view class="form-card">
                <view class="card-header">
                    <view class="header-icon green">
                        <fui-icon name="info" :size="32" color="#fff"></fui-icon>
                    </view>
                    <text class="header-title">基本信息</text>
                </view>
                <view class="card-content">
                    <view class="form-group">
                        <view class="form-label">
                            <text class="label-text">服务队名称</text>
                            <text class="required">*</text>
                        </view>
                        <input class="form-input" placeholder="请输入农机服务队或公司名称" v-model="form.enterpriseName" placeholder-class="input-placeholder" />
                    </view>
                    <view class="form-group">
                        <view class="form-label">
                            <text class="label-text">统一信用代码</text>
                            <text class="required">*</text>
                        </view>
                        <input class="form-input" placeholder="营业执照上的信用代码" v-model="form.enterpriseCode" placeholder-class="input-placeholder" />
                    </view>
                    <view class="form-group">
                        <view class="form-label">
                            <text class="label-text">服务内容</text>
                            <text class="required">*</text>
                        </view>
                        <input class="form-input" placeholder="如：耕整、播种、植保、收割等" v-model="form.businessScope" placeholder-class="input-placeholder" />
                    </view>
                    <view class="form-group">
                        <view class="form-label">
                            <text class="label-text">服务队介绍</text>
                            <text class="required">*</text>
                        </view>
                        <textarea class="form-textarea" placeholder="介绍您的设备实力、服务经验、团队规模等..." v-model="form.profile" placeholder-class="input-placeholder" />
                    </view>
                    <view class="form-group">
                        <view class="form-label">
                            <text class="label-text">形象照片/Logo</text>
                            <text class="required">*</text>
                        </view>
                        <view class="upload-box">
                            <uni-file-picker :value="pageData.enterpriseLogoArr" limit="1" @select="handleUpload($event, 'logo')" @delete="handleDelete($event, 'logo')" />
                        </view>
                    </view>
                </view>
            </view>

            <!-- 联系与位置卡片 -->
            <view class="form-card">
                <view class="card-header">
                    <view class="header-icon orange">
                        <fui-icon name="location" :size="32" color="#fff"></fui-icon>
                    </view>
                    <text class="header-title">联系与位置</text>
                </view>
                <view class="card-content">
                    <view class="form-group" @click="show.area = true">
                        <view class="form-label">
                            <text class="label-text">常驻地区</text>
                            <text class="required">*</text>
                        </view>
                        <view class="form-picker">
                            <text :class="['picker-text', form.areaText ? '' : 'placeholder']">{{ form.areaText || '请选择所在地区' }}</text>
                            <fui-icon name="arrowright" :size="28" color="#ccc"></fui-icon>
                        </view>
                    </view>
                    <view class="form-group">
                        <view class="form-label">
                            <text class="label-text">详细地址</text>
                            <text class="required">*</text>
                        </view>
                        <input class="form-input" placeholder="村组、街道门牌号" v-model="form.addr" placeholder-class="input-placeholder" />
                    </view>
                    <view class="form-row">
                        <view class="form-group half">
                            <view class="form-label">
                                <text class="label-text">负责人</text>
                                <text class="required">*</text>
                            </view>
                            <input class="form-input" placeholder="联系人姓名" v-model="form.contactPerson" placeholder-class="input-placeholder" />
                        </view>
                        <view class="form-group half">
                            <view class="form-label">
                                <text class="label-text">联系电话</text>
                                <text class="required">*</text>
                            </view>
                            <input class="form-input" type="tel" placeholder="手机号码" v-model="form.contactMobile" placeholder-class="input-placeholder" />
                        </view>
                    </view>
                </view>
            </view>

            <!-- 资质证照卡片 -->
            <view class="form-card">
                <view class="card-header">
                    <view class="header-icon blue">
                        <fui-icon name="auth" :size="32" color="#fff"></fui-icon>
                    </view>
                    <text class="header-title">资质证照</text>
                </view>
                <view class="card-content">
                    <view class="cert-tips">
                        <fui-icon name="info-fill" :size="28" color="#fa8c16"></fui-icon>
                        <text>请上传营业执照、农机驾驶证或相关作业资质</text>
                    </view>
                    <view class="upload-box">
                        <uni-file-picker limit="9" :value="pageData.cersImageArr" @select="handleUpload($event, 'cers')" @delete="handleDelete($event, 'cers')" />
                    </view>
                </view>
            </view>

            <!-- 协议勾选 -->
            <view class="agree-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.8" color="#5db66f" />
                            <view class="agree-text">
                                <text>我已阅读并同意</text>
                                <text class="link" @click.stop="handleViewProtocol">《农机服务平台入驻协议》</text>
                            </view>
                        </view>
                    </fui-label>
                </fui-checkbox-group>
            </view>

            <!-- 提交按钮 -->
            <view class="submit-section">
                <view class="submit-btn" :class="{ disabled: pageData.loading }" @click="submit">
                    <text class="btn-text">{{ pageData.loading ? '提交中...' : '提交申请' }}</text>
                </view>
            </view>
        </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: #f5f6f8;
        padding-bottom: 60rpx;
        padding-bottom: calc(60rpx + env(safe-area-inset-bottom));
    }

    /* 头部Banner */
    .header-banner {
        position: relative;
        height: 280rpx;
        overflow: hidden;

        .banner-bg {
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: linear-gradient(135deg, #5db66f 0%, #3da553 50%, #2e8b57 100%);

            .circle {
                position: absolute;
                border-radius: 50%;
                background-color: rgba(255, 255, 255, 0.1);
            }
            .circle-1 {
                width: 300rpx;
                height: 300rpx;
                top: -100rpx;
                right: -50rpx;
            }
            .circle-2 {
                width: 200rpx;
                height: 200rpx;
                bottom: -80rpx;
                left: -40rpx;
            }
            .circle-3 {
                width: 120rpx;
                height: 120rpx;
                top: 60rpx;
                left: 30%;
            }
        }

        .banner-content {
            position: relative;
            z-index: 2;
            display: flex;
            flex-direction: column;
            align-items: center;
            padding-top: 60rpx;

            .banner-icon {
                width: 88rpx;
                height: 88rpx;
                background-color: rgba(255, 255, 255, 0.2);
                border-radius: 24rpx;
                display: flex;
                align-items: center;
                justify-content: center;
                margin-bottom: 20rpx;
            }

            .banner-title {
                font-size: 40rpx;
                font-weight: 600;
                color: #fff;
                letter-spacing: 2rpx;
            }

            .banner-desc {
                font-size: 24rpx;
                color: rgba(255, 255, 255, 0.85);
                margin-top: 12rpx;
                letter-spacing: 4rpx;
            }
        }
    }

    /* 步骤指示器 */
    .step-card {
        background-color: #fff;
        margin: -40rpx 24rpx 0;
        border-radius: 20rpx;
        padding: 36rpx 40rpx;
        box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.06);
        position: relative;
        z-index: 5;

        .step-list {
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .step-item {
            display: flex;
            flex-direction: column;
            align-items: center;

            .step-num {
                width: 52rpx;
                height: 52rpx;
                background-color: #e8e8e8;
                border-radius: 50%;
                display: flex;
                align-items: center;
                justify-content: center;
                margin-bottom: 12rpx;
                transition: all 0.3s;

                text {
                    font-size: 26rpx;
                    color: #999;
                    font-weight: 600;
                }
            }

            .step-text {
                font-size: 22rpx;
                color: #999;
            }

            &.active {
                .step-num {
                    background: linear-gradient(135deg, #5db66f 0%, #3da553 100%);
                    box-shadow: 0 4rpx 12rpx rgba(93, 182, 111, 0.4);

                    text {
                        color: #fff;
                    }
                }

                .step-text {
                    color: #5db66f;
                    font-weight: 600;
                }
            }
        }

        .step-line {
            width: 60rpx;
            height: 4rpx;
            background-color: #e8e8e8;
            margin: 0 16rpx;
            margin-bottom: 36rpx;
            border-radius: 2rpx;

            &.active {
                background: linear-gradient(90deg, #5db66f 0%, #7cc98a 100%);
            }
        }
    }

    /* 表单主体 */
    .form-body {
        padding: 24rpx;
    }

    /* 卡片样式 */
    .form-card {
        background-color: #fff;
        border-radius: 20rpx;
        overflow: hidden;
        margin-bottom: 24rpx;
        box-shadow: 0 2rpx 16rpx rgba(0, 0, 0, 0.04);

        .card-header {
            display: flex;
            align-items: center;
            padding: 28rpx 28rpx 20rpx;
            background: linear-gradient(180deg, #fafbfc 0%, #fff 100%);
            border-bottom: 1rpx solid #f5f5f5;

            .header-icon {
                width: 56rpx;
                height: 56rpx;
                border-radius: 14rpx;
                display: flex;
                align-items: center;
                justify-content: center;
                margin-right: 16rpx;

                &.green {
                    background: linear-gradient(135deg, #5db66f 0%, #3da553 100%);
                    box-shadow: 0 4rpx 12rpx rgba(93, 182, 111, 0.3);
                }
                &.orange {
                    background: linear-gradient(135deg, #fa8c16 0%, #fa541c 100%);
                    box-shadow: 0 4rpx 12rpx rgba(250, 140, 22, 0.3);
                }
                &.blue {
                    background: linear-gradient(135deg, #1890ff 0%, #096dd9 100%);
                    box-shadow: 0 4rpx 12rpx rgba(24, 144, 255, 0.3);
                }
            }

            .header-title {
                font-size: 30rpx;
                font-weight: 600;
                color: #333;
            }
        }

        .card-content {
            padding: 12rpx 28rpx 28rpx;
        }
    }

    /* 表单项 */
    .form-group {
        padding: 20rpx 0;

        .form-label {
            display: flex;
            align-items: center;
            margin-bottom: 16rpx;

            .label-text {
                font-size: 28rpx;
                color: #333;
                font-weight: 500;
            }

            .required {
                color: #ff4d4f;
                margin-left: 6rpx;
                font-size: 28rpx;
            }
        }

        .form-input {
            width: 100%;
            height: 88rpx;
            background-color: #f7f8fa;
            border-radius: 14rpx;
            padding: 0 24rpx;
            font-size: 28rpx;
            color: #333;
            box-sizing: border-box;
            transition: all 0.2s;

            &:focus {
                background-color: #fff;
                box-shadow: 0 0 0 2rpx rgba(93, 182, 111, 0.3);
            }
        }

        .form-textarea {
            width: 100%;
            height: 180rpx;
            background-color: #f7f8fa;
            border-radius: 14rpx;
            padding: 20rpx 24rpx;
            font-size: 28rpx;
            color: #333;
            box-sizing: border-box;
            line-height: 1.6;
        }

        .form-picker {
            display: flex;
            align-items: center;
            justify-content: space-between;
            height: 88rpx;
            background-color: #f7f8fa;
            border-radius: 14rpx;
            padding: 0 24rpx;

            .picker-text {
                font-size: 28rpx;
                color: #333;

                &.placeholder {
                    color: #bbb;
                }
            }
        }
    }

    .form-row {
        display: flex;
        margin: 0 -12rpx;

        .form-group.half {
            flex: 1;
            padding-left: 12rpx;
            padding-right: 12rpx;
        }
    }

    /* 资质提示 */
    .cert-tips {
        display: flex;
        align-items: center;
        padding: 20rpx 24rpx;
        background: linear-gradient(135deg, #fffbe6 0%, #fff7e6 100%);
        border-radius: 12rpx;
        margin-bottom: 20rpx;
        border: 1rpx solid #ffe7ba;

        text {
            font-size: 24rpx;
            color: #ad6800;
            margin-left: 10rpx;
        }
    }

    .upload-box {
        margin-top: 8rpx;
    }

    .input-placeholder {
        color: #bbb;
        font-size: 28rpx;
    }

    /* 协议区域 */
    .agree-section {
        background-color: #fff;
        border-radius: 16rpx;
        padding: 28rpx;
        margin-bottom: 24rpx;

        .agree-label {
            display: block;
        }

        .agree-inner {
            display: flex;
            align-items: center;
        }

        .agree-text {
            font-size: 26rpx;
            color: #666;
            margin-left: 12rpx;
            line-height: 1.6;

            .link {
                color: #5db66f;
                font-weight: 500;
            }
        }
    }

    /* 提交按钮 */
    .submit-section {
        padding: 20rpx 0;

        .submit-btn {
            width: 100%;
            height: 96rpx;
            background: linear-gradient(135deg, #5db66f 0%, #3da553 100%);
            border-radius: 48rpx;
            display: flex;
            align-items: center;
            justify-content: center;
            box-shadow: 0 8rpx 24rpx rgba(93, 182, 111, 0.4);

            &.disabled {
                opacity: 0.7;
            }

            .btn-text {
                font-size: 32rpx;
                color: #fff;
                font-weight: 600;
                letter-spacing: 4rpx;
            }
        }
    }
</style>
