<template>
    <!-- 历史数据对话框 -->
    <el-dialog title="历史数据" v-model="historyDataOpen" width="1400px" class="my_dialog" align-center
        :destroy-on-close="true" :close-on-click-modal="false">
        <div v-loading="loading">
            <el-form :inline="true" :model="queryParams" class="myInsertForm">
                <el-form-item label="开始时间">
                    <el-date-picker v-model="queryParams.startTime" format="YYYY-MM-DD HH:mm:ss"
                        value-format="YYYY-MM-DD HH:mm:ss" type="date" placeholder="开始时间" @change="validateStartTime" />
                </el-form-item>
                <el-form-item label="结束时间">
                    <el-date-picker v-model="queryParams.endTime" format="YYYY-MM-DD HH:mm:ss"
                        value-format="YYYY-MM-DD HH:mm:ss" type="date" placeholder="结束时间" @change="validateEndTime" />
                </el-form-item>
                <el-form-item label="类型:" v-if="!readonly">
                    <el-select v-model="mediaType" placeholder="请选择" style="min-width: 120px;" clearable @change="handleChangeMediaType" >
                        <el-option v-for="item in mediaTypes" :key="item.value" :label="item.label"
                            :value="item.value" />
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-radio-group v-model="charsType" @change="handleChangeType">
                        <el-radio value="1">折线图</el-radio>
                        <el-radio value="2">柱状图</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" class="primaryBtn" @click="handleQuery">查询</el-button>
                    <el-button type="primary" class="primaryBtn" @click="resetQuery">重置</el-button>
                </el-form-item>
            </el-form>
            <el-empty v-if="xData.length == 0" description="无数据" />
            <div v-else id="historyChar" ref="historyCharRef"></div>
            <el-table :data="historyList" border height="285px">
                <template v-if="readonly">
                    <el-table-column label="城市/市场" align="center" prop="cityName" width="100" />
                    <el-table-column label="媒体形式/名称" align="left" prop="mediaName" width="150" />
                    <el-table-column label="频次" align="center" prop="frequency" width="130" />
                    <el-table-column label="统一对外刊例价" align="right" prop="listPrice" width="150" />
                    <el-table-column label="单位" align="center" prop="listPriceUnit" width="120" />
                    <el-table-column label="实际购买频次" align="center" prop="actualBuyFrequency" width="130" />
                    <el-table-column label="实际购买刊例价" align="right" prop="actualBuyListPrice" width="140" />
                    <el-table-column label="购买周期" align="right" prop="buyCycle" width="120" />
                    <el-table-column label="折扣" align="center" prop="discount" width="100" />
                    <el-table-column label="媒体总净价" align="right" prop="mediaRegularPrice" width="120" />
                    <el-table-column label="总制作费" align="right" prop="totalMakeFee" width="130" />
                    <el-table-column label="总净价" align="right" prop="totalRegularPrice" width="120" />
                    <el-table-column label="供应商" align="left" prop="supplier" width="150" />
                    <el-table-column label="项目名称" align="left" prop="projectName" width="150" />
                </template>
                <template v-else>
                    <template v-if="mediaType == 1">
                        <el-table-column label="城市" align="center" prop="cityName" width="90" />
                        <el-table-column label="媒体名称" align="left" prop="mediaName" width="150" />
                        <el-table-column label="频次" align="center" prop="frequency" width="100" />
                        <el-table-column label="投放数量" align="right" prop="putTotal" width="100" />
                        <el-table-column label="起购周期" align="right" prop="buyCycle" width="120" />
                        <el-table-column label="刊例价" align="right" prop="listPrice" width="120" />
                        <el-table-column label="刊例价单位" align="center" prop="listPriceUnit" width="120" />
                        <el-table-column label="实际购买刊例价" align="right" prop="actualBuyListPrice" width="140" />
                        <el-table-column label="实际购买刊例价单位" align="center" prop="actualBuyListPriceUnit" width="170" />
                        <el-table-column label="折扣" align="center" prop="discount" width="100" />
                        <el-table-column label="媒体总净价" align="right" prop="mediaRegularPrice" width="120" />
                        <el-table-column label="首次制作安装费" align="right" prop="firstInstallFee" width="150" />
                        <el-table-column label="总制作费" align="right" prop="totalMakeFee" width="130" />
                        <el-table-column label="供应商" align="left" prop="supplier" width="150" />
                    </template>
                    <template v-if="mediaType == 2">
                        <el-table-column label="城市" align="center" prop="cityName" width="90" />
                        <el-table-column label="资源描述" align="left" prop="resourceRemark" width="150" />
                        <el-table-column label="媒体名称" align="left" prop="mediaName" width="150" />
                        <el-table-column label="频次" align="center" prop="frequency" width="100" />
                        <el-table-column label="发布总量" align="right" prop="releaseTotal" width="120" />
                        <el-table-column label="购买周期" align="right" prop="buyCycle" width="120" />
                        <el-table-column label="刊例价" align="right" prop="listPrice" width="120" />
                        <el-table-column label="刊例价单位" align="center" prop="listPriceUnit" width="120" />
                        <el-table-column label="实际购买刊例价" align="right" prop="actualBuyListPrice" width="140" />
                        <el-table-column label="实际购买刊例价单位" align="center" prop="actualBuyListPriceUnit" width="170" />
                        <el-table-column label="折扣" align="center" prop="discount" width="100" />
                        <el-table-column label="媒体总净价" align="right" prop="mediaRegularPrice" width="120" />
                        <el-table-column label="首次制作安装费" align="right" prop="firstInstallFee" width="150" />
                        <el-table-column label="总制作费" align="right" prop="totalMakeFee" width="130" />
                        <el-table-column label="总净价" align="right" prop="totalRegularPrice" width="120" />
                        <el-table-column label="总净价单位" align="center" prop="totalRegularPriceUnit" width="130" />
                        <el-table-column label="供应商" align="left" prop="supplier" width="150" />
                    </template>
                    <template v-if="mediaType == 3">
                        <el-table-column label="城市" align="center" prop="cityName" width="90" />
                        <el-table-column label="媒体名称" align="left" prop="mediaName" width="150" />
                        <el-table-column label="频次" align="center" prop="frequency" width="100" />
                        <el-table-column label="发布总量" align="right" prop="releaseTotal" width="120" />
                        <el-table-column label="最短购买周期" align="right" prop="buyCycle" width="130" />
                        <el-table-column label="刊例价" align="right" prop="listPrice" width="120" />
                        <el-table-column label="刊例价单位" align="center" prop="listPriceUnit" width="120" />
                        <el-table-column label="折扣" align="center" prop="discount" width="100" />
                        <el-table-column label="媒体总净价" align="right" prop="mediaRegularPrice" width="120" />
                        <el-table-column label="首次制作安装费" align="right" prop="firstInstallFee" width="150" />
                        <el-table-column label="总制作费" align="right" prop="totalMakeFee" width="130" />
                        <el-table-column label="总净价" align="right" prop="totalRegularPrice" width="120" />
                        <el-table-column label="总净价单位" align="center" prop="totalRegularPriceUnit" width="130" />
                        <el-table-column label="供应商" align="left" prop="supplier" width="150" />
                    </template>
                    <template v-if="mediaType == 4">
                        <el-table-column label="城市" align="center" prop="cityName" width="90" />
                        <el-table-column label="线路" align="center" prop="subwayLine" width="150" />
                        <el-table-column label="站点" align="center" prop="station" width="130" />
                        <el-table-column label="级别" align="center" prop="level" width="100" />
                        <el-table-column label="媒体形式" align="center" prop="mediaFormat" width="120" />
                        <el-table-column label="媒体名称" align="left" prop="mediaName" width="150" />
                        <el-table-column label="起投周期" align="right" prop="buyCycle" width="120" />
                        <el-table-column label="投放周期" align="right" prop="deliverCycle" width="120" />
                        <el-table-column label="购买数量" align="right" prop="buyTotal" width="120" />
                        <el-table-column label="购买数量单位" align="center" prop="buyTotalUnit" width="130" />
                        <el-table-column label="频次" align="center" prop="frequency" width="100" />
                        <el-table-column label="刊例价" align="right" prop="listPrice" width="120" />
                        <el-table-column label="刊例价单位" align="center" prop="listPriceUnit" width="120" />
                        <el-table-column label="实际购买刊例价" align="right" prop="actualBuyListPrice" width="140" />
                        <el-table-column label="实际购买刊例价单位" align="center" prop="actualBuyListPriceUnit" width="170" />
                        <el-table-column label="媒体总净价" align="right" prop="mediaRegularPrice" width="120" />
                        <el-table-column label="媒体总净价单位" align="center" prop="mediaRegularPriceUnit" width="140" />
                        <el-table-column label="常规制作费" align="right" prop="commonMakeFee" width="130" />
                        <el-table-column label="创意制作费" align="right" prop="ideaMakeFee" width="130" />
                        <el-table-column label="总制作费" align="right" prop="totalMakeFee" width="130" />
                        <el-table-column label="总净价" align="right" prop="totalRegularPrice" width="120" />
                        <el-table-column label="总净价单位" align="center" prop="totalRegularPriceUnit" width="130" />
                        <el-table-column label="供应商" align="left" prop="supplier" width="150" />
                    </template>
                    <template v-if="mediaType == 5">
                        <el-table-column label="城市" align="center" prop="cityName" width="90" />
                        <el-table-column label="场站" align="center" prop="station" width="130" />
                        <el-table-column label="媒体位置" align="left" prop="mediaName" width="150" />
                        <el-table-column label="频次" align="center" prop="frequency" width="100" />
                        <el-table-column label="发布总量" align="right" prop="releaseTotal" width="120" />
                        <el-table-column label="购买周期" align="right" prop="buyCycle" width="120" />
                        <el-table-column label="刊例价" align="right" prop="listPrice" width="120" />
                        <el-table-column label="刊例价单位" align="center" prop="listPriceUnit" width="120" />
                        <el-table-column label="折扣" align="center" prop="discount" width="100" />
                        <el-table-column label="媒体总净价" align="right" prop="mediaRegularPrice" width="120" />
                        <el-table-column label="首次制作安装费" align="right" prop="firstInstallFee" width="150" />
                        <el-table-column label="总制作费" align="right" prop="totalMakeFee" width="130" />
                        <el-table-column label="总净价" align="right" prop="totalRegularPrice" width="120" />
                        <el-table-column label="总净价单位" align="center" prop="totalRegularPriceUnit" width="130" />
                        <el-table-column label="供应商" align="left" prop="supplier" width="150" />
                    </template>
                    <template v-if="mediaType == 6 || mediaType == 7">
                        <el-table-column label="城市" align="center" prop="cityName" width="90" />
                        <el-table-column label="媒体名称" align="left" prop="mediaName" width="150" />
                        <el-table-column label="频次" align="center" prop="frequency" width="100" />
                        <el-table-column label="发布总量" align="right" prop="releaseTotal" width="120" />
                        <el-table-column label="购买周期" align="right" prop="buyCycle" width="120" />
                        <el-table-column label="刊例价" align="right" prop="listPrice" width="120" />
                        <el-table-column label="刊例价单位" align="center" prop="listPriceUnit" width="120" />
                        <el-table-column label="实际购买刊例价" align="right" prop="actualBuyListPrice" width="140" />
                        <el-table-column label="实际购买刊例价单位" align="center" prop="actualBuyListPriceUnit" width="170" />
                        <el-table-column label="折扣" align="center" prop="discount" width="100" />
                        <el-table-column label="媒体总净价" align="right" prop="mediaRegularPrice" width="120" />
                        <el-table-column label="首次制作安装费" align="right" prop="firstInstallFee" width="150" />
                        <el-table-column label="总制作费" align="right" prop="totalMakeFee" width="130" />
                        <el-table-column label="总净价" align="right" prop="totalRegularPrice" width="120" />
                        <el-table-column label="总净价单位" align="center" prop="totalRegularPriceUnit" width="130" />
                        <el-table-column label="供应商" align="left" prop="supplier" width="150" />
                    </template>
                </template>
            </el-table>

            <!-- <pagination :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize"
            @pagination="getList" /> -->
        </div>
    </el-dialog>
