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

    const userStore = useUserStore()
    const globSetting = useGlobSetting()
    let enterpriseId = null
    
    onLoad((options) => {
        const param = JSON.parse(decodeURIComponent(options.param))
        uni.setNavigationBarTitle({
            title: param.name,
        })
        enterpriseId = param.id
        getDetailData(enterpriseId)
        queryByCategoryAndCode(0, null)
        queryByCategory()
        getGoodsQueryById()
    })

    const toastRef = ref()
    const unitPopupRef = ref(null)
    const uploadRef = ref()
    
    const pageData = reactive({
        data: {
            enterpriseName: '',
            enterpriseLogoUrl: '',
            businessScope: '',
            profile: '',
            contactPerson: '',
            contactMobile: '',
            provinceName: '',
            cityName: '',
            districtName: ''
        },
        enterpriseCers: [],
        isPopupShow: false,
        unitPopup: false,
        unitOptions: [],
        unitVal: [],
        productImageArr: [],
        categoryPopup: false,
        categoryOptions: [],
        categoryText: [],
        categoryVal: [],
        enterpriseProduct: [],
        contactName: '',
        showConfirmDialog: false,
        loading: false,

        rules: [
            { name: 'name', rule: ['required'], msg: ['请输入商品名称'] },
            { name: 'category', rule: ['required'], msg: ['请选择商品分类'] },
            { name: 'minSellPrice', rule: ['required'], msg: ['请输入最小销售价'] },
            { name: 'maxSellPrice', rule: ['required'], msg: ['请输入最大销售价'] },
            { name: 'unit', rule: ['required'], msg: ['请选择单位'] },
            { name: 'image', rule: ['required'], msg: ['请选择商品图片'] },
        ],
    })

    const productInfo = reactive({
        id: '',
        name: '',
        category: '',
        minSellPrice: '',
        maxSellPrice: '',
        unit: '',
        unitCode: '',
        enterpriseId: '',
        image: '',
    })

    function getGoodsQueryById() {
        NongzhiAPI.getGoodsQueryById({ enterpriseId }).then((res) => {
            pageData.enterpriseProduct = res
        })
    }

    function handleUpload(file) {
        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: '上传成功' })
                    pageData.productImageArr = [{ url: data.message }]
                    productInfo.image = data.message
                }
            }
        })
    }

    function handleDelete() {
        pageData.productImageArr = []
        productInfo.image = ''
    }

    function changeCategory(e) {
        productInfo.category = e.value
        pageData.categoryPopup = false
    }

    function selectCompleteUnit(e) {
        productInfo.unit = e.text[e.text.length - 1]
        pageData.unitPopup = false
    }

    function changeUnit(e) {
        queryByCategoryAndCode(e.value, e)
    }

    function queryByCategory() {
        LinghuoyonggongAPI.gitListByCodeDict({ code: 'category' }).then((res) => {
            pageData.categoryOptions = res
            pageData.categoryText = res.map(i => i.itemText)
        })
    }

    function queryByCategoryAndCode(code, e) {
        LinghuoyonggongAPI.queryByCategoryAndCode({ category: 2, code }).then((res) => {
            if (res.length) {
                const dataArr = res.map(i => ({ text: i.name, value: i.code }))
                if (!pageData.unitOptions.length) {
                    pageData.unitOptions = dataArr
                } else {
                    unitPopupRef.value.setRequestData(dataArr, e.layer)
                }
            } else {
                unitPopupRef.value.end()
            }
        })
    }

    const formRef = ref()
    function addData() {
        formRef.value.validator(productInfo, pageData.rules, true).then((res) => {
            if (res.isPassed) {
                NongzhiAPI.postGoodsAdd(productInfo).then(() => {
                    toastRef.value.show({ type: 'success', text: '发布成功' })
                    pageData.isPopupShow = false
                    getGoodsQueryById()
                })
            }
        })
    }

    function getDetailData(id) {
        pageData.loading = true
        NongzhiAPI.getEnterpriseDetail({ id }).then((res) => {
            pageData.enterpriseCers = res.enterpriseCers ? res.enterpriseCers.split(',') : []
            pageData.data = res
            pageData.contactName = res.contactPerson ? (res.contactPerson.substring(0, 1) + '**') : '商家'
            productInfo.unitCode = res.enterpriseCode
            productInfo.enterpriseId = res.id
        }).finally(() => {
            pageData.loading = false
        })
    }

    function handlePublish() {
        Object.assign(productInfo, {
            id: '', name: '', category: '', minSellPrice: '', maxSellPrice: '', unit: '', image: ''
        })
        pageData.productImageArr = []
        pageData.isPopupShow = true
    }

    function makePhoneCall() {
        uni.makePhoneCall({
            phoneNumber: pageData.data.contactMobile,
        })
    }
