<template>
    <div class="charts_area">
        <el-card shadow="never">
            <template #header>
                <div class="top_nav flex">
                    <template v-for="(item,index) in headerNav">
                        <div class="nav_list" @click="changeNav(index,item.value)">
                            {{ item.label }}
                            <i :class="navIndex == index ? 'on' : ''"></i>
                        </div>
                    </template>
                </div>
            </template>
            <div class="search">
                <el-form :model="form" ref="queryFormRef" :inline="true">
                    <SelectTime
                        ref="selectTimeRef"
                        v-model="summaryType"
                        :monthName="navIndex == 0 ? '按月统计' : '按月'"
                        :dayName="navIndex == 0 ? '按日统计' : '按日'"
                        :daysLimit="navIndex == 0"
                        v-model:query-params="form"
                        @changeSummary="changeSummary"
                    />
                    <el-form-item prop="deptIds" v-if="navIndex == 2">
                        <SelectOrg authorty clearable :inputWidth="215" multiple v-model="form.deptIds" :type="3"></SelectOrg>
                    </el-form-item>
                    <el-form-item prop="createByIds" v-if="navIndex != 2">
                        <SelectUser authorty :deptIds="form.deptIds" multiple v-model="form.ownerByIds"></SelectUser>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" icon="Search" @click="handleQuery">查询</el-button>
                        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
                    </el-form-item>
                </el-form>
            </div>
        </el-card>
        <div class="echarts-body">
            <Echart :height="450" :options="echartsOptionLine" />
        </div>
        <div class="table-body">
            <Table
                :tableParams="tableParams"
                :isCheckbox='false'
                :rightBtn="[]"
                :btnRole="[]"
                :isPagination="false"
                :tableData="tableData"
                :key="navIndex"
            >
                <template #left>
                    <div>
                        新增线索：{{ businessCountData?.clusNumTotal }}，
                        新增商机：{{ businessCountData?.businessNumTotal }}，
                        新增客户：{{ businessCountData?.customerNumTotal }}，
                        新增订单：{{ businessCountData?.orderFormNumTotal }}
                    </div>
                </template>
                <!-- <template #right>
                    <el-button style="margin-left: 10px;">导出</el-button>
                </template> -->
            </Table>
        </div>
    </div>
  </template>

<script setup name="completionDegree" lang="ts">
import auth from '@/plugins/auth'
import Table from '@/components/Table/index.vue'
import { tableTypes } from '@/components/Table/types'
import { getNewBusinessCountTotal } from '@/api/statistics/salesAnalysis'
import { SalesProcessQuery, SalesProcessVO } from '@/api/statistics/salesAnalysis/types';
import moment from 'moment'
import SelectTime from '../../components/selectTime.vue';
import useUserStore from '@/store/modules/user';

const summaryType = ref('30')
const { userInfo } = useUserStore();
const form = ref({
    summaryType: '30',
    beginCycleTime: moment().subtract(12, 'months').format('YYYY-MM') + '-01',
    endCycleTime: moment().endOf('month').format('YYYY-MM-DD'),
    deptIds: [],
    ownerByIds: [userInfo.id]
})

const queryFormRef = ref<ElFormInstance>();
const tableParams = reactive<tableTypes<SalesProcessQuery, SalesProcessVO>>({
    tableColumn: []
})

const { tableColumn } = toRefs(tableParams);

// 顶部客户类型切换
const headerNav = [
    { label: '按创建时间汇总', value: '30' },
    { label: '按创建人员汇总', value: '80' },
    { label: '按部门汇总', value: '70' }
]
const navIndex = ref(0)

