<template>
    <div class="charts_area">
        <el-card shadow="never">
            <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 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">
            <div class="echarts-title">
                <span>客户状态</span>
                <span class='more' @click='toMore("status")'>更多></span>
            </div>
            <div class="echarts-box flex">
                <Echart :height="400" :options="statusEchartsOption" style="flex: 1;" />
                <div class="table-body">
                    <Table ref="publicTable"
                        :tableParams="statusTableParams"
                        :isCheckbox='false'
                        :rightBtn="[]"
                        :btnRole="[]"
                        :isPagination="false"
                        :tableData="statusTableData"
                    >
                    </Table>
                </div>
            </div>
        </div>
        <div class="echarts-body">
            <div class="echarts-title">
                <span>客户等级</span>
                <span class='more' @click='toMore("level")'>更多></span>
            </div>
            <div class="echarts-box flex">
                <Echart :height="400" :options="levelEchartsOption" style="flex: 1;" />
                <div class="table-body">
                    <Table ref="publicTable"
                        :tableParams="levelTableParams"
                        :isCheckbox='false'
                        :rightBtn="[]"
                        :btnRole="[]"
                        :isPagination="false"
                        :tableData="levelTableData"
                    >
                    </Table>
                </div>
            </div>
        </div>
        <div class="echarts-body">
            <div class="echarts-title">
                <span>客户来源</span>
                <span class='more' @click='toMore("source")'>更多></span>
            </div>
            <div class="echarts-box flex">
                <Echart :height="400" :options="sourceEchartsOption" style="flex: 1;" />
                <div class="table-body">
                    <Table ref="publicTable"
                        :tableParams="sourceTableParams"
                        :isCheckbox='false'
                        :rightBtn="[]"
                        :btnRole="[]"
                        :isPagination="false"
                        :tableData="sourceTableData"
                    >
                    </Table>
                </div>
            </div>
        </div>
        <div class="echarts-body">
            <div class="echarts-title">
                <span>所在区域</span>
                <span class='more' @click='toMore("area")'>更多></span>
            </div>
            <div class="echarts-box flex">
                <Echart :height="400" :options="echartsOptionCategory" style="flex: 1;" />
                <div class="table-body">
                    <Table ref="publicTable"
                        :tableParams="areaTableParams"
                        :isCheckbox='false'
                        :rightBtn="[]"
                        :btnRole="[]"
                        :isPagination="false"
                        :tableData="areaTableData"
                    >
                    </Table>
                </div>
            </div>
        </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';

  const {userInfo } = useUserStore()
  const router = useRouter();
  const { queryDictDetailByCodes } = useDictCache(['work_data_group', 'follow_up_type',])
  queryDictDetailByCodes()

  const queryFormRef = ref<ElFormInstance>();

    const publicTable = ref()

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

  const statusTableParams = reactive<tableTypes<DataQuery, DataVO>>({
        tableColumn: [
            {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},
        ],
    })
    const levelTableParams = reactive<tableTypes<DataQuery, DataVO>>({
        tableColumn: [
            {show: true, label: '名称', prop: 'customerLevelName', 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},
        ],
    })
    const sourceTableParams = reactive<tableTypes<DataQuery, DataVO>>({
        tableColumn: [
            {show: true, label: '名称', prop: 'customerSourceName', 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},
        ],
    })
    const areaTableParams = reactive<tableTypes<DataQuery, DataVO>>({
        tableColumn: [
            {show: true, label: '名称', prop: 'country', 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},
        ],
    })
    const queryParams = ref<DataQuery>({
        beginTime:null,
        endTime:null,
        blurry:'',
        deptId:'',
        ownerByIds: [userInfo.id],
        // deptIds: [userInfo.deptId],
    })
    const daterange = ref('')
    const getDate = (val: string[] | null) => {
        queryParams.value.beginTime = val ? val[0] : ''
        queryParams.value.endTime = val ? moment(val[1]).endOf('month').format('YYYY-MM-DD') : ''
    }

    const statusEchartsOption = reactive({
        title: {},
        tooltip: {
            trigger: 'item',
            formatter: (params) => {
                return `${params.name}: ${params.value} %`;
            },
        },
        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 levelEchartsOption = reactive({
        title: {},
        tooltip: {
            trigger: 'item',
            formatter: (params) => {
                return `${params.name}: ${params.value} %`;
            },
        },
        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 sourceEchartsOption = reactive({
        title: {},
        tooltip: {
            trigger: 'item',
            formatter: (params) => {
                return `${params.name}: ${params.value} %`;
            },
        },
        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 statusTableData = ref([])
    const levelTableData = ref([])
    const sourceTableData = ref([])
    const areaTableData = ref([])
    const handleQuery = () => {
        statusEchartsOption.series[0].data = []
        levelEchartsOption.series[0].data = []
        sourceEchartsOption.series[0].data = []
        echartsOptionCategory.dataset.source = [['区域', '新增客户']]
        getStatusData()
        getLevelData()
        getSourceData()
        getAreaData()
    }
    const getStatusData = ()=>{
        statusAnalytics(queryParams.value).then(res => {
            if(res.success) {
                if(res.result.list){
                    let EchartsData = setData(res.result.list,'customerStatusName')
                    statusTableData.value = EchartsData
                    EchartsData.forEach(item=>{
                        statusEchartsOption.series[0].data.push({value:item.customerStatusPercent,name:item.customerStatusName})
                    })
                }
            }
        })
    }
    const getLevelData = ()=>{
        levelAnalytics(queryParams.value).then(res => {
            if(res.success) {
                if(res.result.list){
                    let EchartsData = setData(res.result.list,'customerLevelName')
                    levelTableData.value = EchartsData
                    EchartsData.forEach(item=>{
                        levelEchartsOption.series[0].data.push({value:item.customerStatusPercent,name:item.customerLevelName})
                    })
                }
            }
        })
    }
    const getSourceData = ()=>{
        sourceAnalytics(queryParams.value).then(res => {
            if(res.success) {
                if(res.result.list){
                    let EchartsData = setData(res.result.list,'customerSourceName')
                    sourceTableData.value = EchartsData
                    EchartsData.forEach(item=>{
                        sourceEchartsOption.series[0].data.push({value:item.customerStatusPercent,name:item.customerSourceName})
                    })
                }
            }
        })
    }
    const getAreaData = ()=>{
        countryAnalytics(queryParams.value).then(res => {
            if(res.success) {
                if(res.result.list){
                    let EchartsData = setData(res.result.list,'country')
                    areaTableData.value = EchartsData
                    EchartsData.forEach(item=>{
                        echartsOptionCategory.dataset.source.push([item.country,item.addCustomerNum])
                    })
                }
            }
        })
    }
    const setData = (list:any,type)=>{
        const itemsToShow = list.slice(0, 5);
        const itemsAfterFive = list.slice(5);
        let addkh = 0
        let addzb = 0
        let addgj = 0
        let addcj = 0
        let addze = 0
        let addPervent = 0
        if (list.length > 5) {
            itemsAfterFive.forEach(item=>{
                addkh+=Number(item.addCustomerNum)
                addzb+=Number(item.addCustomerPercent)
                addgj+=Number(item.followUpNum)
                addcj+=Number(item.dealNum)
                addze+=Number(item.dealTotal)
                addPervent+=Number(item.customerStatusPercent)
            })
            if(type=='customerStatusName'){
                itemsToShow.push({ 'customerStatusName':'其他','addCustomerNum': addkh, 'addCustomerPercent':addzb,'followUpNum':addgj,'dealNum':addcj,'dealTotal':addze,'customerStatusPercent':addPervent});
            }else if(type=='customerLevelName'){
                itemsToShow.push({ 'customerLevelName':'其他','addCustomerNum': addkh, 'addCustomerPercent':addzb,'followUpNum':addgj,'dealNum':addcj,'dealTotal':addze,'customerStatusPercent':addPervent});
            }else if(type=='customerSourceName'){
                itemsToShow.push({ 'customerSourceName':'其他','addCustomerNum': addkh, 'addCustomerPercent':addzb,'followUpNum':addgj,'dealNum':addcj,'dealTotal':addze,'customerStatusPercent':addPervent});
            }else if(type=='country'){
                itemsToShow.push({ 'country':'其他','addCustomerNum': addkh, 'addCustomerPercent':addzb,'followUpNum':addgj,'dealNum':addcj,'dealTotal':addze});
            }
        }
        return itemsToShow;
    }
    handleQuery()
    const selectsUser = (data: { realName: string,id:number|string }[]) => {
        // form.value.ownerByName = data[0].realName
        // form.value.ownerBy = data[0].id
    }

    const toMore= (val:string)=>{

        if(val=='status'){
            router.push({ path: '/statistics/dataAnalysis/custoverview', query: { type: '0' } })
        } else if (val == 'level') {
            router.push({ path: '/statistics/dataAnalysis/custoverview', query: { type: '10' } })
        } else if (val == 'source') {
            router.push({ path: '/statistics/dataAnalysis/custoverview', query: { type: '20' } })
        } else if (val == 'area') {
            router.push({ path: '/statistics/dataAnalysis/custoverview', query: { type: '30' } })
        }
        // router.push({path:'/statistics/custoverview', query: {type:val}})
    }

  onMounted(() => {

  });
  </script>

  <style lang="scss" scoped>
  .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: 0 16px 16px;
        flex: 1;
    }
    .echarts-title {
        margin: 10px 16px 20px;
        font-size: 16px;
        display: flex;
        justify-content: space-between;
        font-weight:bold;
        .more{
            color:#1874ff;
            font-weight:normal;
            cursor: pointer;
            font-size:14px;
        }
    }
  </style>
