<template>
    <div class="hc-datav-main hc-full">
        <img class="hc-datav-bg" :src="bgPng" alt="bg">
        <div id="hc-datav-header-body" class="relative">
            <div class="hc-datav-header">
                <img id="datav-header-bg" :src="png2" alt="头部图">
                <div class="header-title hc-flex-center w-full">
                    <div ref="nameRef" class="name hc-flex" @click="toHomePage">
                        <i class="i-solar-graph-outline" />
                        高速公路投资效益分析看板
                    </div>
                </div>
            </div>
            <div class="hc-datav-total relative p-[14px]">
                <el-row :gutter="24">
                    <el-col :span="12">
                        <HcDatavCard title="项目数" :num="projectNum" unit="" color="#D5DEFF" />
                    </el-col>
                    <el-col :span="12">
                        <HcDatavCard title="运营单位" :num="companyNum" unit="" color="#EEB500" />
                    </el-col>
                </el-row>
            </div>
            <div class="hc-datav-statics-1 relative p-[14px]">
                <el-row :gutter="24">
                    <el-col :span="8">
                        <div class="bg-box-card">
                            <div class="bg-box-card-title">
                                <i class="ri-share-line" /> <span>项目统计</span>
                            </div>
                            <div class="hc-full relative">
                                <ArrRoundChart
                                    ref="fixedChartRef" 
                                    :datas="typeTotal.reduce((acc, item) => {
                                        acc[item.type] = item.count
                                        return acc
                                    }, {})"
                                    :config="{
                                        color: ['#4B91FF', '#36CBCB', '#32C67C'],
                                        name: typeTotal.map(item => item.typeName),
                                        key: typeTotal.map(item => item.type),
                                        label: '项目统计',
                                        stageTotalVos: typeTotal,

                                    }"
                                    @chart-click="handleChartClick"
                                />
                            </div>
                        </div>
                    </el-col>
                    <el-col :span="8">
                        <div class="bg-box-card">
                            <div class="bg-box-card-title">
                                <i class="ri-numbers-line" style="color:rgb(62, 177, 165)" /> <span>运营统计</span>
                            </div>
                            <div class="hc-full relative">
                                <HcDatavBarChart
                                    :datas="companyTotal.map(item => ({
                                        name: item.operationCompany,
                                        value: item.count,
                                    }))"
                                    @chart-click="handleChartClick1"
                                />
                            </div>
                        </div>
                    </el-col>
                    <el-col :span="8">
                        <div class="bg-box-card">
                            <div class="bg-box-card-title flex justify-between">
                                <div> <i class="ri-line-chart-line" style="color:#18DD32" /> <span>收益统计</span></div>
                                <div ref="searchRef">
                                    <HcDatavSelect v-model="searchForm.year" :datas="yearArr" :clearable="false" @change="searchChange" />
                                    <HcDatavSelect v-model="searchForm.type" :datas="typeArr1" placeholder="项目类型" @change="searchChange" />
                                    <HcDatavSelect v-model="searchForm.size" :datas="typeArr2" placeholder="前五名" @change="searchChange" />
                                </div>
                            </div>
                            <div class="hc-full relative">
                                <HcDatavVerticalBarChart
                                    :datas="incomeTotal"
                                />
                            </div>
                        </div>
                    </el-col>
                </el-row>
            </div>
            <div class="hc-datav-statics-2 relative p-[14px]">
                <el-row :gutter="24">
                    <el-col :span="24">
                        <div class="bg-box-card-1">
                            <div class="bg-box-card-title flex justify-between">
                                <div> <i class="ri-taxi-wifi-line" style="color:#B3206F" /> <span>车流量统计</span></div>
                                <div ref="searchRef">
                                    <HcDatavSelect v-model="searchForm1.year" :datas="yearArr" :clearable="false" @change="searchChange1" />
                                    <HcDatavSelect v-model="searchForm1.type" :datas="typeArr1" placeholder="项目类型" @change="searchChange3" />
                                    <HcDatavSelect 
                                        v-if="searchForm1.type === 1"
                                        v-model="searchForm1.id" 
                                        :datas="operationCompanyOptions" 
                                        placeholder="项目名称" 
                                        @change="searchChange1" 
                                    />
                                    <HcDatavSelect 
                                        v-if="searchForm1.type === 2"
                                        v-model="searchForm1.operationCompany" 
                                        :datas="operationCompanyOptions" 
                                        placeholder="运营商名称" 
                                        @change="searchChange1" 
                                    />
                                </div>
                            </div>
                            <div class="hc-full relative">
                                <HcDatavLineChart
                                    :datas="companyListTotal"
                                />
                            </div>
                        </div>
                    </el-col>
                </el-row>
            </div>
        </div>
    </div>
</template>

<script setup>
import { onMounted, onUnmounted, ref } from 'vue'
import { useRouter } from 'vue-router'
import { useAppStore } from '~src/store'