const tableData = ref([])
const businessCountData = ref()
const xAxisData = ref([])
const countData = ref({
    clue: [],
    business: [],
    customer: [],
    order: []
})
const getData = () => {
    let params = JSON.parse(JSON.stringify(form.value))
    if(form.value.summaryType == '80') {
        params.createByIds = params.ownerByIds
        delete params.ownerByIds
    }
    params.queryTimeType = navIndex.value == 0 ? 10 : 20
    getNewBusinessCountTotal(params).then(res => {
        if(res.success) {
            businessCountData.value = res.result
            tableData.value = res.result.datas
            if(navIndex.value === 0) {
                xAxisData.value = tableData.value.map(item => item.groupTypeName)
                countData.value = {
                    clue: tableData.value.map(item => item.clusNum),
                    business: tableData.value.map(item => item.businessNum),
                    customer: tableData.value.map(item => item.customerNum),
                    order: tableData.value.map(item => item.orderFormNum)
                }
                echartsOptionLine.value = {
                    tooltip: {
                        trigger: 'axis'
                    },
                    legend: {
                        data: ['线索', '商机', '客户', '订单'],
                        top: 'bottom'
                    },
                    grid: {
                        top: '8%',
                        left: '3%',
                        right: '4%',
                        bottom: '10%',
                        containLabel: true
                    },
                    xAxis: {
                        type: 'category',
                        // boundaryGap: false,
                        data: xAxisData.value
                    },
                    yAxis: {
                        type: 'value'
                    },
                    series: [
                        {
                            name: '线索',
                            type: 'line',
                            stack: 'Total',
                            data: countData.value.clue
                        },
                        {
                            name: '商机',
                            type: 'line',
                            stack: 'Total',
                            data: countData.value.business
                        },
                        {
                            name: '客户',
                            type: 'line',
                            stack: 'Total',
                            data: countData.value.customer
                        },
                        {
                            name: '订单',
                            type: 'line',
                            stack: 'Total',
                            data: countData.value.order
                        }
                    ]
                }
            }else {
                echartsOptionLine.value = {
                    tooltip: {
                        trigger: 'axis',
                        axisPointer: {
                            crossStyle: {
                                color: '#999'
                            }
                        }
                    },
                    legend: {
                        top: 'bottom'
                    },
                    grid: {
                        left: '16px',    // 组件离容器左侧的距离
                        right: '16px',   // 组件离容器右侧的距离
                        bottom: '36px',  // 组件离容器底部的距离
                        top: '16px',    // 组件离容器顶部的距离
                        containLabel: true // 如果为true，则grid 区域会根据标签大小自动调整
                    },
                    xAxis: {
                        type: 'category',
                        axisLabel: {
                            interval: 0,
                            color: '#333', //坐标轴字体颜色
                        },
                        axisLine: {
                            lineStyle: {
                                color: '#EBEFF3' // 修改x轴颜色
                            }
                        },
                        axisPointer: {
                            type: 'shadow'
                        },
                        data: res.result.datas.map(item => item.groupTypeName)
                    },
                    yAxis: {},
                    series: [
                        {
                            name: '线索',
                            type: 'bar',
                            barWidth: 18,
                            color:'#3F9EFF',
                            itemStyle: {
                                borderRadius: [4, 4, 0, 0] // 这里设置圆角的大小
                            },
                            data: res.result.datas.map(item => item.clusNum)
                        },
                        {
                            name: '商机',
                            type: 'bar',
                            barWidth: 18,
                            itemStyle: {
                                color:'#58CC74',
                                borderRadius: [4, 4, 0, 0] // 这里设置圆角的大小
                            },
                            data: res.result.datas.map(item => item.businessNum)
                        },
                        {
                            name: '客户',
                            type: 'bar',
                            barWidth: 18,
                            itemStyle: {
                                color:'#fbd337',
                                borderRadius: [4, 4, 0, 0] // 这里设置圆角的大小
                            },
                            data: res.result.datas.map(item => item.customerNum)
                        },
                        {
                            name: '订单',
                            type: 'bar',
                            barWidth: 18,
                            itemStyle: {
                                color:'#435188',
                                borderRadius: [4, 4, 0, 0] // 这里设置圆角的大小
                            },
                            data: res.result.datas.map(item => item.orderFormNum)
                        },
                    ]
                }
            }
        }
    })
}

const changeNav = (index: number, val: string) => {
    form.value.summaryType = val
    navIndex.value = index
    tableColumn.value = [
        { show: navIndex.value == 0, label: '时间', prop: 'groupTypeName' },
        { show: navIndex.value == 1, label: '员工姓名', prop: 'groupTypeName' },
        { show: navIndex.value == 1, label: '所在部门', prop: 'deptName' },
        { show: navIndex.value == 2, label: '部门名称', prop: 'groupTypeName' },
        { show: true, label: '新增线索', prop: 'clusNum' },
        { show: true, label: '新增商机', prop: 'businessNum' },
        { show: true, label: '新增客户', prop: 'customerNum' },
        { show: true, label: '新增订单', prop: 'orderFormNum' }
    ]
    form.value.deptIds = index == 2 ? [userInfo.deptId] : []
    form.value.ownerByIds = index != 2 ? [userInfo.id] : []
    getData()
}
changeNav(0, '30')

const changeSummary = (val) => {
    if(navIndex.value == 0) {
        form.value.summaryType = val
    }
}

const echartsOptionLine = ref({})

const handleQuery = () => {
    getData()
}

/** 重置按钮操作 */
const selectTimeRef = ref()
const resetQuery = () => {
    queryFormRef.value?.resetFields();
    form.value.summaryType = form.value.summaryType == '50' ? '30' : form.value.summaryType
    summaryType.value = '30'
    form.value.beginCycleTime = moment().subtract(12, 'months').format('YYYY-MM') + '-01'
    form.value.endCycleTime = moment().endOf('month').format('YYYY-MM-DD')
    selectTimeRef.value?.resetTime()
    handleQuery();
}
</script>
