<template>
    <view class="detail" @click="handleClickOutside">
        <u-navbar class="nav_bar" title="商品详情档案" :autoBack="true" :placeholder="true" rightIcon="more-dot-fill"
            v-hideNav></u-navbar>
        <u-swiper :list="imgsUrl" keyName="url" indicator indicatorMode="line" circular>
            <!-- <template v-slot:item="{ item, index }">
                <view style="width: 100%; height: 600rpx;">
                    <image :src="item.url" mode="aspectFill" style="width: 100%; height: 100%; object-fit: cover;"></image>
                </view>
            </template> -->
        </u-swiper>

        <!-- 立即下架按钮 -->
        <view class="immediate_off_shelf">
            <u-button type="error" shape="circle" size="large" @click="handleOffShelf" :disabled="lockStatus === '1' || globalEditMode">
                <u-icon :name="downStatus == '0' ? 'arrow-upward' : 'arrow-downward'" size="38rpx"
                    color="#ffffff"></u-icon>
                <text>{{ downStatus == '0' ? '立即上架' : '立即下架' }}</text>
            </u-button>
        </view>

        <!-- 轮播图下方操作按钮 -->
        <view class="swiper_actions">
            <view class="action_item" @click="handleDownload">
                <u-icon name="download" size="44rpx" color="#606266"></u-icon>
                <text class="action_text">下载图文</text>
            </view>
            <view class="action_item" @click="handleShare">
                <u-icon name="share" size="44rpx" color="#606266"></u-icon>
                <text class="action_text">分享</text>
            </view>
            <view class="action_item" @click="handleEditImgs">
                <u-icon name="camera" size="44rpx" color="#606266"></u-icon>
                <text class="action_text">编辑图片</text>
                <u-modal :show="showEditImgsModal" title="编辑图片" showCancelButton @confirm="confirmEditImgs" @cancel="cancelEditImgs">
                    <imgs-row-scroll v-if="tempImgsUrl.length > 0" :isShowDeleteIcon="true" keyName="url"
                        @deleteImgInfo="getDeleteImgInfo" imgMode="aspectFill" :totalWidth="400" :images="tempImgsUrl"
                        :previewEnabled="true" :imageWidth="150" :imageHeight="150"></imgs-row-scroll>
                    <u-upload @afterRead="afterRead" multiple></u-upload>
                </u-modal>
            </view>
            <view class="action_item" @click="handleCutImg">
                <u-icon name="cut" size="44rpx" color="#606266"></u-icon>
                <text class="action_text">智能抠图</text>
            </view>
        </view>

        <!-- 核心信息区域 -->
        <view class="core_info">
            <view class="section_title">核心信息</view>
            <view class="info_row">
                <view class="info_label">品牌</view>
                <view class="info_value" @click.stop="showBrandlList()">
                    <!-- <u-input v-if="editMode.dictLabel" v-model="tempValues.dictLabel" :autoFocus="true" @blur="!globalEditMode && saveEditField('dictLabel', tempValues.dictLabel, 'dictLabel')" /> -->
                    <span>{{ coreInfo.dictLabel || '-' }}</span>
                    <BrandList ref="brandListRef" @selectedBrand="handleSelectedBrand"></BrandList>
                </view>
            </view>
            <view class="info_row">
                <view class="info_label">型号</view>
                <view class="info_value" @click.stop="toggleEditField('model', coreInfo.model)">
                    <u-input v-if="editMode.model" v-model="tempValues.model" :autoFocus="true"
                        @blur="!globalEditMode && saveEditField('model', tempValues.model, 'model')" />
                    <span v-else>{{ coreInfo.model || '-' }}</span>
                </view>
            </view>
            <view class="info_row">
                <view class="info_label">独立编码</view>
                <view class="info_value code" @click.stop="toggleEditField('indentifyCode', coreInfo.indentifyCode)">
                    <u-input v-if="editMode.indentifyCode" v-model="tempValues.indentifyCode" :autoFocus="true"
                        @blur="!globalEditMode && saveEditField('indentifyCode', tempValues.indentifyCode, 'indentifyCode')" />
                    <span v-else>{{ coreInfo.indentifyCode || '-' }}</span>
                </view>
            </view>
            <view class="info_row">
                <view class="info_label">是否入库</view>
                <view class="info_value">{{ stockStatusFormatter(coreInfo.stockStatus) }}</view>
            </view>
            <view class="info_row">
                <view class="info_label">入库日期</view>
                <view class="info_value">{{ coreInfo.createTime || '-' }}</view>
            </view>
            <view class="info_row">
                <view class="info_label">付款方式</view>
                <view class="info_value">{{ payTypeFormatter(coreInfo.payType) }}</view>
            </view>
            <view class="info_row col">
                <view class="info_label">备注信息</view>
                <view class="info_value note" @click.stop="toggleEditField('desc', coreInfo.desc)">
                    <textarea v-if="editMode.desc" v-model="tempValues.desc" :autoFocus="true" rows="3"
                        @blur="!globalEditMode && saveEditField('desc', tempValues.desc, 'desc')" />
                    <span v-else>{{ coreInfo.desc || '-' }}</span>
                </view>
            </view>
        </view>

        <!-- 财务与价格区域 -->
        <view class="finance_price">
            <view class="section_title">财务与价格</view>
            <view class="price_group" v-if="isWareHouser">
                <view class="price_item">
                    <view class="price_label">总成本价</view>
                    <view class="price_value original"
                        @click.stop="toggleEditField('costPrice', coreInfo.costPrice)">
                        <u-input v-if="editMode.costPrice" v-model="tempValues.costPrice" :autoFocus="true"
                            @blur="!globalEditMode && saveEditField('costPrice', tempValues.costPrice, 'costPrice')" />
                        <span v-else>￥{{ coreInfo.costPrice || '-' }}</span>
                    </view>
                </view>
                <view class="price_item">
                    <view class="price_label">同行价格</view>
                    <view class="price_value additional"
                        @click.stop="toggleEditField('peerPrice', coreInfo.peerPrice)">
                        <u-input v-if="editMode.peerPrice" v-model="tempValues.peerPrice" :autoFocus="true"
                            @blur="!globalEditMode && saveEditField('peerPrice', tempValues.peerPrice, 'peerPrice')" />
                        <span v-else>￥{{ coreInfo.peerPrice || '-' }}</span>
                    </view>
                </view>
            </view>
            <view class="price_group">
                <view class="price_item">
                    <view class="price_label">代理价格</view>
                    <view class="price_value agent" @click.stop="toggleEditField('agentPrice', coreInfo.agentPrice)">
                        <u-input v-if="editMode.agentPrice" v-model="tempValues.agentPrice" :autoFocus="true"
                            @blur="!globalEditMode && saveEditField('agentPrice', tempValues.agentPrice, 'agentPrice')" />
                        <span v-else>￥{{ coreInfo.agentPrice || '-' }}</span>
                    </view>
                </view>
                <view class="price_item">
                    <view class="price_label">官方指导价</view>
                    <view class="price_value original" @click.stop="toggleEditField('price', coreInfo.price)">
                        <u-input v-if="editMode.price" v-model="tempValues.price" :autoFocus="true"
                            @blur="!globalEditMode && saveEditField('price', tempValues.price, 'price')" />
                        <span v-else>￥{{ coreInfo.price || '-' }}</span>
                    </view>
                </view>
                
            </view>
            <view class="price_group" v-if="isWareHouser">
                <view class="price_item">
                    <view class="price_label">销售价格</view>
                    <view class="price_value suggested"
                        @click.stop="toggleEditField('salePrice', coreInfo.salePrice)">
                        <u-input v-if="editMode.salePrice" v-model="tempValues.salePrice" :autoFocus="true"
                            @blur="!globalEditMode && saveEditField('salePrice', tempValues.salePrice, 'salePrice')" />
                        <span v-else>￥{{ coreInfo.salePrice || '-' }}</span>
                    </view>
                </view>
                <view class="price_item"></view>
            </view>
        </view>

        <!-- 溯源与位置区域 -->
        <view class="traceability_productPosition">
            <view class="section_title">溯源与位置</view>
            <view class="info_row">
                <view class="info_label">商品位置</view>
                <view class="info_value" @click.stop="toggleEditField('productPosition', coreInfo.productPosition)">
                    <u-input v-if="editMode.productPosition" v-model="tempValues.productPosition" :autoFocus="true"
                        @blur="!globalEditMode && saveEditField('productPosition', tempValues.productPosition, 'productPosition')" />
                    <span v-else>{{ coreInfo.productPosition || '-' }}</span>
                </view>
            </view>
            <view class="info_row">
                <view class="info_label">回收人员</view>
                <view class="info_value" @click.stop="showRecyclePersonPicker">
                    <span>{{ coreInfo.recyclePerson || '-' }}</span>
                    <personPicker ref="recyclePersonPickerRef" title="请选择回收人员"
                        @selectPerson="handleSelectRecyclePerson">
                    </personPicker>
                </view>
            </view>
            <view class="info_row">
                <view class="info_label">鉴定人员</view>
                <view class="info_value" @click.stop="showIdentifyingPersonPicker">
                    <span>{{ coreInfo.identifyingPerson || '-' }}</span>
                    <personPicker ref="identifyingPersonPickerRef" title="请选择鉴定人员"
                        @selectPerson="handleSelectIdentifyingPerson"></personPicker>
                </view>
            </view>
            <view class="action_button">
                <u-button type="primary" plain size="mini" @click="viewLog">查看操作日志({{ coreInfo.logTotal ||
                    '-'}}条)</u-button>
                <u-modal :show="logShow" title="日志" :closeOnClickOverlay="true" :showConfirmButton="false"
                    @close="logShow = false">
                    <view class="log_list">
                        <view v-for="value in logList" :key="value.id" class="log_item">
                            {{ value.createTime }}{{ value.name }}{{ value.operation }}
                        </view>
                    </view>
                </u-modal>
            </view>
        </view>

        <!-- 底部功能按钮栏 -->
        <view :class="['bottom_bar', { 'fourPart': coreInfo.stockStatus === '1', 'fivePart': coreInfo.stockStatus === '0' }]">
            <view class="bar_item" @click.stop="globalEditMode ? confirmGlobalEdit() : enterGlobalEdit()">
                <u-icon :name="globalEditMode ? 'checkbox-mark' : 'edit-pen'" size="46rpx"
                    :color="globalEditMode ? '#10b981' : '#9ca3af'"></u-icon>
                <text class="bar_text">{{ globalEditMode ? '确定' : '编辑' }}</text>
            </view>
            <view :class="['bar_item', { 'disabled': globalEditMode}]" @click.stop="lockGoods">
                <u-icon :name="lockStatus === '1' ? 'lock-open' : 'lock'" size="46rpx" color="#9ca3af"></u-icon>
                <text class="bar_text">{{ lockStatus === '1' ? '解锁' : '锁单' }}</text>
            </view>
            <view :class="['bar_item', { 'disabled': globalEditMode}]">
                <image class="bar_icon" src="../../../static/icons/print.png" alt=""></image>
                <text class="bar_text">打印</text>
            </view>
            <view class="bar_item" v-if="coreInfo.stockStatus === '0'" @click.stop="handleConfirmStockIn">
                <view class="primary blue">
                    <image class="bar_img" src="../../../static/icons/stockIn.png" alt=""></image>
                    <text class="bar_text">确认入库</text>
                </view>
            </view>
            <view :class="['bar_item', { 'disabled': lockStatus === '1' ||  globalEditMode || downStatus == '0'}]" @click="handleOpenOrder">
                <view class="primary orange">
                    <u-icon name="bag" size="44rpx" color="#fff"></u-icon>
                    <text class="bar_text">开单</text>
                </view>
            </view>
        </view>
    </view>