import bgPng from '~src/assets/view/beijing.png'
import png2 from '~src/assets/view/preview.png'
import HcDatavSelect from './modules/select.vue'
import HcDatavCard from './modules/card.vue'
import HcDatavBarChart from './modules/echarts/HcDatavBarChart.vue'
import HcDatavVerticalBarChart from './modules/echarts/HcDatavVerticalBarChart.vue'
import HcDatavLineChart from './modules/echarts/HcDatavLineChart.vue'
import ArrRoundChart from './modules/echarts/HcDatavRoundChart.vue'
import { getArrValue, getObjValue } from 'js-fast-way'
import { getDictionary } from '~api/dictbiz.js'
import projectApi from '~api/promanage/project'
import dayjs from 'dayjs'
import { getMenuData } from '~src/router/routers'

const menuBarData = ref([])

//获取菜单数据
const getMenuBarData = async () => {
    menuBarData.value = await getMenuData()
   
}
const router = useRouter()
const store = useAppStore()

//引导
const nameRef = ref(null)


onMounted(async () => {

    await getMenuBarData()
 await getProType()
 await getDataProjectStat()
 await getTypeTotal()
 await getCompanyTotal()
 await getIncomeTotal()
 await getProOperationCompany(searchForm1.value.type)
 await getCompanyListTotal()
})
const projectNum = ref(0)
const companyNum = ref(0)
//获取项目统计
const getDataProjectStat = async ()=>{
    const { error, code, data } = await projectApi.total()
    //处理数据
    if (!error && code === 200) {
        let res = getObjValue(data)
        projectNum.value = res.projectNum
        companyNum.value = res.companyNum
    } else {
        projectNum.value = 0
        companyNum.value = 0
    }
}
//根据类型统计
const typeTotal = ref([])
const getTypeTotal = async ()=>{
    const { error, code, data } = await projectApi.typeTotal()
    //处理数据
    if (!error && code === 200) {
        let res = getArrValue(data)
       
        typeTotal.value = res
       
    } else {
        typeTotal.value = []
    }
}
const handleChartClick1 = (params) => {
 console.log(params, 'params')
//  router.push( { name: 'project-data', query: { operationCompany: params.name } })
const hasPermission = menuBarData.value.some(item => item.code === 'project2')
    if (!hasPermission) {
        return
    }
    
    router.push({ name: 'project-data', query: { operationCompany: params.name } })
 
}
//根据公司统计
const companyTotal = ref([])
const getCompanyTotal = async ()=>{
    const { error, code, data } = await projectApi.companyTotal()
    //处理数据
    if (!error && code === 200) {
        let res = getArrValue(data)
        companyTotal.value = res
       
    } else {
        companyTotal.value = []
    }
}
const yearArr = ref((() => {
    const currentYear = dayjs().year()
    const years = []
    // 前五年
    for (let i = 5; i > 0; i--) {
        const year = currentYear - i
        years.push({ id: `${year}`, name: `${year}年` })
    }
    // 当前年
    years.push({ id: `${currentYear}`, name: `${currentYear}年` })
    // 后五年
    for (let i = 1; i <= 5; i++) {
        const year = currentYear + i
        years.push({ id: `${year}`, name: `${year}年` })
    }
    return years
})())
const typeArr = ref([])
//项目类型

const getProType = async () => {
   await getTypeListData(1, 'ibaProjectType')
 }
 const routeOptions = ref([])
 //获取字典数
const getTypeListData = async (parentId, code) => {
        const { data } = await getDictionary({ parentId, code, type:2 })

        if (code === 'ibaProjectType') {
            typeArr.value = getArrValue(data).map(item => ({
                id: item.id,
                name: item.dictValue,
            }))
           if ( typeArr.value.length > 0) {
            searchForm.value.type = typeArr1.value[0].id
       
            searchForm.value.size = typeArr2.value[0].id
           }
            return
        } else {
            // routeOptions.value = getArrValue(data)
            routeOptions.value = getArrValue(data).map(item => ({
                id: item.id,
                name: item.dictValue,
            }))
            return
        }
        
    
    
}
const typeArr2 = ref([
    { id: 5, name: '前五名' },
    { id: 10, name: '前十名' },
    { id: 15, name: '前十五名' },
    { id: 20, name: '前二十名' },
])
const typeArr1 = ref([
    { id: 1, name: '项目' },
    { id: 2, name: '运营商' },
    
])
const fixedChartRef = ref(null)

//根据收益统计
const incomeTotal = ref([])
const getIncomeTotal = async ()=>{
   
    
    const { error, code, data } = await projectApi.incomeTotalList({
        type: searchForm.value.type,
        year:searchForm.value.year,
        size:searchForm.value.size,
    })
    //处理数据
    if (!error && code === 200) {
        let res = getArrValue(data)
     
        incomeTotal.value = res.map(item => ({
            // name: item.projectName,
            name:searchForm.value.type === 1 ? item.projectName : item.operationCompany,
            value: item.inflow,
        }))
        
       
    } else {
        incomeTotal.value = []
    }
}
//搜索表单