</template>
<script setup>
import { onMounted, defineEmits, ref } from 'vue'
import { mediaPrice } from "@/api/mediaLibrary"
import * as echarts from 'echarts'

const { proxy } = getCurrentInstance()

// 图表类型
const charsType = ref('1')
const historyCharRef = ref(null)

const xData = ref([])
const yData = ref([])

const historyDataOpen = ref(false)
const loading = ref(false)
// const total = ref(0)
const historyList = ref([])
const queryParams = ref({
    mediaId: undefined,
    startTime: undefined,
    endTime: undefined,
})

// 媒体类型
const readonly = ref(false)
const mediaType = ref(1)

// 0-优势 1-门禁 2-候车厅 3-道闸  4-地铁  5-高铁  6-写字楼  7-车库灯箱
const mediaTypes = ref([
    // { value: 0, label: '优势' },
    { value: 1, label: '门禁' },
    { value: 2, label: '候车厅' },
    { value: 3, label: '道闸' },
    { value: 4, label: '地铁' },
    { value: 5, label: '高铁' },
    { value: 6, label: '写字楼' },
    { value: 7, label: '车库灯箱' },
])

const _historyChar = ref(null)
// 折线图
const initHistoryCharLine = () => {
    if (_historyChar.value) _historyChar.value.dispose();
    _historyChar.value = echarts.init(historyCharRef.value)
    _historyChar.value.setOption({
        tooltip: {
            trigger: 'item',
            formatter: "{b} : {c} 元/天"   //鼠标放上去 展示内容 
        },
        grid: {
            left: '3%',
            right: '3%',  // 右侧留更多空间显示长数值
            top: '14%',
            bottom: '10%',
            containLabel: true
        },
        xAxis: {
            type: 'category',
            data: xData.value,
            axisLabel: {
                interval: 0,  // 强制显示所有标签
                rotate: 15,   // 标签旋转45度防止重叠
                fontSize: 16,  // 缩小字体
                color: '#808080'
            },
            axisLine: {
                show: false
            },
            axisTick: {
                show: false
            },
            splitLine: {
                lineStyle: {
                    type: 'dashed',
                    color: '#eee',
                },
                show: false
            },
        },
        yAxis: {
            name: '实际报价（元/天）',
            nameTextStyle: {
                color: '#3B3B3B',
                fontSize: 16,
                fontWeight: '400',
                fontFamily: 'Microsoft YaHei',
                align: 'center',
            },
            type: 'value',
            axisLabel: {
                fontSize: 16,
                color: '#808080'
            },
            axisLine: {
                show: false
            },
            axisTick: {
                show: false
            },
            splitLine: {
                lineStyle: {
                    type: 'solid',
                    color: '#F1F1F1',
                },
                show: true
            },
        },
        series: [
            {
                data: yData.value,
                type: 'line',
                smooth: true,
                // symbol: 'circle',
                symbolSize: 12,
                itemStyle: {
                    color: '#FFC63D'
                },
                lineStyle: {
                    width: 2,
                    color: '#FFC63D'
                },
            }
        ]
    })
    // window.addEventListener("resize", () => {
    //     _historyChar.value.resize()
    // })
}
// 柱状图
const initHistoryCharBar = () => {
    if (_historyChar.value) _historyChar.value.dispose();
    _historyChar.value = echarts.init(historyCharRef.value)
    _historyChar.value.setOption({
        tooltip: {
            trigger: 'item',
            formatter: "{b} : {c} 元/天"   //鼠标放上去 展示内容 
        },
        grid: {
            left: '3%',
            right: '3%',  // 右侧留更多空间显示长数值
            top: '14%',
            bottom: '10%',
            containLabel: true
        },
        xAxis: {
            type: 'category',
            data: xData.value,
            axisLabel: {
                interval: 0,  // 强制显示所有标签
                rotate: 15,   // 标签旋转45度防止重叠
                fontSize: 16,  // 缩小字体
                color: '#808080'
            },
            axisLine: {
                show: false
            },
            axisTick: {
                show: false
            },
            splitLine: {
                lineStyle: {
                    type: 'dashed',
                    color: '#eee',
                },
                show: false
            },
        },
        yAxis: {
            name: '实际报价（元/天）',
            nameTextStyle: {
                color: '#3B3B3B',
                fontSize: 16,
                fontWeight: '400',
                fontFamily: 'Microsoft YaHei',
                align: 'center',
            },
            type: 'value',
            axisLabel: {
                fontSize: 16,
                color: '#808080'
            },
            axisLine: {
                show: false
            },
            axisTick: {
                show: false
            },
            splitLine: {
                lineStyle: {
                    type: 'solid',
                    color: '#F1F1F1',
                },
                show: true
            },
        },
        series: [{
            name: '数值',
            type: 'bar',
            barWidth: '16',
            data: yData.value,
            itemStyle: {
                // color: '#767C81',

                // 间隔变色函数
                color: '#1A75E6',
                borderRadius: [0, 0, 0, 0]  // 顶部圆角
            },
            label: {
                show: false,
                position: 'top',  // 数值显示在柱子上方
                formatter: '{c}',
                color: '#333'
            }
        }]
    })
    // window.addEventListener("resize", () => {
    //     _historyChar.value.resize()
    // })
}
const handleChangeMediaType = (val) => { 
    getMediaPriceList()
}
const handleChangeType = (val) => {
    charsType.value = val
    getMediaPriceList()
}