</template>

<script>
import BrandList from '@/components/brand-list/index.vue'
import personPicker from '@/components/person-picker/index.vue'
import imgsRowScroll from '@/components/imgs-row-scroll/index.vue'
import { permissionCheck } from '@/utils/util.js'
export default {
    components: {
        BrandList,
        personPicker,
        imgsRowScroll,
    },
    data() {
        return {
            // 核心信息模拟数据
            coreInfo: {},
            // 编辑状态管理
            editMode: {
                model: false,
                indentifyCode: false,
                desc: false,
                costPrice: false,
                peerPrice: false,
                agentPrice: false,
                salePrice: false,
                price: false,
                productPosition: false,
            },
            // 全局编辑模式
            globalEditMode: false,
            // 临时存储编辑值
            tempValues: {},
            goodsId: '',
            logShow: false,
            logList: [],
            imgsUrl: [],
            lockStatus: '',//锁单状态 0：未锁单 1：已锁单 
            downStatus: '',//下架状态 0：已下架 1：已上架
            showEditImgsModal: false,
            tempImgsUrl: [],
            isWareHouser: permissionCheck('WAREHOUSER',false),
        }
    },
    onLoad(options) {
        this.goodsId = options.id;
        this.getGoodsDetail();
    },
    methods: {
        // 分享
        handleShare() {
            uni.showToast({
                title: '分享功能暂未开放',
                icon: 'none'
            })
        },
        // 智能抠图
        handleCutImg() {
            uni.showToast({
                title: '智能抠图功能暂未开放',
                icon: 'none'
            })
        },
        // 是否入库格式化
        stockStatusFormatter(val){
            switch (val) {
                case '1':
                    return '已入库'
                case '0':
                    return '未入库'
                default:
                    return '-'
            }
        },
        payTypeFormatter(val){
            switch (val) {
                case '1':
                    return '微信'
                case '2':
                    return '支付宝'
                case '3':
                    return '银行卡'
                case '4':
                    return '现金'
                case '5':
                    return '数字货币'
                case '6':
                    return '挂账'
                default:
                    return '-'
            }
        },
        // 锁单
        lockGoods() {
            if (this.globalEditMode) {
                uni.showToast({
                    title: '编辑状态下不能操作',
                    icon: 'none'
                })
                return
            }
            uni.$u.api.wareHouseLock({
                id: this.goodsId,
                lockStatus: this.lockStatus === '1' ? '0' : '1',
            }).then(res => {
                uni.showToast({
                    type: "success",
                    title: this.lockStatus === '1' ? '解锁成功' : '锁单成功',
                    icon: 'success'
                })
                this.getGoodsDetail();
            }).catch((error) => {
                uni.showToast({
                    title: error || '操作失败',
                    icon: 'none'
                })
            })
        },
        showRecyclePersonPicker() {
            this.$refs.recyclePersonPickerRef.open();
        },
        // 处理选中回收人员
        handleSelectRecyclePerson(person) {
            this.coreInfo.recyclePerson = person.label;
            this.coreInfo.recyclePersonId = person.id;
            this.submitEdit(this.coreInfo)
        },
        // 显示鉴定人员选择器
        showIdentifyingPersonPicker() {
            this.$refs.identifyingPersonPickerRef.open();
        },
        // 处理选中鉴定人员
        handleSelectIdentifyingPerson(person) {
            this.coreInfo.identifyingPerson = person.label;
            this.coreInfo.identifyingPersonId = person.id;
            this.submitEdit(this.coreInfo)
        },
        // 显示品牌列表
        showBrandlList() {
            if(!permissionCheck('WAREHOUSER')) return false
            this.$refs.brandListRef.showBrandList();
        },
        // 处理选中品牌
        handleSelectedBrand(info) {
            this.coreInfo.dictLabel = info.dictLabel;
            this.coreInfo.dictValue = info.dictValue;
            this.submitEdit(this.coreInfo)
        },
        // 获取商品详情
        getGoodsDetail() {
            uni.$u.api.wareHouseDetail({
                id: this.goodsId,
                userId: this.$store.state.user.userInfo.userId,
            }).then(res => {
                this.coreInfo = res.data;
                this.imgsUrl = res.data.goodPicFileList || [];
                this.lockStatus = res.data.lockStatus;
                this.downStatus = res.data.downStatus;
            });
        },
        // 打开销售业务开单页面
        handleOpenOrder() {
            if (this.lockStatus === '1') {
                uni.showToast({
                    title: '已锁单，不能开单',
                    icon: 'none'
                })
                return
            }
            if (this.globalEditMode) {
                uni.showToast({
                    title: '编辑状态下不能开单',
                    icon: 'none'
                })
                return
            }
            if(this.downStatus === '0'){
                uni.showToast({
                    title: '已下架，不能开单',
                    icon: 'none'
                })
                return
            }
            const params = {
                id: this.goodsId,
                url: this.imgsUrl[0]?.url,
                dictLabel: this.coreInfo.dictLabel,
                dictValue: this.coreInfo.dictValue,
                model: this.coreInfo.model,
                agentPrice: this.coreInfo.agentPrice,
                price: this.coreInfo.price,
                recyclePerson: this.coreInfo.recyclePerson,
                recyclePersonId: this.coreInfo.recyclePersonId,
                createTime: this.coreInfo.createTime,
            }
            uni.navigateTo({
                url: '/pages/wareHouse/components/openOrder?params=' + JSON.stringify(params),
            });
        },
        handleConfirmStockIn(){
            this.coreInfo.stockStatus = '1';
            this.submitEdit(this.coreInfo)
        },
        viewLog() {
            uni.$u.api.wareHouseLog({
                id: this.goodsId,
                userId: this.$store.state.user.userInfo.userId,
            }).then(res => {
                this.logList = res.data;
                this.logShow = true;
            });
        },

        // 立即下架按钮
        handleOffShelf() {
            if (this.lockStatus === '1') {
                uni.showToast({
                    title: '已锁单，不能下架',
                    icon: 'none'
                })
                return
            }
            if (this.globalEditMode) {
                uni.showToast({
                    title: '编辑状态下不能操作',
                    icon: 'none'
                })
                return
            }
            uni.$u.api.wareHouseDown({
                id: this.goodsId,
                downStatus: this.downStatus === '1' ? '0' : '1',
            }).then(() => {
                uni.showToast({
                    title: this.downStatus === '1' ? '下架成功' : '上架成功',
                    icon: 'success'
                })
                this.getGoodsDetail();
            }).catch(() => {
                uni.showToast({
                    title: '操作失败',
                    icon: 'none'
                })
            })
        },
        // 切换单个字段的编辑状态
        toggleEditField(field, value) {
            if(!permissionCheck('WAREHOUSER')) return false
            // 如果不是全局编辑模式
            if (!this.globalEditMode) {
                // 重置所有编辑状态
                this.resetEditMode();
                // 设置当前字段为编辑状态
                this.editMode[field] = true;
                // 保存临时值
                this.tempValues[field] = value;
            }
        },
        // 保存单个字段的编辑值
        saveEditField(field, newValue, fieldName) {
            this.coreInfo[fieldName] = newValue;
            this.editMode[field] = false;
            delete this.tempValues[field];
            console.log(`保存${field}字段值: ${newValue}`);
            this.submitEdit(this.coreInfo);
        },
        // 进入全局编辑模式
        enterGlobalEdit() {
            if(!permissionCheck('WAREHOUSER')) return false
            this.globalEditMode = true;
            // 设置所有可编辑字段为编辑状态
            this.editMode = {
                model: true,
                indentifyCode: true,
                desc: true,
                costPrice: true,
                peerPrice: true,
                agentPrice: true,
                salePrice: true,
                price: true,
                productPosition: true,
            };
            // 保存所有字段的临时值
            this.tempValues = { ...this.coreInfo }
        },
        // 重置所有编辑状态
        resetEditMode() {
            Object.keys(this.editMode).forEach(key => {
                this.editMode[key] = false;
            });
        },
        submitEdit(info) {
            const data = {
                id: this.goodsId,
                goodPicFileList: this.imgsUrl,
                dictLabel: info.dictLabel,
                dictValue: info.dictValue,
                model: info.model,
                indentifyCode: info.indentifyCode,
                createTime: info.createTime,
                payType: info.payType,
                desc: info.desc,
                costPrice: info.costPrice,
                peerPrice: info.peerPrice,
                agentPrice: info.agentPrice,
                salePrice: info.salePrice,
                price: info.price,
                productPosition: info.productPosition,
                recyclePerson: info.recyclePerson,
                recyclePersonId: info.recyclePersonId,
                identifyingPerson: info.identifyingPerson,
                identifyingPersonId: info.identifyingPersonId,
                stockStatus: info.stockStatus,
            }
            uni.$u.api.wareHouseUpdate(data).then(res => {
                uni.showToast({
                    title: '编辑成功',
                    icon: 'success'
                });
                this.getGoodsDetail();
                this.$emit('editSuccess')
            }).catch(() => {
                uni.showToast({
                    title: '操作失败',
                    icon: 'none'
                })
            })
        },
        // 点击页面其他地方保存所有编辑
        handleClickOutside() {
            if (!this.globalEditMode) {
                // 保存当前正在编辑的字段
                Object.keys(this.editMode).forEach(key => {
                    if (this.editMode[key]) {
                        this.saveEditField(key, this.tempValues[key], key);
                    }
                });
            }
            // 当globalEditMode为true时，不执行任何操作

        },
        // 确认全局编辑
        confirmGlobalEdit() {
            this.submitEdit(this.tempValues)
            // 重置全局编辑模式
            this.globalEditMode = false;
            // 退出所有编辑状态
            this.resetEditMode();
            // 清空临时值，恢复初始状态
            this.tempValues = {};
        },
        handleDownload() {
            if (this.imgsUrl.length == 0) {
                uni.showToast({
                    title: '暂无图片',
                    icon: 'none'
                })
                return;
            }
            uni.showModal({
                title: '保存图片',
                content: `是否将 ${this.imgsUrl.length} 张图片保存到本地相册？`,
                confirmText: '保存',
                success: (res) => {
                    if (res.confirm) {
                        this.saveImagesToLocal(this.imgsUrl);
                    }
                }
            })

        },
        saveImagesToLocal(allUrls) {
            uni.showToast({
                title: '图片保存中...',
                icon: 'loading'
            })
            allUrls.forEach((item, index) => {
                uni.downloadFile({
                    url: item.url,
                    success: (res) => {
                        if (res.statusCode === 200) {
                            uni.saveImageToPhotosAlbum({
                                filePath: res.tempFilePath,
                                success() {
                                    uni.showToast({
                                        title: '保存成功'
                                    })
                                },
                                fail: (err) => {
                                    console.error('保存到相册失败:', err);
                                    // 如果是权限问题，尝试请求权限
                                    if (err.errMsg.includes('auth denied')) {
                                        uni.showModal({
                                            title: '权限不足',
                                            content: '需要访问相册权限来保存图片，是否去设置？',
                                            success: (modalRes) => {
                                                if (modalRes.confirm) {
                                                    // 打开设置页面
                                                    uni.openSetting({
                                                        success: (settingRes) => {
                                                            console.log('设置页面结果:', settingRes);
                                                        }
                                                    });
                                                }
                                            }
                                        });
                                    }
                                    reject(err);
                                }
                            })
                        }
                    }
                })
            })
        },
        handleEditImgs() {
            if(!permissionCheck('WAREHOUSER')) return false
            this.showEditImgsModal = true;
            this.tempImgsUrl = this.imgsUrl
        },
        getDeleteImgInfo(imgInfo) {
            this.tempImgsUrl = imgInfo.newImages
        },
        afterRead(info) {
            info.file.forEach(item=>{
                uni.$u.api.uploadFile(item.url).then((res) => {
                    this.tempImgsUrl.push({url:res.data.url});
                    uni.$u.toast("文件上传成功");
                }).catch(() => {
                    uni.$u.toast("上传文件失败");
                })
            })
        },
        confirmEditImgs() {
            this.imgsUrl = this.tempImgsUrl
            this.submitEdit(this.coreInfo)
            this.showEditImgsModal = false;
        },
        cancelEditImgs() {
            this.tempImgsUrl = []
            this.showEditImgsModal = false;
        }
    }
}
</script>

<style lang="scss" scoped>
@import "../styles/detail.scss";
</style>