<template>
    <div class="charts_area">
        <el-card shadow="never">
            <template #header>
                <div class="top_nav flex">
                    <template v-for="(item,index) in headerNav" :key="index">
                        <div class="nav_list" v-if="item.show"
                            @click="changeNav(item.value)">{{ item.label }}<i
                            :class="pageVal==item.value?'on':''"></i></div>
                    </template>
                </div>
            </template>
            <div class="search">
                <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="68px">
                    <el-form-item prop="blurry">
                        <el-form-item>
                            <el-date-picker
                                v-model="daterange"
                                type="monthrange"
                                range-separator="-"
                                value-format="YYYY-MM-DD"
                                start-placeholder="开始年月"
                                end-placeholder="结束年月"
                                @change="getDate"
                            />
                        </el-form-item>
                    </el-form-item>
                    <!-- <el-form-item prop="blurry">
                        <SelectOrg authorty clearable multiple  v-model="queryParams.deptIds"></SelectOrg>
                    </el-form-item> -->
                    <el-form-item prop="blurry">
                        <SelectUser authorty :deptIds="queryParams.deptIds" multiple v-model="queryParams.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" v-if="pageVal!='30'"/>
            <Echart :height="450" :options="echartsOptionCategory" v-else />
        </div>
        <div class="table-body">
            <Table ref="publicTable"
                :tableParams="tableParams"
                :isCheckbox='false'
                :rightBtn="[]"
                :btnRole="[]"
                :isPagination="false"
                :key="pageVal"
                :tableData="tableData"
            >
            <template #left>
                <div>新增客户：{{addCustomerData}}</div>
            </template>
            </Table>
        </div>

    </div>


  </template>

  <script setup name="customerAttributeAnalysis" lang="ts">
  import moment from 'moment'
  import auth from '@/plugins/auth'
  import {useDictCache} from '@/hooks/web/useDict'
  import {tableTypes} from '@/components/Table/types'
  import {countryAnalytics,levelAnalytics,sourceAnalytics,statusAnalytics} from '@/api/statistics/data';
  import { EChartsOption } from 'echarts'
  import { DataVO, DataQuery } from '@/api/statistics/data/types';
  import useUserStore from '@/store/modules/user';
