<template>
    <u-modal :show="trendModal" title="价格趋势" @confirm="closeTrendModal" confirmText="关闭弹窗" height="93%"><view class="trend_modal">
            <RemoteSearchSelect ref="searchSelect" :value="model" placeholder="请输入关键词" :resultsShow="resultsShow" :currentUrl="currentImg" :searchResults="searchResults" :imgResults="imgResults" :loading="loading"
                :cameraEnabled="true" @search="handleSearch" @select="handleSelect" @select-img="handleSelectImg" @select-crop-img="handleSelectCropImg" @load-more="loadMore" @load-more-img="loadMoreImg" @clear="handleClear" @focus="handleFocus" @upload="uploadImage"></RemoteSearchSelect>
            <view class="charts_box" v-if="chartShow">
                <u--text type="primary" :text="`最大价格：${Math.max(...maxPrice)}元`"></u--text>
                <u--text type="warning" :text="`最小价格：${Math.min(...minPrice)}元`"></u--text>
                <qiun-data-charts type="line" :chartData="chartData" canvasId="trendChart" :opts="opts" :ontouch="true"
                    tooltipFormat="tooltipFormatPrice" width="700rpx" height="600rpx" backgroundColor="#ffffff"
                    @getIndex="handleChartClick" />
            </view>

            <!-- <u--text v-if="cardData.length > 0" :text="'日期：' + date"></u--text> -->
            <view class="card-container" v-if="cardData.length > 0">
                <view class="card-item" v-for="(item, index) in cardData" :key="index">
                    <view class="card-row">
                        <span class="card-label">型号：</span>
                        <span class="card-value">{{ item.model }}</span>
                    </view>
                    <view class="card-row">
                        <span class="card-label">日期：</span>
                        <span class="card-value">{{ item.recycleTime }}</span>
                    </view>
                    <view class="card-row">
                        <span class="card-label">价格：</span>
                        <span class="card-value">{{ item.price }}元</span>
                    </view>
                    <view class="card-row">
                        <span class="card-label">回收情况：</span>
                        <span class="card-value">{{ item.recycleSituation }}</span>
                    </view>
                    <view class="card-row">
                        <span class="card-label">备注：</span>
                        <span class="card-value">{{ item.remark || '-' }}</span>
                    </view>
                </view>
            </view>
        </view>
    </u-modal>
</template>

