<template>
    <u-modal :show="trendModal" title="价格趋势" @confirm="closeTrendModal" confirmText="关闭弹窗" height="80%">
        <view class="trend_modal">
            <u-search placeholder="请输入型号" v-model="model" @blur="searchTrend" @custom="searchTrend"></u-search>
            <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="500rpx" 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">{{ formatTime(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">{{ formatRecycleSituation(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'
export default {
    name: 'ComponentName',
    data() {
        return {
            trendModal: false,
            chartData: {},
            color: [],
            opts: {
                color: this.color,
                padding: [20, 10, 20, 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,
        }
    },
    props: {
    },
    emits: [],
    methods: {
        openTrendModal() {
            this.trendModal = true;
        },
        closeTrendModal() {
            this.model = ""
            this.date = ""
            this.cardData = []
            this.chartShow = false
            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
                            return
                        }
                        const response = res.data
                        this.maxPrice = []
                        this.minPrice = []
                        this.color = []
                        const categories = []
                        const dateMap = {}
                        response.forEach(item => {
                            this.maxPrice.push(item.max)
                            this.minPrice.push(item.min)
                            item.list.forEach(i => {
                                i.recycleTime = this.formatTime(i.recycleTime)
                                if (!dateMap[i.recycleTime]) {
                                    dateMap[i.recycleTime] = true
                                    categories.push(i.recycleTime)
                                }
                            })
                        })
                        const series = response.map((item) => {
                            const color = this.getRandomColor()
                            this.color.push(color)
                            const data = categories.map(date => {
                                const itemData = item.list.find(i => this.formatTime(i.recycleTime) == date)
                                return itemData ? itemData.price : null
                            })
                            return {
                                name: item.model,
                                data: data,
                                list: item.list,
                                setShadow: [
                                    3,
                                    8,
                                    15,
                                    color
                                ],
                            }
                        })
                        this.opts.color = this.color
                        const chartData = {
                            categories: categories,
                            series: series
                        }
                        this.chartData = JSON.parse(JSON.stringify(chartData))
                        this.cardData = []
                        this.chartShow = true
                    }).catch((err) => {
                        uni.$u.toast(err)
                    })
                }
            },
        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) {
                    // 查找对应日期的完整数据
                    const itemData = series.list.find(i => i.recycleTime === date);
                    cardData.push({
                        model: series.name,
                        price: price,
                        recycleSituation: itemData?.recycleSituation || '',
                        remark: itemData?.remark || ''
                    });
                }
            });
            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%;
	display: flex;
	flex-direction: column;
	gap: 20rpx;
}

.card-container {
	display: flex;
	flex-direction: column;
	gap: 16rpx;
	max-height: 500rpx;
	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>