<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">
            <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">
                    <image class="p-img" :src="item.image" mode="aspectFill" lazy-load />
                    <view class="p-info">
                        <text class="p-name">{{ item.name }}</text>
                        <view class="p-price-row">
                            <text class="p-symbol">¥</text>
                            <text class="p-price">{{ item.minSellPrice }}</text>
                            <text class="p-unit">/{{ item.unit }}</text>
                        </view>
                        <view class="p-buy-btn" @click="pageData.showConfirmDialog = true">咨询</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="contact-box" @click="pageData.showConfirmDialog = true">
                <fui-icon name="mobile" :size="40" color="#5db66f"></fui-icon>
                <text>联系商家</text>
            </view>
            <view class="main-btn" @click="pageData.showConfirmDialog = true">
                我要购买
            </view>
        </view>

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

        <fui-fab position="right" distance="20" bottom="240" width="100" @click="handlePublish">
            <view class="fab-content">
                <fui-icon name="plus" :size="40" color="#fff"></fui-icon>
                <text style="font-size: 20rpx; color:#fff">发布产品</text>
            </view>
        </fui-fab>

        <!-- 发布产品弹窗 -->
        <fui-bottom-popup :show="pageData.isPopupShow" @close="pageData.isPopupShow = false">
            <view class="popup-wrap">
                <view class="popup-header">
                    <text>发布新产品</text>
                    <fui-icon name="close" @click="pageData.isPopupShow = false"></fui-icon>
                </view>
                <fui-form ref="formRef" top="20">
                    <fui-input label="产品名称" placeholder="请输入产品名称" v-model="productInfo.name" required />
                    <fui-input label="产品分类" placeholder="请选择" v-model="productInfo.category" disabled @click="pageData.categoryPopup = true" required />
                    <view class="price-edit-row">
                        <text class="label">售价范围</text>
                        <input type="number" v-model="productInfo.minSellPrice" placeholder="最低价" class="p-input" />
                        <text class="sep">-</text>
                        <input type="number" v-model="productInfo.maxSellPrice" placeholder="最高价" class="p-input" />
                        <view class="unit-sel" @click="pageData.unitPopup = true">
                            {{ productInfo.unit || '单位' }}
                        </view>
                    </view>
                    <view class="upload-section">
                        <text class="label">产品图片</text>
                        <uni-file-picker v-model="pageData.productImageArr" limit="1" @select="handleUpload" @delete="handleDelete" />
                    </view>
                    <view class="submit-btn-box">
                        <fui-button text="立即发布" radius="100rpx" @click="addData"></fui-button>
                    </view>
                </fui-form>
            </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: 20rpx;
        padding: 30rpx;
        .section-title {
            font-size: 30rpx;
            font-weight: bold;
            color: #333;
            margin-bottom: 24rpx;
            padding-left: 16rpx;
            border-left: 8rpx solid #5db66f;
        }
    }

    .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 -10rpx;
        .product-item {
            width: 50%;
            padding: 10rpx;
            box-sizing: border-box;
            .p-img {
                width: 100%;
                height: 280rpx;
                border-radius: 12rpx 12rpx 0 0;
                background-color: #f8f8f8;
            }
            .p-info {
                background-color: #f9f9f9;
                padding: 16rpx;
                border-radius: 0 0 12rpx 12rpx;
                .p-name {
                    font-size: 26rpx;
                    color: #333;
                    height: 72rpx;
                    display: -webkit-box;
                    -webkit-box-orient: vertical;
                    -webkit-line-clamp: 2;
                    overflow: hidden;
                }
                .p-price-row {
                    margin-top: 12rpx;
                    color: #ff4d4f;
                    .p-symbol { font-size: 20rpx; }
                    .p-price { font-size: 32rpx; font-weight: bold; }
                    .p-unit { font-size: 22rpx; color: #999; }
                }
                .p-buy-btn {
                    margin-top: 16rpx;
                    background-color: #5db66f;
                    color: #fff;
                    font-size: 22rpx;
                    text-align: center;
                    padding: 8rpx 0;
                    border-radius: 24rpx;
                }
            }
        }
    }

    .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;
        padding: 0 30rpx;
        box-shadow: 0 -4rpx 16rpx rgba(0,0,0,0.05);
        z-index: 100;
        .contact-box {
            display: flex;
            flex-direction: column;
            align-items: center;
            margin-right: 40rpx;
            text { font-size: 20rpx; color: #666; margin-top: 4rpx; }
        }
        .main-btn {
            flex: 1;
            height: 80rpx;
            background-color: #5db66f;
            color: #fff;
            display: flex;
            align-items: center;
            justify-content: center;
            border-radius: 40rpx;
            font-size: 30rpx;
            font-weight: bold;
        }
    }

    .popup-wrap {
        background-color: #fff;
        padding: 30rpx;
        border-radius: 30rpx 30rpx 0 0;
        .popup-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            font-size: 32rpx;
            font-weight: bold;
            margin-bottom: 20rpx;
        }
    }

    .price-edit-row {
        display: flex;
        align-items: center;
        padding: 30rpx 0;
        border-bottom: 1rpx solid #eee;
        .label { width: 160rpx; font-size: 28rpx; color: #333; }
        .p-input { flex: 1; font-size: 28rpx; }
        .sep { margin: 0 20rpx; color: #ccc; }
        .unit-sel {
            padding: 4rpx 20rpx;
            background-color: #f5f5f5;
            font-size: 24rpx;
            color: #666;
            border-radius: 20rpx;
        }
    }

    .upload-section {
        padding: 30rpx 0;
        .label { display: block; font-size: 28rpx; color: #333; margin-bottom: 20rpx; }
    }

    .submit-btn-box { padding: 40rpx 0; }
    .fab-content { display: flex; flex-direction: column; align-items: center; }
    .empty-products { text-align: center; padding: 60rpx 0; color: #999; font-size: 26rpx; }
    .area-sel-wrap { background-color: #fff; padding: 30rpx; }
</style>