<script>
import { recycleSituationList } from '@/pages/wareHouse/js/public.js'
import RemoteSearchSelect from '@/components/remote-search-select/index.vue'
export default {
    name: 'ComponentName',
    components: {
        RemoteSearchSelect,
    },
    data() {
        return {
            trendModal: false,
            chartData: {},
            color: [],
            opts: {
                color: this.color,
                padding: [20, 10, 40, 0],
                dataLabel: true,
                dataPointShape: true,
                enableScroll: true,

                xAxis: {
                    disableGrid: true,
                    scrollShow: true,
                    itemCount: 10,
                    rotateLabel: true,
                    rotateAngle: 45,
                },
                yAxis: {
                    gridType: "dash",
                    dashLength: 7,
                },
                legend: {
                    show: false,
                    type: 'scroll',
                    orient: 'horizontal',
                    pageSize: 3,
                    pageIconSize: 12,
                    pageIconColor: '#666',
                    pageIconInactiveColor: '#ccc',
                    pageTextStyle: {
                        color: '#666',
                        fontSize: 12
                    },
                    bottom: 0
                },
                extra: {
                    line: {
                        type: "curve",
                        width: 3,
                        activeType: "hollow",
                        linearType: "custom",
                        onShadow: true,
                        animation: "horizontal"
                    },
                    tooltip: {
                        legendShow: false,
                        bgOpacity: 0.6,
                    }
                }
            },
            model: "",
            maxPrice: [],
            minPrice: [],
            chartShow: false,
            cardData: [],
            // date: '',
            recycleSituationList: recycleSituationList,
            searchResults: [],
            loading: false,
            pageNum: 1,
            total: 0,
            resultsShow: false,
            isSelecting: false,
            imgResults: [],
            currentImg: '',
            imgPageNum: 1,
            imgTotal: 0,
            searchImgInfo: {},
        }
    },
    props: {
    },
    emits: [],
    methods: {
        handleSearch({ keyword }) {
            if (this.isSelecting) {
                this.isSelecting = false
                return
            }
            if (!keyword) {
                this.searchResults = []
                return
            }
            this.model = keyword
            this.loading = true
            uni.$u.api.selectModelList({
                inputValue: keyword,
                pageNum: this.pageNum,
                pageSize: 10,
            }).then(res=>{
                this.loading = false
                this.total = Number(res.total) || 0
                if (this.pageNum == 1){
                    this.searchResults = res.rows || []
                }else{
                    this.searchResults = [...this.searchResults, ...res.rows || []]
                }
                this.resultsShow = true
            })
        },
        handleFocus() {
            this.resultsShow = true
            this.handleSearch({ keyword: this.model })
        },
        handleClear() {
            this.resultsShow = false
            this.searchResults = []
            this.total = 0
            this.pageNum = 1
            this.imgResults = []
            this.imgTotal = 0
            this.imgPageNum = 1
            this.currentImg = ''
            this.model = ""
            this.minPrice = []
            this.maxPrice = []
            this.chartData = []
            this.cardData = []
            this.chartShow = false
        },
        loadMore() {
            if (this.searchResults.length >= this.total) {
                uni.$u.toast("没有更多数据了")
                return
            }
            this.pageNum++
            this.handleSearch({ keyword: this.model })
        },
        // 处理图片列表滚动到底部事件
        loadMoreImg() {
            if (this.imgResults.length >= this.imgTotal) {
                uni.$u.toast("没有更多数据了")
                return
            }
            this.imgPageNum++
            this.uploadImage(this.searchImgInfo)
        },
        handleSelect(item) {
            this.isSelecting = true
            this.model = item.model
            this.resultsShow = false
            this.chartShow = false
            this.$nextTick(() => {
                this.searchTrend(item.model)
            })
        },
        handleSelectImg(item) {
            this.model = item.record.model
            this.chartShow = false
            this.isSelecting = true
            this.pageNum = 1
            this.total = 0
            this.$nextTick(() => {
                this.searchTrend(item.record.model)
            })
        },
        handleSelectCropImg(file) {
            this.imgPageNum = 1
            this.imgTotal = 0
            
            const data = {
                tempFilePaths:[file]
            }
            this.uploadImage(data)
        },
        openTrendModal() {
            this.trendModal = true;
        },
        closeTrendModal() {
            this.handleClear()
            this.trendModal = false;
        },
        searchTrend(val) {
            if (val !== '') {
                uni.$u.api.inquiryChart({
                    model: val,
                }).then(res => {
                    if (res.data.length == 0) {
                        uni.$u.toast("暂无数据")
                        this.minPrice = []
                        this.maxPrice = []
                        this.chartShow = false
                        this.cardData = []
                        return
                    }
                    this.maxPrice = []
                    this.minPrice = []
                    this.color = []
                    const categories = []
                    const dateMap = {}
                    const recycleData = res.data[0].list
                    recycleData.forEach(i => {
                        i.recycleTime = this.formatTime(i.recycleTime)
                        if (!dateMap[i.recycleTime]) {
                            dateMap[i.recycleTime] = true
                            categories.push(i.recycleTime)
                        }
                    })
                    const situationMap = {}
                    recycleData.forEach(i => {
                        const key = `${i.recycleTime}-${i.recycleSituation}`
                        if (!situationMap[key]) {
                            situationMap[key] = {
                                recycleTime: i.recycleTime,
                                recycleSituation: i.recycleSituation,
                                prices: []
                            }
                        }
                        situationMap[key].prices.push(i.price)
                        this.maxPrice.push(i.price)
                        this.minPrice.push(i.price)
                    })
                    const situationGroups = {}
                    Object.values(situationMap).forEach(item => {
                        const avgPrice = item.prices.reduce((sum, price) => sum + price, 0) / item.prices.length
                        if (!situationGroups[item.recycleSituation]) {
                            situationGroups[item.recycleSituation] = []
                        }
                        situationGroups[item.recycleSituation].push({
                            recycleTime: item.recycleTime,
                            price: avgPrice
                        })
                    })
                    const series = Object.entries(situationGroups).map(([situation, data]) => {
                        const color = this.getRandomColor()
                        this.color.push(color)
                        const seriesData = categories.map(date => {
                            const itemData = data.find(i => i.recycleTime == date)
                            return itemData ? itemData.price : null
                        })
                        return {
                            name: this.formatRecycleSituation(situation),
                            data: seriesData,
                            list: data,
                            setShadow: [
                                3,
                                8,
                                15,
                                color
                            ],
                        }
                    })
                    this.opts = {
                        ...this.opts,
                        color: [...this.color]
                    }
                    const chartData = {
                        categories: categories,
                        series: series
                    }
                    this.chartData = chartData
                    this.cardData = []
                    this.chartShow = true
                }).catch((err) => {
                    uni.$u.toast(err)
                })
            } else {
                this.minPrice = []
                this.maxPrice = []
                this.chartShow = false
                this.cardData = []
            }
        },
        uploadImage(res) {
            this.$nextTick(()=>{
                this.searchImgInfo = res;
                uni.$u.api.searchModelByImage(
                    this.searchImgInfo.tempFilePaths[0],
                    {
                        pageNum: this.imgPageNum,
                        pageSize: 10
                    }
                ).then(res => {
                    if (res.data) {
                        this.imgTotal = Number(res.data.total)
                        this.currentImg = this.searchImgInfo.tempFilePaths[0]
                        if(this.imgPageNum == 1){
                            this.imgResults = res.data.rows
                        }else{
                            this.imgResults = [...this.imgResults, ...res.data.rows]
                        }
                        this.$refs.searchSelect.openImgPopup()
                    } else {
                        uni.$u.toast('未匹配到型号，请换一张图或手动输入');
                    }
                }).catch((err) => {
    
                    console.log(err);
                    
                    uni.$u.toast('识别失败，请重试');
                });
            })
        },
        formatTime(date) {
            return this.$dayjs(date).format('YYYY-MM-DD')
        },
        formatRecycleSituation(situation) {
            const item = this.recycleSituationList.find(i => i.value == situation)
            return item ? item.name : '-'
        },
        handleChartClick(event) {
            const index = event.currentIndex.index;
            // 获取点击的日期
            const date = this.chartData.categories[index];
            // this.date = date;

            // 构建该日期的所有回收情况价格数据
            const cardData = [];
            this.chartData.series.forEach(series => {
                const price = series.data[index];
                if (price !== null) {
                    cardData.push({
                        model: this.model,
                        price: price,
                        recycleSituation: series.name,
                        remark: '',
                        recycleTime: date,
                    });
                }
            });
            this.cardData = cardData;
        },
        getRandomColor() {
            var letters = '0123456789ABCDEF';
            var color = '#';
            for (var i = 0; i < 6; i++) {
                color += letters[Math.floor(Math.random() * 16)];
            }
            return color;
        },
    }
}
</script>

<style lang="scss" scoped>
.trend_modal {
    width: 100%;
    min-height: 500rpx;
    max-height: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    gap: 20rpx;
    overflow-y: auto;
}

.charts_box {
    width: 100%;
    max-height: 600rpx;
    overflow: hidden;
}

.card-container {
    display: flex;
    flex-direction: column;
    gap: 16rpx;
    max-height: 200rpx;
    overflow-y: auto;
    font-size: 26rpx;

    &::-webkit-scrollbar {
        width: 6rpx;
    }

    &::-webkit-scrollbar-track {
        background: #f1f1f1;
        border-radius: 3rpx;
    }

    &::-webkit-scrollbar-thumb {
        background: #c1c1c1;
        border-radius: 3rpx;

        &:hover {
            background: #a8a8a8;
        }
    }
}

.card-item {
    background-color: #f5f5f5;
    border-radius: 8rpx;
    padding: 16rpx;
    box-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.1);
}

.card-row {
    display: flex;
    margin-bottom: 10rpx;
    align-items: flex-start;

    .card-label {
        flex-shrink: 0;
    }

    .card-value {
        flex: 1;
        word-break: break-all;
    }
}
</style>