<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 NongjifuwuAPI from '@/api/model/nongjifuwu'
    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)
        getProvince(0, null)
        postMachineryQueryById()
    })

    const toastRef = ref()
    const unitPopupRef = ref(null)
    const uploadRef = ref()
    
    const pageData = reactive({
        data: null,
        enterpriseCers: [],
        isPopupShow: false,
        unitPopup: false,
        unitOptions: [],
        unitVal: [],
        productImageArr: [],
        enterpriseProduct: [],
        contactName: "",
        showConfirmDialog: false,
        loading: false,

        rules: [
            { name: 'name', rule: ['required'], msg: ['请输入农机名称'] },
            { name: 'mobile', rule: ["required", "isMobile"], msg: ["请输入联系电话", "请输入正确的联系电话"] },
            { name: 'areaText', rule: ['required'], msg: ['请选择服务区域'] },
            { name: 'minPrice', rule: ['required'], msg: ['请输入最低价'] },
            { name: 'maxPrice', rule: ['required'], msg: ['请输入最高价'] },
            { name: 'image', rule: ['required'], msg: ['请选择商品图片'] },
        ],
    })

    const productInfo = reactive({
        id: "",
        name: "",
        mobile: "",
        province: "",
        city: "",
        districts: "",
        minPrice: "",
        maxPrice: "",
        image: "",
        enterpriseId: "",
        areaText: '',
    })

    function postMachineryQueryById() {
        NongjifuwuAPI.postMachineryQueryById({ enterpriseId }).then((res) => {
            pageData.enterpriseProduct = res
        })
    }

    function handleUpload(file) {
        const tempFilePaths = file.tempFilePaths
        uni.uploadFile({
            url: `${globSetting.apiUrl + globSetting.urlPrefix}/sys/common/upload`,
            filePath: tempFilePaths[0],
            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 selectCompleteUnit(e) {
        const areaAttr = ['province', 'city', 'districts']
        for (let i = 0; i < e.text.length; i++) {
            productInfo[areaAttr[i]] = e.text[i]
        }
        productInfo.areaText = e.text.join('')
        pageData.unitPopup = false
    }

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

    function getProvince(code, e) {
        if (e && e.layer >= 2) {
            unitPopupRef.value.end()
            return
        }
        LinghuoyonggongAPI.queryConditions({ parentCode: 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) {
                NongjifuwuAPI.postMachineryAdd(productInfo).then(() => {
                    toastRef.value.show({ type: 'success', text: '发布成功' })
                    pageData.isPopupShow = false
                    postMachineryQueryById()
                })
            }
        })
    }

    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.enterpriseId = res.id
        }).finally(() => {
            pageData.loading = false
        })
    }

    function handlePublish() {
        Object.assign(productInfo, {
            id: "", name: "", mobile: "", province: "", city: "", districts: "",
            minPrice: "", maxPrice: "", image: "", areaText: ""
        })
        pageData.productImageArr = []
        pageData.isPopupShow = true
    }

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

<template>
    <view class="page" v-if="pageData.data">
        <!-- 店铺头部 -->
        <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" v-if="pageData.data.businessScope">
                <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="#fff" style="margin-right: 8rpx"></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="aspectFill"
                        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-range" v-if="item.province">服务：{{item.province}}{{item.city}}</view>
                        <view class="p-price-row">
                            <text class="p-symbol">¥</text>
                            <text class="p-price">{{ item.minPrice }}</text>
                            <text class="p-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.contactName}】进行电话沟通，确认拨打吗？`"
            @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.mobile" required />
                    <fui-input label="服务区域" placeholder="点击选择区域" v-model="productInfo.areaText" @click="pageData.unitPopup = true" disabled required />
                    <view class="price-edit-row">
                        <text class="label">租赁单价</text>
                        <input type="number" v-model="productInfo.minPrice" placeholder="最低价" class="p-input" />
                        <text class="sep">-</text>
                        <input type="number" v-model="productInfo.maxPrice" placeholder="最高价" class="p-input" />
                        <text class="unit-text">元/亩</text>
                    </view>
                    <view class="upload-section">
                        <text class="label">实拍图片</text>
                        <uni-file-picker :value="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-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;
                    }
                }
            }
        }
        .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: 240rpx;
                height: 160rpx;
                border-radius: 12rpx;
                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: 260rpx;
                border-radius: 16rpx 16rpx 0 0;
                background-color: #f8f8f8;
            }
            .p-info {
                background-color: #f9f9f9;
                padding: 16rpx;
                border-radius: 0 0 16rpx 16rpx;
                .p-name {
                    font-size: 28rpx;
                    color: #333;
                    font-weight: 500;
                    height: 40rpx;
                    white-space: nowrap;
                    overflow: hidden;
                    text-overflow: ellipsis;
                }
                .p-range {
                    font-size: 22rpx;
                    color: #999;
                    margin-top: 8rpx;
                }
                .p-price-row {
                    margin-top: 12rpx;
                    color: #ff4d4f;
                    .p-symbol { font-size: 20rpx; }
                    .p-price { font-size: 34rpx; 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: 10rpx 0;
                    border-radius: 30rpx;
                }
            }
        }
    }

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

    .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; text-align: center; }
        .sep { margin: 0 20rpx; color: #ccc; }
        .unit-text { font-size: 24rpx; color: #666; margin-left: 10rpx; }
    }

    .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>