const handleQuery = () => {
    getMediaPriceList()
}
const resetQuery = () => {
    queryParams.value.startTime = undefined
    queryParams.value.endTime = undefined
    getMediaPriceList()
}

const getMediaPriceList = () => {
    loading.value = true
    mediaPrice(queryParams.value).then(res => {
        if (readonly.value) historyList.value = res.data.filter(item => item.mediaType == 0)
        else historyList.value = res.data.filter(item => item.mediaType == mediaType.value)
        xData.value = []
        yData.value = []
        historyList.value.forEach(item => {
            xData.value.push(item.supplier)
            let itemYDate = null;
            const convertIntTotalRegularPrice = parseFloat(item.totalRegularPrice.replace(/,/g, ''))
            if (readonly.value) itemYDate = (convertIntTotalRegularPrice / item.buyCycle).toFixed(2)
            else {
                // 判断是否纯数字
                const convertIntValue = safeParseInt(item.buyCycle)
                if (typeof convertIntValue === 'number' && Number.isFinite(convertIntValue)) {
                    itemYDate = (convertIntTotalRegularPrice / (item.buyCycle * 7)).toFixed(2)
                } else {
                    const repliceValue = parseInt(item.buyCycle.replace('个月', '').replace('月', ''))
                    console.log('会输入月份的原始值', item.buyCycle)
                    console.log('替换会输入月份的结果', repliceValue)
                    itemYDate = (convertIntTotalRegularPrice / (repliceValue * 31)).toFixed(2)
                }
            }
            yData.value.push(itemYDate)
        });
        if (xData.value.length > 0) {
            nextTick(() => {
                if (charsType.value == '1') initHistoryCharLine()
                else initHistoryCharBar()
            });
        }
        loading.value = false
    })
}
const safeParseInt = (str) => {
    // 匹配可选的正负号后跟纯数字（不支持小数点或其他字符）
    const isValid = /^[+-]?\d+$/.test(str);
    return isValid ? parseInt(str, 10) : NaN; // 无效时返回 NaN
}
// 校验开始时间是否超过结束时间
const validateStartTime = (val) => {
    if (val && queryParams.value.endTime && new Date(val) > new Date(queryParams.value.endTime)) {
        proxy.$modal.msgError("开始时间不能晚于结束时间！")
        // 自动修正为与结束时间相同
        queryParams.value.startTime = queryParams.value.endTime;
    }
};

// 校验结束时间是否早于开始时间
const validateEndTime = (val) => {
    if (val && queryParams.value.startTime && new Date(val) < new Date(queryParams.value.startTime)) {
        proxy.$modal.msgError("结束时间不能早于开始时间！")
        // 自动修正为与开始时间相同
        queryParams.value.endTime = queryParams.value.startTime;
    }
};
// 对外暴漏方法
const initHistoryData = (_mediaId, _readonly) => { 
    historyDataOpen.value = true
    readonly.value = _readonly
    nextTick(() => {
        if (_mediaId) {
            queryParams.value.mediaId = _mediaId
            getMediaPriceList()
        }
    })
}

// 暴露方法\属性给父组件
defineExpose({
    initHistoryData
});
</script>
<style lang='scss'>
.mediaNameLabel {
    font-family: Microsoft YaHei;
    font-weight: 400;
    font-size: 16px;
    color: #1A75E6;
    cursor: pointer;
}

.mediaNameLabel:hover {
    text-decoration: underline solid #1A75E6 1px;
    text-underline-offset: 4px;
}

#historyChar {
    width: 100%;
    height: 350px;
}
</style>