<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">
                    <el-form-item prop="targetType">
                        <el-select v-model="form.targetType" @change="changeTargetType">
                            <el-option v-for="item in typeData" :label="item.label" :value="item.value"></el-option>
                        </el-select>
                    </el-form-item>
                    <SelectTime ref="selectTimeRef" v-model="summaryType" v-model:query-params="form" />
                    <!-- <el-form-item prop="deptIds" v-if="navIndex == 1">
                        <SelectOrg authorty clearable :inputWidth="215" multiple v-model="form.deptIds" :type="3"></SelectOrg>
                    </el-form-item> -->
                    <el-form-item prop="ownerByIds" v-if="navIndex == 0">
                        <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>
        <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"
                :key="key"
            >
                <template #left>
                    <div>
                        {{ typeNameData[form.targetType].convertedNum }}：{{ conversionRateData?.totalconvertedNum }}，
                        {{ typeNameData[form.targetType].newNum }}：{{ conversionRateData?.totalNewNum }}，
                        {{ form.targetType == '31' ? '流失' : form.targetType == '30' ? '成交' : '转化' }}率：{{ conversionRateData?.totalConversionRate }}%
                    </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 { getConversionRateRanking } from '@/api/statistics/salesAnalysis'
import { SalesProcessQuery, SalesProcessVO } from '@/api/statistics/salesAnalysis/types';
import SelectTime from '../../components/selectTime.vue';
import useUserStore from '@/store/modules/user';

// 顶部类型切换
const headerNav = [
    { label: '个人排名', value: '80' },
    { label: '部门排名', value: '70' },
]
const navIndex = ref(0)
const key = ref(0)
const typeData = ref([
    { label: '线索转化率', value: '11', type: 'customerNum' },
    { label: '客户转化率', value: '12', type: 'clusNum' },
    { label: '商机成交率', value: '30', type: 'businessNum' },
    { label: '商机流失率', value: '31', type: 'orderFormNum' },
])
let typeNameData = {
    '11': { convertedNum: '新增线索', newNum: '已转客户' },
    '12': { convertedNum: '新增客户', newNum: '首次商机' },
    '30': { convertedNum: '商机总数', newNum: '成交商机' },
    '31': { convertedNum: '商机总数', newNum: '流失商机' },
}
const summaryType = ref('30')
const { userInfo } = useUserStore();
const form = ref({
    deptIds: [],
    ownerByIds: [userInfo.id],
    beginCycleTime: moment().subtract(12, 'months').format('YYYY-MM') + '-01',
    endCycleTime: moment().endOf('month').format('YYYY-MM-DD'),
    summaryType: '80',
    targetType: '11'
})

const tableData = ref([])
const conversionRateData = ref()
const getData = () => {
    let params = JSON.parse(JSON.stringify(form.value))
    if(params.summaryType == '80') {
        delete params.deptIds
    } else {
        delete params.ownerByIds
    }
    getConversionRateRanking(params).then(res => {
        if(res.success) {
            conversionRateData.value = res.result
            tableData.value = res.result.datas
            let xAxisData = res.result.datas.map(item => form.value.summaryType == '80' ? item.groupType : item.deptName)
            echartsOption.xAxis.data = xAxisData
            echartsOption.series = [
                {
                    name: form.value.targetType == '31' ? '流失率' : form.value.targetType == '30' ? '成交率' : '转化率',
                    type: 'bar',
                    barWidth: 18,
                    color: '#3F9EFF',
                    itemStyle: {
                        borderRadius: [4, 4, 0, 0] // 这里设置圆角的大小
                    },
                    data: res.result.datas.map(item => item.conversionRate)
                }
            ]
        }
    })
}

const echartsOption = reactive({
    tooltip: {
        formatter: '{a} : {c}%',
    },
    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轴颜色
            }
        },
        data: []
    },
    yAxis: {},
    series: []
})

const queryFormRef = ref<ElFormInstance>();

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

const { tableColumn } = toRefs(tableParams)

const changeNav = (index: number, val: string) => {
    key.value ++
    navIndex.value = index
    form.value.summaryType = val
    changeTableColumn(index)
    getData()
}
const changeTableColumn = (index) => {
    tableColumn.value = [
        { show: true, label: '排名', prop: 'index', render: ({ index }) => {
            return index + 1
        }},
        { show: index == 0, label: '员工姓名', prop: 'groupType' },
        { show: index == 0, label: '所在部门', prop: 'deptName' },
        { show: index == 1, label: '部门名称', prop: 'deptName' },
        { show: true, label: typeNameData[form.value.targetType].convertedNum, prop: 'convertedNum' },
        { show: true, label: typeNameData[form.value.targetType].newNum, prop: 'newNum' },
        { show: true, label: form.value.targetType == '31' ? '流失率' : form.value.targetType == '30' ? '成交率' : '转化率', prop: 'conversionRate', render: ({ column }) => {
            return column.conversionRate + '%'
        } }
    ]
}
changeNav(0, '80')
const changeTargetType = () => {
    key.value ++
    handleQuery()
}

/** 搜索按钮操作 */
const handleQuery = () => {
    changeTableColumn(navIndex.value)
    getData()
}

/** 重置按钮操作 */
const selectTimeRef = ref()
const resetQuery = () => {
    queryFormRef.value?.resetFields();
    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>