const searchRef = ref(null)
const searchForm = ref({
year: dayjs().year().toString(), type: null, size: null,
  
})
const searchChange = () => {

  getIncomeTotal()
}



const searchForm1 = ref({ id:'', year:dayjs().year().toString(), type:1, operationCompany:'' })
const searchChange1 = () => {
 
 getCompanyListTotal()
}
const searchChange3 = () => {
    getProOperationCompany(searchForm1.value.type)
    if (searchForm1.value.type === 1) {
        searchForm1.value.id = ''
    } else if (searchForm1.value.type === 2) {
        searchForm1.value.operationCompany = ''
    } else {
        searchForm1.value.id = ''
        searchForm1.value.operationCompany = ''
    }

}
//运营公司
const operationCompanyOptions = ref([])
const getProOperationCompany = async (type) => {

  
    const { error, code, data } = await projectApi.selectProjectOrCompanyList({ type: type })
    //处理数
    if (!error && code === 200) {
        operationCompanyOptions.value = getArrValue(data).map(item => ({
            id: type === 1 ? item.id : item.operationCompany,
            name: type === 1 ? item.projectName : item.operationCompany,
        }))
        if (type === 1 && searchForm1.value.id === '') {
            searchForm1.value.id = operationCompanyOptions.value[0].id
        } else if (type === 2 && searchForm1.value.operationCompany === '') {
            searchForm1.value.operationCompany = operationCompanyOptions.value[0].name
        }
        getCompanyListTotal()

    } else {
        operationCompanyOptions.value = []
        getCompanyListTotal()
    }
}
//根据车流量统计
const companyListTotal = ref([])
const getCompanyListTotal = async ()=>{
    const params = {
        year: searchForm1.value.year,
        type: searchForm1.value.type,
    }
    // 根据type类型添加对应的参数
    if (searchForm1.value.type === 1) {
        params.id = searchForm1.value.id
        params.operationCompany = ''
    } else if (searchForm1.value.type === 2) {
        params.operationCompany = searchForm1.value.operationCompany
        params.id = ''
    }
    const { error, code, data } = await projectApi.companyList(params)
    //处理数据
    if (!error && code === 200) {
        let res = getArrValue(data)
        companyListTotal.value = res.map(item => ({
            name: item.month + '月',
            value: item.number,
        }))
    } else {
        companyListTotal.value = []
    }
}

//跳转到首页
const toHomePage = () => {
    console.log(store.page)
    // router.push( { name: 'project-data' })
    const hasPermission = menuBarData.value.some(item => item.code === 'project2')
    console.log(hasPermission, 'hasPermission')
    
    if (!hasPermission) {
        return
    }
    
      router.push( { name: 'project-data' })
}

//监听浏览器窗口变化
//监听浏览器窗口变化
const windowResize = () => {
    window.addEventListener('resize', resizeEvent)
}
const resizeEvent = () => {
    window.requestAnimationFrame(() => {
        onWindowResize()
    })
}

//设置尺寸
const onWindowResize = () => {
    const height = document.getElementById('hc-datav-header-body').offsetHeight
    document.getElementById('hc-datav-row-total-body').style.height = `calc(100% - ${height + 10}px)`
}

//被卸载
onUnmounted(() => {
    window.removeEventListener('resize', resizeEvent)
})
// 在 script setup 中添加处理函数
const handleChartClick = (data) => {
    
    // router.push( { name: 'project-data', query: { type: data.type } })
    console.log(menuBarData.value, 'menuBarData.value')
    
    const hasPermission = menuBarData.value.some(item => item.code === 'project2')
    console.log(hasPermission, 'hasPermission')
    
    if (!hasPermission) {
        return
    }
    
    router.push( { name: 'project-data', query: { type: data.type } })
    // 这里可以添加您的业务逻辑
}
</script>

<style lang="scss" scoped>
@import '~src/styles/view/datav';
.bg-box-card{
    background-color: rgba(0, 43, 84, 0.8);
    border: 1px solid rgba(15, 84, 155, 0.8);
    border-radius: 4px;
    height: calc(34vh);  // 修改固定高度为动态高度
    padding: 14px;
}

.bg-box-card-1{
    background-color: rgba(0, 43, 84, 0.8);
    border: 1px solid rgba(15, 84, 155, 0.8);
    border-radius: 4px;
    height: calc(37vh - 17px);   // 修改固定高度为动态高度
    padding: 14px;
}
.bg-box-card-title{
    height: 25px;
    color:#5087EC;
    font-size: 18px;
    font-weight: 700;
    z-index: 999;
    margin-bottom: 15px;
 
}
// .hc-full {
//     height: calc(100% - 40px);  // 减去标题和padding的高度
//     overflow: hidden;
// }
</style>
