<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.label }}
                            <i :class="navIndex == index ? 'on' : ''"></i>
                        </div>
                    </template>
                </div>
            </template>
            <div class="search">
                <el-form :model="form" ref="queryFormRef" :inline="true">
                    <el-form-item prop="rangeTime">
                        <el-date-picker type="monthrange" v-model="rangeTime" :clearable="false" range-separator="-"
                            start-placeholder="请选择月份区间" end-placeholder="请选择月份区间" value-format="YYYY-MM"
                            @change="changeTime" />
                    </el-form-item>
                    <!-- <el-form-item prop="deptIds">
                        <SelectOrg authorty clearable :inputWidth="215" multiple v-model="form.deptIds" :type="3"></SelectOrg>
                    </el-form-item> -->
                    <el-form-item prop="ownerByIds">
                        <SelectUser authorty 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>
        <template v-if="navIndex == 0">
            <div class="echarts-body">
                <Echart :height="450" :options="echartsOption" />
            </div>
            <div class="table-body">
                <Table :tableParams="tableParams" :isCheckbox='false' :rightBtn="[]" :btnRole="[]" :isPagination="false"
                    :tableData="tableData">
                    <template #left>
                        <div>商机数量: {{ salesFunnelData?.businessNumTotal }}，
                            预计销售金额：¥ {{ salesFunnelData?.salesAmountTotal }}，
                            概率金额：¥ {{ salesFunnelData?.expectedSalesAmountTotal }}
                        </div>
                    </template>
                    <!-- <template #right>
                        <el-button>导出</el-button>
                    </template> -->
                </Table>
            </div>
        </template>
        <div class="table-body" style="margin-top: 16px;" v-else>
            <Table ref="salesFunnelTable" :tableParams="detailTableParams" :isCheckbox='false' :rightBtn="[]"
                :btnRole="[]">
                <template #left>
                    <div>商机数量：{{ salesFunnelData?.businessNumTotal }}，
                        预计销售金额：¥ {{ salesFunnelData?.salesAmountTotal }}，
                        概率金额：¥ {{ salesFunnelData?.expectedSalesAmountTotal }}
                    </div>
                </template>
                <!-- <template #right>
                    <el-button style="margin-left: 10px;">导出</el-button>
                </template> -->
            </Table>
        </div>
    </div>
</template>

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

// 顶部类型切换
const headerNav = [
    { label: '漏斗分析', value: '0' },
    { label: '漏斗报表', value: '10' },
]
const navIndex = ref(0)
const changeNav = (index: number) => {
    navIndex.value = index
    if(index == 0) {
        getData()
    }
}

const nowYear = moment().format('YYYY')
const rangeTime = ref([nowYear + '-01', nowYear + '-12'])
const changeTime = (val) => {
    form.value.beginCycleTime = val ? val[0] + '-01' : ''
    form.value.endCycleTime = val ? moment(val[1]).endOf('month').format('YYYY-MM-DD') : ''
}
const { userInfo } = useUserStore();
const form = ref({
    // deptIds: [userInfo.deptId],
    ownerByIds: [userInfo.id],
    beginCycleTime: nowYear + '-01-01',
    endCycleTime: nowYear + '-12-31'
})

const tableData = ref([])
const salesFunnelData = ref()
const dataSource = ref([])
const legendData = ref([])
const getData = () => {
    dataSource.value = []
    legendData.value = []
    getSalesFunnelTotal(form.value).then(res => {
        if(res.success) {
            salesFunnelData.value = res.result
            tableData.value = res.result.businessStageCountls
            legendData.value = res.result.businessStageCountls.map(item => item.stageName)
            res.result.businessStageCountls.map(item => {
                let obj = { value: item.businessNumRatio, name: item.stageName }
                dataSource.value.push(obj)
            })
            echartsOption.legend.data = legendData.value
            echartsOption.series[0].data = dataSource.value
        }
    })
}

const echartsOption = reactive({
    tooltip: {
        trigger: 'item',
        formatter: '{b} : {c}%'
    },

    legend: {
        orient: 'horizontal', // 水平布局
        bottom: 0, // 距离底部0像素
        data: legendData.value
    },
    series: [
        {
            name: 'funnel',
            type: 'funnel',
            left: '10%',
            top: 30,
            bottom: 30,
            width: '80%',
            min: 0,
            max: 100,
            minSize: '0%',
            maxSize: '100%',
            sort: 'descending',
            gap: 2,
            label: {
                show: true,
                position: 'outside',
                normal: {
                    textStyle: {
                        // 设置文本阴影颜色为透明
                        textBorderWidth: 0,
                        textBorderColor:'#666666'
                    }
                }
            },
            labelLine: {
                length: 10,
                lineStyle: {
                    width: 1,
                    type: 'solid'
                }
            },
            itemStyle: {
                borderColor: '#fff',
                borderWidth: 1,
                normal: {
                    color: function(params) {
                        // params是当前数据项的信息
                        const colors = ['#2989FF', '#29CCCB', '#F18E56', '#D787FF', '#7F6BFF'];
                        return colors[params.dataIndex];
                    }
                }
            },
            emphasis: {
                label: {
                    fontSize: 20
                }
            },
            data: dataSource.value
        }
    ]
})


const queryFormRef = ref<ElFormInstance>();

const tableParams = reactive<tableTypes<SalesProcessQuery, SalesProcessVO>>({
    tableColumn: [
        { show: true, label: '销售阶段', prop: 'stageName' },
        { show: true, label: '商机数量', prop: 'businessNum' },
        { show: true, label: '占比', prop: 'businessNumRatio', render: ({ column }) => {
            return column.businessNumRatio + '%'
        } },
        {
            show: true, label: '转化率', prop: 'stageSurnoverRatio',
            headerQuestionFilled: { content: '转化率计算方式：大于当前阶段的商机之和除以大于等于商机总和，流失商机数量不计算在内', width: 300 },
            render: ({ column }) => {
                return column.stageSurnoverRatio + '%'
            }
        },
        { show: true, label: '预计销售金额', prop: 'salesAmount' },
        { show: true, label: '概率金额', prop: 'expectedSalesAmount', headerQuestionFilled: { content: '预计签单金额*成交机率', width: 180 } }
    ]
})

const detailTableParams = reactive<tableTypes<SalesProcessQuery, SalesProcessVO>>({
    tableColumn: [
        { show: true, label: '商机标题', prop: 'title' },
        { show: true, label: '对应客户', prop: 'customerName' },
        { show: true, label: '预计签单日期', prop: 'expectedSigningDate' },
        { show: true, label: '预计销售金额', prop: 'estimatedSalesAmount' },
        { show: true, label: '销售阶段', prop: 'stageName' },
        { show: true, label: '成交机率', prop: 'stransactionProbabilityName' },
        { show: true, label: '概率金额', prop: 'expectedSalesAmount' },
        { show: true, label: '负责人员', prop: 'ownerByName' }
    ],
    queryParams: form.value,
    listFn: listSalesFunnel
})

const salesFunnelTable = ref()
/** 搜索按钮操作 */
const handleQuery = () => {
    getData()
    if(navIndex.value == 1) {
        salesFunnelTable.value?.getData()
    }
}

/** 重置按钮操作 */
const resetQuery = () => {
    queryFormRef.value?.resetFields();
    rangeTime.value = [nowYear + '-01', nowYear + '-12']
    form.value.beginCycleTime = nowYear + '-01-01'
    form.value.endCycleTime = nowYear + '-12-31'
    handleQuery();
}

onBeforeMount(() => {
    getData()
})
</script>
