<template>
    <uni-card title="项目计划统计" extra="更多" margin="0px" padding="0px">
        <view style="height: 300px;">
            <LEchart ref="chartRef" style="width: 100%;height: 100%;" @touchstart="touchStart" @touchmove="touchMove"
                @touchend="touchEnd" />
        </view>
    </uni-card>
</template>

<script setup lang="ts">
import LEchart from '@/components/l-echart/l-echart.vue';
import { ref, watch, nextTick, onMounted, getCurrentInstance } from 'vue'
import {
    endOfYear,
    format,
    startOfYear,
    eachDayOfInterval,
    startOfDay,
    subMonths,
    subWeeks
} from 'date-fns'
import useChartOption from '@/hooks/chart-option'
import { LineSeriesOption } from 'echarts/types/dist/echarts';
import { ProjectPlanStatReqParams } from '@/types/dashboard';
import { getProjectPlanStat } from '@/api/dashboard/project';

// #ifdef MP
const echarts = require('./static/echarts.min')
// #endif

// #ifndef MP
// import * as echarts from 'echarts'
// #endif

const { mobile } = uni.getStorageSync('info_status')
const units = ['个', '个', '个', '%']
const chartRef = ref()
const dateType = ref(2)
const totalCount = ref<any[]>([])
const inCompleteCount = ref<any[]>([])
const delayedCount = ref<any[]>([])
const delayRate = ref<any[]>([])
const xAxisStat = ref<string[]>([])
const proxy = getCurrentInstance()?.proxy
const { $onLaunched } = proxy as any
const preloadData = [{
    "id": "",
    "dataset": {},
    "left": 0,
    "right": 375,
    "top": 0,
    "bottom": 0,
    "width": "100%",
    "height": "100%",
    "skeletonType": "rect"
}]

const requestData = reactive<{
    beginAt: Date
    endAt: Date
    dateType: number
}>({
    dateType: 0,
    beginAt: subWeeks(new Date(), 1),
    endAt: startOfDay(new Date())
})
const initData = async (data: any) => {
    await nextTick()
    if (chartRef.value) {
        const myChart = await chartRef.value?.init(echarts)
        myChart.setOption(data)
    }
}

function graphicFactory(side: AnyObject) {
    return {
        type: 'text',
        bottom: '8',
        ...side,
        style: {
            text: '',
            textAlign: 'center',
            fill: '#4E5969',
            fontSize: 12
        }
    }
}
const graphicElements = ref([
    graphicFactory({ left: '2.6%' }),
    graphicFactory({ right: 0 })
])

const generateSeries = (
    name: string,
    lineColor: string,
    itemBorderColor: string,
    data: number[]
): LineSeriesOption => {
    return {
        name,
        data,
        type: 'line',
        smooth: true,
        connectNulls: true,
        symbol: 'circle',
        symbolSize: 8,
        itemStyle: {
            color: lineColor
        },
        emphasis: {
            focus: 'series',
            itemStyle: {
                color: lineColor,
                borderWidth: 2,
                borderColor: itemBorderColor
            }
        },
        lineStyle: {
            width: 2,
            color: lineColor
        },
        showSymbol: false,
        areaStyle: {
            opacity: 0.1,
            color: lineColor
        }
        // label: {
        //   show: true,
        //   formatter: params => {
        //     // 当数据值为 0 时，不显示标签
        //     return params.value === 0 ? '' : params.value
        //   }
        // }
    }
}

const { chartOption } = useChartOption(() => {
    return {
        animation: false,
        legend: {
            show: true,
            width: '80%',
            textStyle: {
                color: '#333'
            }
        },
        grid: {
            right: '0',
            bottom: '30'
        },
        xAxis: {
            type: 'category',
            data: xAxisStat.value,
            axisLine: {
                show: true
            },
            axisTick: {
                show: true
            },
            splitLine: {
                show: true
            },
            axisPointer: {
                show: true,
                lineStyle: {
                    color: '#23ADFF',
                    width: 2
                }
            }
        },
        yAxis: {
            type: 'value',
            axisLine: {
                show: true
            },
            splitLine: {
                lineStyle: {
                    color: '#F2F3F5'
                }
            }
        },
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'shadow'
            },
            confine: true
        },
        graphic: {
            elements: graphicElements.value
        },
        series: [
            generateSeries(
                '总任务数',
                'rgb(22, 93, 255)',
                'rgb(232, 243, 255)',
                totalCount.value
            ),
            generateSeries(
                '未完成任务数',
                '#F77234',
                '#FFE4BA',
                inCompleteCount.value
            ),
            generateSeries('任务延期数', '#33D1C9', '#E8FFFB', delayedCount.value),
            generateSeries('任务延期率', '#722ED1', '#F5E8FF', delayRate.value)
        ]
    }
})

const getDataStat = async () => {
    try {
        xAxisStat.value = []
        totalCount.value = []
        inCompleteCount.value = []
        delayedCount.value = []
        delayRate.value = []
        const { beginAt, endAt } = requestData
        const params: ProjectPlanStatReqParams = {
            begin_at: format(beginAt, 'yyyy-MM-dd'),
            end_at: format(endAt, 'yyyy-MM-dd')
        }
        const xValue = eachDayOfInterval({
            start: beginAt,
            end: endAt
        }).map(item => {
            return format(item, 'yyyy-MM-dd')
        })
        xAxisStat.value = xValue
        await $onLaunched;
        if(!mobile){
            return
        }
        const { list } = await getProjectPlanStat(params)
        xValue.map(item => {
            const data = list.find(l => l.ts === item)
            if (data) {
                totalCount.value.push(data.total_count)
                inCompleteCount.value.push(data.incomplete_count)
                delayedCount.value.push(data.delayed_count)
                delayRate.value.push(data.delay_rate)
            } else {
                totalCount.value.push(null)
                inCompleteCount.value.push(null)
                delayedCount.value.push(null)
                delayRate.value.push(null)
            }
            return item
        })
    } catch (e) {
        console.log(e)
    }
}

onMounted(() => {
    getDataStat()
})

watch(
    () => chartOption.value,
    () => {
        initData(chartOption.value)
    },
    {
        flush: 'post',
        deep: true
    }
)

const touchStart = (e: any) => {
    chartRef.value.touchStart(e)
}

const touchMove = (e: any) => {
    chartRef.value.touchMove(e)
}


const touchEnd = (e: any) => {
    chartRef.value.touchEnd(e)
}

</script>
