<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
                                v-model="datarange"
                                type="monthrange"
                                range-separator="-"
                                value-format="YYYY-MM-DD"
                                start-placeholder="开始年月"
                                end-placeholder="结束年月"
                                @change="getDate"
                                :clearable='false'
                            />
                        </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">
            <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>销售数量：{{productSalesData?.totalNum}}， 销售金额：¥ {{productSalesData?.totalAmount}}</div>
                </template>
                <!-- <template #right>
                    <el-button style="margin-left: 10px;">导出</el-button>
                </template> -->
            </Table>
        </div>

    </div>


  </template>

  <script setup name="productSalesSummary" 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 {productSalesBusiness,productTimeBusiness} from '@/api/statistics/performance';
  import { EChartsOption } from 'echarts'
  import { performanceVO, performanceQuery } from '@/api/statistics/performance/types';
  // import SelectUser from '@/components/SelectOrg/SelectUser.vue'
  const { queryDictDetailByCodes } = useDictCache(['work_data_group', 'follow_up_type',])
  queryDictDetailByCodes()


  const {userInfo } = useUserStore()

  // 顶部客户类型切换
const headerNav = [
    {label: '按产品汇总', value: '10',perPrefix: '',show: true},
    {label: '按时间汇总', value: '11',perPrefix: '', show: true},
]

const navIndex = ref(0)
const pageVal = ref('10')
const changeNav = (index: number, val) => {
    navIndex.value = index
    pageVal.value = val
    handleQuery()
}

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

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

const getDate = (val: string[] | null) => {
    tableParams.queryParams.beginCycleTime = val ? val[0] : ''
    tableParams.queryParams.endCycleTime = val ? moment(val[1]).endOf('month').format('YYYY-MM-DD') : ''
}

const tableData = ref([])
const productSalesData = ref()
const handleQuery = () => {
    if(pageVal.value=='10'){
        tableParams.tableColumn=[
            {show: true, label: '产品编号', prop: 'productName', sortable: false},
            {show: true, label: '销售数量', prop: 'salesNum', sortable: false},
            {show: true, label: '销售金额', prop: 'salesAmount', sortable: false},
            {show: true, label: '平均单价', prop: 'avgPrice', sortable: false},
        ],
        productSalesBusiness(tableParams.queryParams).then(res => {
            if(res.success) {
                productSalesData.value = res.result
                tableData.value = res.result.datas
                let echartsData = [['产品编号', '销售金额']]
                if(res.result.datas){
                    res.result.datas.forEach(item=>{
                        echartsData.push([item.productName,item.salesAmount])
                    })
                }
                echartsOption.dataset.source = echartsData
            }
        })
    }else{
        tableParams.tableColumn=[
            {show: true, label: '时间', prop: 'month', sortable: false},
            {show: true, label: '销售数量', prop: 'salesNum', sortable: false},
            {show: true, label: '销售金额', prop: 'salesAmount', sortable: false},
            {show: true, label: '销售额环比增长', prop: 'increaseRate', sortable: false,render: ({column}: { column: performanceVO }) => {
                return [
                    h('div', {}, column.increaseRate+'%'),
                ]
            }},
        ]
        // tableParams.tableColumn.prop='month'
        productTimeBusiness(tableParams.queryParams).then(res => {
            if(res.success) {
                productSalesData.value = res.result
                tableData.value = res.result.datas
                let echartsData = [['月份', '销售金额']]
                if(res.result.datas){
                    res.result.datas.forEach(item=>{
                        echartsData.push([item.month,item.salesAmount])
                    })
                }
                echartsOption.dataset.source = echartsData
            }
        })
    }

}

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

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


const queryFormRef = ref<ElFormInstance>();

const tableParams = reactive<tableTypes<performanceQuery, performanceVO>>({
    tableColumn: [
        {show: true, label: '产品编号', prop: 'productName', sortable: false},
        {show: true, label: '销售数量', prop: 'salesNum', sortable: false},
        {show: true, label: '销售金额', prop: 'salesAmount', sortable: false},
        {show: true, label: '平均单价', prop: 'avgPrice', sortable: false},
    ],
    queryParams: {
        yearMonth:'',
        summaryType:'',
        deptId:'',
        beginCycleTime:starDate,
        endCycleTime:endDate,
        followUpTimeType:'',
        targetType:'',
        increaseType:'',
        ownerByIds: [userInfo.id],
        // deptIds: [userInfo.deptId],
    },
})

const {queryParams} = toRefs(tableParams);

const publicTable = ref()

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

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

  onMounted(() => {
    handleQuery()
  });
  </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>