</script>

<template>
    <view class="page">
        <!-- 商家头部卡片 -->
        <view class="shop-header">
            <view class="shop-main">
                <image class="shop-logo" :src="pageData.data.enterpriseLogoUrl || '/static/images/nongjifuwu/default-corp.png'" mode="aspectFill" />
                <view class="shop-info">
                    <text class="shop-name">{{ pageData.data.enterpriseName }}</text>
                    <view class="shop-tags">
                        <text class="tag">认证入驻</text>
                        <text class="tag green">诚信商家</text>
                    </view>
                </view>
            </view>
            <view class="shop-intro">
                <text class="label">主营：</text>
                <text class="content">{{ pageData.data.businessScope }}</text>
            </view>
            <view class="shop-addr" v-if="pageData.data.provinceName">
                <fui-icon name="location" :size="24" color="#999"></fui-icon>
                <text>{{ pageData.data.provinceName }}{{ pageData.data.cityName }}{{ pageData.data.districtName }}</text>
            </view>
        </view>

        <!-- 资质证书 -->
        <view class="section-card" v-if="pageData.enterpriseCers.length">
            <view class="section-title">资质证书</view>
            <scroll-view scroll-x class="cert-scroll">
                <view class="cert-list">
                    <image
                        v-for="(item, index) in pageData.enterpriseCers"
                        :key="index"
                        :src="item"
                        mode="aspectFit"
                        class="cert-img"
                        @click="uni.previewImage({ urls: pageData.enterpriseCers, current: index })"
                    />
                </view>
            </scroll-view>
        </view>

        <!-- 商品展示 (商城化) -->
        <view class="section-card product-section">
            <view class="section-title">主营产品</view>
            <view v-if="!pageData.enterpriseProduct.length" class="empty-products">
                商家暂未发布产品
            </view>
            <view class="product-grid">
                <view class="product-item" v-for="item in pageData.enterpriseProduct" :key="item.id">
                    <view class="p-img-wrap">
                        <image class="p-img" :src="item.image" mode="aspectFill" lazy-load />
                    </view>
                    <view class="p-info">
                        <text class="p-name">{{ item.name }}</text>
                        <view class="p-bottom">
                            <view class="p-price-box">
                                <text class="p-symbol">¥</text>
                                <text class="p-price">{{ item.minSellPrice }}</text>
                                <text class="p-unit">/{{ item.unit }}</text>
                            </view>
                            <text class="p-tag">批发价</text>
                        </view>
                    </view>
                </view>
            </view>
        </view>

        <!-- 商家简介 -->
        <view class="section-card" v-if="pageData.data.profile">
            <view class="section-title">商家简介</view>
            <text class="profile-text">{{ pageData.data.profile }}</text>
        </view>

        <view style="height: 140rpx"></view>

        <!-- 底部联系栏 -->
        <view class="footer-bar">
            <view class="footer-left">
                <view class="action-item" @click="pageData.showConfirmDialog = true">
                    <fui-icon name="mobile" :size="44" color="#5db66f"></fui-icon>
                    <text>电话咨询</text>
                </view>
                <view class="action-divider"></view>
                <view class="action-item" @click="pageData.showConfirmDialog = true">
                    <fui-icon name="notice" :size="44" color="#ff9500"></fui-icon>
                    <text>在线客服</text>
                </view>
            </view>
            <view class="buy-btn" @click="pageData.showConfirmDialog = true">
                <text class="btn-text">立即购买</text>
            </view>
        </view>

        <!-- 弹窗组件 -->
        <ConfirmDialog
            v-model:show="pageData.showConfirmDialog"
            title="温馨提示"
            :content="`您将与商家【${pageData.data.enterpriseName}】进行电话沟通，确认拨打吗？`"
            @confirm="makePhoneCall"
        />

        <!-- 发布产品悬浮按钮 -->
        <view class="fab-container" @click="handlePublish">
            <view class="ripple"></view>
            <view class="ripple ripple-2"></view>
            <view class="fab-entry">
                <fui-icon name="plus" :size="44" color="#fff"></fui-icon>
                <text>发布产品</text>
            </view>
        </view>

        <!-- 发布产品弹窗 -->
        <fui-bottom-popup :show="pageData.isPopupShow" @close="pageData.isPopupShow = false">
            <view class="popup-wrap">
                <!-- 弹窗头部 -->
                <view class="popup-header">
                    <view class="header-left">
                        <view class="header-icon">
                            <fui-icon name="plus" :size="32" color="#fff"></fui-icon>
                        </view>
                        <text class="header-title">发布新产品</text>
                    </view>
                    <view class="close-btn" @click="pageData.isPopupShow = false">
                        <fui-icon name="close" :size="36" color="#999"></fui-icon>
                    </view>
                </view>

                <!-- 表单区域 -->
                <view class="form-section">
                    <!-- 产品名称 -->
                    <view class="form-item">
                        <view class="form-label">
                            <text class="label-text">产品名称</text>
                            <text class="required">*</text>
                        </view>
                        <input class="form-input" placeholder="请输入产品名称" v-model="productInfo.name" placeholder-class="input-placeholder" />
                    </view>

                    <!-- 产品分类 -->
                    <view class="form-item" @click="pageData.categoryPopup = true">
                        <view class="form-label">
                            <text class="label-text">产品分类</text>
                            <text class="required">*</text>
                        </view>
                        <view class="form-picker">
                            <text :class="['picker-text', productInfo.category ? '' : 'placeholder']">
                                {{ productInfo.category || '请选择分类' }}
                            </text>
                            <fui-icon name="arrowright" :size="28" color="#ccc"></fui-icon>
                        </view>
                    </view>

                    <!-- 售价范围 -->
                    <view class="form-item">
                        <view class="form-label">
                            <text class="label-text">售价范围</text>
                            <text class="required">*</text>
                        </view>
                        <view class="price-row">
                            <view class="price-input-wrap">
                                <text class="price-symbol">¥</text>
                                <input type="digit" class="price-input" placeholder="最低价" v-model="productInfo.minSellPrice" placeholder-class="input-placeholder" />
                            </view>
                            <text class="price-sep">—</text>
                            <view class="price-input-wrap">
                                <text class="price-symbol">¥</text>
                                <input type="digit" class="price-input" placeholder="最高价" v-model="productInfo.maxSellPrice" placeholder-class="input-placeholder" />
                            </view>
                            <view class="unit-btn" @click="pageData.unitPopup = true">
                                {{ productInfo.unit || '单位' }}
                            </view>
                        </view>
                    </view>

                    <!-- 产品图片 -->
                    <view class="form-item">
                        <view class="form-label">
                            <text class="label-text">产品图片</text>
                            <text class="tip">（最多1张）</text>
                        </view>
                        <view class="upload-area">
                            <uni-file-picker v-model="pageData.productImageArr" limit="1" @select="handleUpload" @delete="handleDelete" />
                        </view>
                    </view>
                </view>

                <!-- 提交按钮 -->
                <view class="submit-area">
                    <view class="submit-btn" @click="addData">
                        <text class="btn-text">立即发布</text>
                    </view>
                </view>
            </view>
        </fui-bottom-popup>

        <fui-picker :options="pageData.categoryText" :show="pageData.categoryPopup" @change="changeCategory" @cancel="pageData.categoryPopup = false" />
        <fui-bottom-popup :show="pageData.unitPopup">
            <view class="area-sel-wrap">
                <fui-cascader :options="pageData.unitOptions" @change="changeUnit" @complete="selectCompleteUnit" stepLoading ref="unitPopupRef" />
            </view>
        </fui-bottom-popup>
        <fui-toast ref="toastRef" />
    </view>
