<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" v-if="item.show"
                            @click="changeNav(index,item.value)">{{ item.label }}<i
                            :class="navIndex==index?'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
                                :clearable='false'
                                v-model="datarange"
                                type="monthrange"
                                range-separator="-"
                                value-format="YYYY-MM-DD"
                                start-placeholder="开始年月"
                                end-placeholder="结束年月"
                                @change="getDate"
                            />
                        </el-form-item>
                    </el-form-item>
                    <!-- <el-form-item >
                        <SelectOrg authorty clearable multiple  v-model="queryParams.deptIds"></SelectOrg>
                    </el-form-item> -->
                    <el-form-item>
                        <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" v-if="pageVal=='10'">
            <Echart :height="450" :options="echartsOption" />
        </div>
        <div class="table-body">
            <Table ref="publicTable"
                :tableParams="tableParams"
                :isCheckbox='false'
                :rightBtn="[]"
                :btnRole="[]"
                :isPagination="false"
                :key="pageVal"
                :tableData="tableData"
            >
                <template #left>
                    <div v-if='pageVal=="10"'>成交商机：{{productSalesData?.businessNumTotal}}， 成交金额：¥ {{productSalesData?.salesAmountTotal}}</div>
                    <div v-else>新增商机：{{productSalesData?.totalCount}}</div>
                </template>
                <!-- <template #right>
                    <el-button style="margin-left: 10px;">导出</el-button>
                </template> -->
            </Table>
        </div>

    </div>


  </template>

  <script setup name="dealOpportunitySummary" lang="ts">
  import {useUserStore} from '@/store/modules/user';
  import moment from 'moment'
  import auth from '@/plugins/auth'
  import {useDictCache} from '@/hooks/web/useDict'
  import {tableTypes} from '@/components/Table/types'
  import {closedBusiness,salesBusiness} from '@/api/statistics/performance';
  import { EChartsOption } from 'echarts'
  import { performanceVO, performanceQuery } from '@/api/statistics/performance/types';
  import {DataQuery} from "@/api/statistics/data/types";
  // import SelectUser from '@/components/SelectOrg/SelectUser.vue'
  const { queryDictDetailByCodes } = useDictCache(['work_data_group', 'follow_up_type',])
  queryDictDetailByCodes()


    const {userInfo } = useUserStore()

  const queryFormRef = ref<ElFormInstance>();

    const publicTable = ref()
    let starDate = moment().subtract(12, 'months').format('YYYY-MM') + '-01'
    let endDate = moment().endOf('month').format('YYYY-MM-DD')

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

    const datarange = ref([])
    datarange.value = [starDate,endDate]

     // 顶部类型切换
    const headerNav = [
        {label: '成交商机汇总', value: '10',perPrefix: '',show: true},
        {label: '成交商机明细', value: '11',perPrefix: '', show: true},
    ]
    const tableParams = reactive<tableTypes<performanceQuery, performanceVO>>({
        tableColumn: [],

    })
      const queryParams = ref<performanceQuery>({
          beginCycleTime: starDate,
          endCycleTime: endDate,
          deptId:'',
          ownerByIds: [userInfo.id],
        //   deptIds: [userInfo.deptId],
      })
    const {tableColumn} = toRefs(tableParams);

    const getDate = (val: string[] | null) => {
        queryParams.value.beginCycleTime = val ? val[0] : ''
        queryParams.value.endCycleTime = val ? moment(val[1]).endOf('month').format('YYYY-MM-DD') : ''
    }
    const navIndex = ref(0)
    const pageVal = ref('10')
    const changeNav = (index: number, val ) => {
        navIndex.value = index
        pageVal.value = val
        if(val=='10'){
            tableColumn.value=[
                {show: true, label: '时间', prop: 'groupTypeName', sortable: false},
                {show: true, label: '成交数量', prop: 'businessNum', sortable: false},
                {show: true, label: '成交数量环比增长', prop: 'businessCountRate', sortable: false,render: ({column}: { column: performanceVO }) => {
                return [
                    h('div', {}, column.businessCountRate+'%'),
                ]
            }},
                {show: true, label: '成交金额', prop: 'businessAmount', sortable: false},
                {show: true, label: '成交金额环比增长', prop: 'businessAmountRate', sortable: false,render: ({column}: { column: performanceVO }) => {
                return [
                    h('div', {}, column.businessAmountRate+'%'),
                ]
            }},
                {show: true, label: '平均客单价', prop: 'avgBusinessAmount', sortable: false},
            ]
        }else{
            tableColumn.value=[
                {show: true, label: '商机标题', prop: 'title', sortable: false},
                {show: true, label: '对应客户', prop: 'customer', sortable: false},
                {show: true, label: '商机阶段', prop: 'status', sortable: false},
                {show: true, label: '成交日期', prop: 'closeTime', sortable: false},
                {show: true, label: '商机来源', prop: 'source', sortable: false},
                {show: true, label: '负责人员', prop: 'ownerBy', sortable: false},
            ]
        }
        console.log(tableColumn.value)
        handleQuery()
    }
    const router = useRouter();

    const tableData = ref([])
    const productSalesData = ref()
    const handleQuery = () => {
        echartsOption.dataset.source = [['月份', '成交金额']]
        if(pageVal.value=='10'){
            closedBusiness(queryParams.value).then(res => {
                if(res.success) {
                    productSalesData.value = res.result
                    tableData.value = res.result.businessMonthCountls
                    if(res.result.businessMonthCountls){
                        res.result.businessMonthCountls.forEach(item=>{
                            echartsOption.dataset.source.push([item.groupTypeName,item.businessAmount])
                        })
                    }
                }
            })
        }else{
            salesBusiness(queryParams.value).then(res => {
                if(res.success) {
                    productSalesData.value = res.result
                    tableData.value = res.result.closeBusinessAllList
                }
            })
        }

    }


    const echartsOption = reactive({
        // legend: {
        //     x:'center',
        //     y:'bottom'
        // },
        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] // 这里设置圆角的大小
                }
            },
        ]
    })

    changeNav(0,'10')

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

  onMounted(() => {

  });
  </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>