//   import SelectUser from '@/components/SelectOrg/SelectUser.vue'
  const { queryDictDetailByCodes } = useDictCache(['work_data_group', 'follow_up_type',])
  queryDictDetailByCodes()
  const route = useRoute()
  const queryFormRef = ref<ElFormInstance>();

    const publicTable = ref()
    const {userInfo } = useUserStore()
    /** 重置按钮操作 */
    const resetQuery = () => {
        queryParams.value = {
            deptId:'',
            beginCycleTime:null,
            endCycleTime:null,
            ownerByIds: [userInfo.id],
            // deptIds: [userInfo.deptId],
        }
        daterange.value = ''
        handleQuery();
    }

    const tableParams = reactive<tableTypes<DataQuery, DataVO>>({
        tableColumn: [],
        queryParams: {
            beginTime:null,
            endTime:null,
            blurry:'',
            ownerByIds: [userInfo.id],
            // deptIds: [userInfo.deptId],
        },
    })
    const daterange = ref('')
    const getDate = (val: string[] | null) => {
        tableParams.queryParams.beginTime = val ? val[0] : ''
        tableParams.queryParams.endTime = val ? moment(val[1]).endOf('month').format('YYYY-MM-DD') : ''
    }
    const {queryParams,tableColumn} = toRefs(tableParams);

    const echartsOption = reactive({
        title: {},
        tooltip: {
            trigger: 'item'
        },
        legend: {
            orient: 'vertical',
            bottom: 'bottom'
        },
        series: [
            {
                name: '新增客户',
                type: 'pie',
                radius: '50%',
                data: [],
                label:{
                    formatter:'{b}:{c}%',
                    color: "#000",
                    fontSize:14,
                    fontFamily:'宋体'
                },
                emphasis: {
                    itemStyle: {
                        shadowBlur: 10,
                        shadowOffsetX: 0,
                        shadowColor: 'rgba(0, 0, 0, 0.5)',
                    },
                },
                // textStyle:{

                // }
            }
        ]
    })

    const echartsOptionCategory = reactive({
        tooltip: {},
        grid: {
            left: '16px',    // 组件离容器左侧的距离
            right: '16px',   // 组件离容器右侧的距离
            bottom: '36px',  // 组件离容器底部的距离
            top: '16px',    // 组件离容器顶部的距离
            containLabel: true // 如果为true，则grid 区域会根据标签大小自动调整
        },
        dataset: {
            source: [
                ['区域', '新增客户'],
            ]
        },

        xAxis: {
            type: 'category',
            axisLabel: {
                interval: 0,
                color: '#333', //坐标轴字体颜色
            },
            axisLine: {
                lineStyle: {
                    color: '#EBEFF3' // 修改x轴颜色
                }
            },
        },
        yAxis: {},
        series: [
            {
                type: 'bar',
                barWidth: 24,
                color:'#3F9EFF',
                itemStyle: {
                    borderRadius: [4, 4, 0, 0] // 这里设置圆角的大小
                }
            },
        ]
    })

    // 顶部类型切换
    const headerNav = [
        {label: '客户状态', value: '0',perPrefix: '',show: true},
        {label: '客户等级', value: '10',perPrefix: '', show: true},
        {label: '客户来源', value: '20',perPrefix: '', show: true},
        {label: '所在区域', value: '30',perPrefix: '', show: true},
    ]

    const navIndex = ref('0')
    const pageVal = ref()
    const changeNav = (val: string) => {
        pageVal.value = val
        tableColumn.value=[
            {show: true, label: '名称', prop: 'customerStatusName', sortable: false},
            {show: true, label: '新增客户', prop: 'addCustomerNum', sortable: false},
            {show: true, label: '新增占比', prop: 'customerStatusPercent', sortable: false, render: ({ column }: { column: DataVO }) => {
                 return column.customerStatusPercent +'%'
            }},
            {show: true, label: '跟进次数', prop: 'followUpNum', sortable: false},
            {show: true, label: '成交次数', prop: 'dealNum', sortable: false},
            {show: true, label: '成交总额', prop: 'dealTotal', sortable: false},
        ]
        if(val=='0'){
        }else if(val=='10'){
            tableColumn.value[0].prop = 'customerLevelName'
        }else if(val=='20'){
            tableColumn.value[0].prop = 'customerSourceName'
        }else if(val=='30'){
            tableColumn.value[0].prop = 'country'
        }
        handleQuery()
    }



    const tableData = ref([])
    const addCustomerData = ref()
    const handleQuery = () => {
        echartsOption.series[0].data = []
        echartsOptionCategory.dataset.source = []
        if(pageVal.value=='0'){ //状态
            statusAnalytics(tableParams.queryParams).then(res => {
                if(res.success) {
                    addCustomerData.value =  res.result.number
                    tableData.value = res.result.list
                    if(res.result.list){
                        res.result.list.forEach(item=>{
                            echartsOption.series[0].data.push({value:item.customerStatusPercent,name:item.customerStatusName})
                        })
                    }
                }
            })
        }else if(pageVal.value=='10'){ //等级
            levelAnalytics(tableParams.queryParams).then(res => {
                if(res.success) {
                    addCustomerData.value =  res.result.number
                    tableData.value = res.result.list
                    if(res.result.list){
                        res.result.list.forEach(item=>{
                            echartsOption.series[0].data.push({value:item.customerStatusPercent,name:item.customerLevelName})
                        })
                    }
                }
            })
        }else if(pageVal.value=='20'){ //来源
            sourceAnalytics(tableParams.queryParams).then(res => {
                if(res.success) {
                    addCustomerData.value =  res.result.number
                    tableData.value = res.result.list
                    if(res.result.list){
                        res.result.list.forEach(item=>{
                            echartsOption.series[0].data.push({value:item.customerStatusPercent,name:item.customerSourceName})
                        })
                    }
                }
            })
        }else if(pageVal.value=='30'){ //区域
            countryAnalytics(tableParams.queryParams).then(res => {
                if(res.success) {
                    addCustomerData.value =  res.result.number
                    tableData.value = res.result.list
                    if(res.result.list){
                        res.result.list.forEach(item=>{
                            echartsOptionCategory.dataset.source.push([item.country,item.addCustomerNum])
                        })
                    }
                }
            })
        }

    }



    const selectsUser = (data: { realName: string,id:number|string }[]) => {
        // form.value.ownerByName = data[0].realName
        // form.value.ownerBy = data[0].id
    }

  onMounted(() => {
      let type = route.query.type as string
      pageVal.value = type
      changeNav(type)
  });
  </script>

  <style lang="scss" scoped>
  .top_nav{
    margin: 0;
  }
  .search .el-form-item--default{
    margin-bottom:0;
  }
.echarts-body{
    background-color: #fff;
    border-radius: 4px;
    margin:16px 0;
    padding:10px 0;
}
.table-body{
    background-color: #fff;
    border-radius: 4px;
    padding:16px;
}
  </style>