</template>

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

    .shop-header {
        background-color: #5db66f;
        padding: 40rpx 30rpx 60rpx;
        color: #fff;
        .shop-main {
            display: flex;
            align-items: center;
            .shop-logo {
                width: 120rpx;
                height: 120rpx;
                border-radius: 60rpx;
                border: 4rpx solid rgba(255,255,255,0.3);
                background-color: #fff;
            }
            .shop-info {
                margin-left: 24rpx;
                .shop-name {
                    font-size: 36rpx;
                    font-weight: bold;
                    display: block;
                }
                .shop-tags {
                    margin-top: 12rpx;
                    display: flex;
                    .tag {
                        font-size: 20rpx;
                        padding: 2rpx 12rpx;
                        background-color: rgba(255,255,255,0.2);
                        border-radius: 4rpx;
                        margin-right: 12rpx;
                        &.green { color: #fff; border: 1rpx solid #fff; }
                    }
                }
            }
        }
        .shop-intro {
            margin-top: 30rpx;
            font-size: 24rpx;
            background-color: rgba(0,0,0,0.05);
            padding: 16rpx 20rpx;
            border-radius: 12rpx;
            .label { opacity: 0.8; }
        }
        .shop-addr {
            margin-top: 20rpx;
            display: flex;
            align-items: center;
            font-size: 22rpx;
            opacity: 0.9;
        }
    }

    .section-card {
        background-color: #fff;
        margin: 20rpx 24rpx;
        border-radius: 16rpx;
        padding: 28rpx 24rpx;
        box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.04);
        .section-title {
            font-size: 28rpx;
            font-weight: 600;
            color: #333;
            margin-bottom: 20rpx;
            padding-left: 14rpx;
            border-left: 6rpx solid #5db66f;
        }
    }

    .product-section {
        margin: 20rpx 24rpx;
        padding: 28rpx 20rpx 20rpx;
    }

    .cert-scroll {
        width: 100%;
        .cert-list {
            display: flex;
            padding-bottom: 10rpx;
            .cert-img {
                width: 200rpx;
                height: 140rpx;
                border-radius: 8rpx;
                margin-right: 20rpx;
                background-color: #f8f8f8;
                flex-shrink: 0;
            }
        }
    }

    .product-grid {
        display: flex;
        flex-wrap: wrap;
        margin: 0 -6rpx;
        .product-item {
            width: 50%;
            padding: 6rpx;
            box-sizing: border-box;
            .p-img-wrap {
                width: 100%;
                height: 320rpx;
                border-radius: 12rpx 12rpx 0 0;
                overflow: hidden;
                background-color: #f5f5f5;
                .p-img {
                    width: 100%;
                    height: 100%;
                }
            }
            .p-info {
                background-color: #fafafa;
                padding: 14rpx 12rpx 16rpx;
                border-radius: 0 0 12rpx 12rpx;
                .p-name {
                    font-size: 26rpx;
                    color: #333;
                    line-height: 36rpx;
                    height: 36rpx;
                    display: block;
                    overflow: hidden;
                    text-overflow: ellipsis;
                    white-space: nowrap;
                    font-weight: 500;
                }
                .p-bottom {
                    display: flex;
                    align-items: center;
                    justify-content: space-between;
                    margin-top: 6rpx;
                }
                .p-price-box {
                    display: flex;
                    align-items: baseline;
                    color: #e93b3b;
                }
                .p-symbol {
                    font-size: 20rpx;
                    font-weight: 600;
                }
                .p-price {
                    font-size: 30rpx;
                    font-weight: 700;
                    margin-left: 2rpx;
                }
                .p-unit {
                    font-size: 20rpx;
                    color: #999;
                    margin-left: 2rpx;
                }
                .p-tag {
                    font-size: 18rpx;
                    color: #ff6b35;
                    background: linear-gradient(135deg, #fff5f0 0%, #ffebe3 100%);
                    padding: 4rpx 8rpx;
                    border-radius: 4rpx;
                    border: 1rpx solid #ffd4c4;
                }
            }
        }
    }

    .profile-text {
        font-size: 26rpx;
        color: #666;
        line-height: 1.6;
    }

    .footer-bar {
        position: fixed;
        bottom: 0;
        left: 0;
        right: 0;
        height: 110rpx;
        background-color: #fff;
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 0 24rpx;
        padding-bottom: env(safe-area-inset-bottom);
        box-shadow: 0 -4rpx 20rpx rgba(0, 0, 0, 0.06);
        z-index: 100;
        .footer-left {
            display: flex;
            align-items: center;
            .action-item {
                display: flex;
                flex-direction: column;
                align-items: center;
                padding: 0 24rpx;
                text {
                    font-size: 20rpx;
                    color: #666;
                    margin-top: 4rpx;
                }
            }
            .action-divider {
                width: 1rpx;
                height: 60rpx;
                background-color: #eee;
            }
        }
        .buy-btn {
            width: 240rpx;
            height: 76rpx;
            background: linear-gradient(135deg, #5db66f 0%, #3da553 100%);
            border-radius: 38rpx;
            display: flex;
            align-items: center;
            justify-content: center;
            box-shadow: 0 6rpx 20rpx rgba(93, 182, 111, 0.4);
            .btn-text {
                font-size: 28rpx;
                font-weight: 600;
                color: #fff;
                letter-spacing: 2rpx;
            }
        }
    }

    .popup-wrap {
        background-color: #fff;
        border-radius: 32rpx 32rpx 0 0;
        overflow: hidden;
        padding-bottom: env(safe-area-inset-bottom);

        .popup-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 32rpx 32rpx 24rpx;
            background: linear-gradient(135deg, #f8fdf9 0%, #fff 100%);
            border-bottom: 1rpx solid #f0f0f0;

            .header-left {
                display: flex;
                align-items: center;
            }

            .header-icon {
                width: 56rpx;
                height: 56rpx;
                background: linear-gradient(135deg, #5db66f 0%, #3da553 100%);
                border-radius: 14rpx;
                display: flex;
                align-items: center;
                justify-content: center;
                margin-right: 16rpx;
                box-shadow: 0 4rpx 12rpx rgba(93, 182, 111, 0.3);
            }

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

            .close-btn {
                width: 56rpx;
                height: 56rpx;
                display: flex;
                align-items: center;
                justify-content: center;
                background-color: #f5f5f5;
                border-radius: 50%;
            }
        }

        .form-section {
            padding: 24rpx 32rpx 0;

            .form-item {
                padding: 24rpx 0;
                border-bottom: 1rpx solid #f5f5f5;

                &:last-child {
                    border-bottom: none;
                }
            }

            .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: 4rpx;
                    font-size: 28rpx;
                }

                .tip {
                    font-size: 24rpx;
                    color: #999;
                    margin-left: 8rpx;
                }
            }

            .form-input {
                width: 100%;
                height: 80rpx;
                background-color: #f7f8fa;
                border-radius: 12rpx;
                padding: 0 24rpx;
                font-size: 28rpx;
                color: #333;
                box-sizing: border-box;
            }

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

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

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

            .price-row {
                display: flex;
                align-items: center;

                .price-input-wrap {
                    flex: 1;
                    display: flex;
                    align-items: center;
                    height: 80rpx;
                    background-color: #f7f8fa;
                    border-radius: 12rpx;
                    padding: 0 20rpx;

                    .price-symbol {
                        font-size: 26rpx;
                        color: #5db66f;
                        font-weight: 600;
                        margin-right: 4rpx;
                    }

                    .price-input {
                        flex: 1;
                        font-size: 28rpx;
                        color: #333;
                    }
                }

                .price-sep {
                    margin: 0 16rpx;
                    color: #ccc;
                    font-size: 26rpx;
                }

                .unit-btn {
                    margin-left: 16rpx;
                    padding: 0 20rpx;
                    height: 80rpx;
                    background: linear-gradient(135deg, #5db66f 0%, #3da553 100%);
                    border-radius: 12rpx;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    font-size: 26rpx;
                    color: #fff;
                    font-weight: 500;
                }
            }

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

        .submit-area {
            padding: 32rpx 32rpx 40rpx;

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

                .btn-text {
                    font-size: 30rpx;
                    color: #fff;
                    font-weight: 600;
                    letter-spacing: 4rpx;
                }
            }
        }
    }

    .input-placeholder {
        color: #bbb;
        font-size: 28rpx;
    }
    .empty-products { text-align: center; padding: 60rpx 0; color: #999; font-size: 26rpx; }
    .area-sel-wrap { background-color: #fff; padding: 30rpx; }

    .fab-container {
        position: fixed;
        right: 30rpx;
        bottom: 140rpx;
        width: 100rpx;
        height: 100rpx;
        z-index: 99;
        display: flex;
        align-items: center;
        justify-content: center;

        .ripple {
            position: absolute;
            width: 100%;
            height: 100%;
            background-color: #5db66f;
            border-radius: 50%;
            opacity: 0.4;
            animation: ripple 2s infinite ease-out;
        }

        .ripple-2 {
            animation-delay: 1s;
        }

        .fab-entry {
            position: relative;
            width: 100rpx;
            height: 100rpx;
            background: linear-gradient(135deg, #a5d63f 0%, #2e8b57 100%);
            border-radius: 50%;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            box-shadow: 0 8rpx 30rpx rgba(46, 139, 87, 0.5);
            animation: breathe 2.5s infinite ease-in-out;
            z-index: 2;
            
            text {
                font-size: 18rpx;
                color: #fff;
                margin-top: -4rpx;
                font-weight: bold;
            }
        }
    }

    @keyframes ripple {
        0% {
            transform: scale(1);
            opacity: 0.4;
        }
        100% {
            transform: scale(1.8);
            opacity: 0;
        }
    }

    @keyframes breathe {
        0%, 100% {
            transform: scale(1);
            box-shadow: 0 8rpx 30rpx rgba(46, 139, 87, 0.5);
        }
        50% {
            transform: scale(1.05);
            box-shadow: 0 12rpx 40rpx rgba(46, 139, 87, 0.6);
        }
    }
</style>
