<template>
    <div class="charts_area">
        <el-card shadow="never">
            <div class="search">
                <el-form :model="queryParams" ref="queryFormRef" :inline="true">
                    <el-form-item>
                        <datePicker ref="dateSelectorRef" @change="getdate"></datePicker>
                    </el-form-item>
                    <!-- 选择公司 -->
                    <el-form-item v-if="props.organizationType==30">
                        <SelectOrg authorty clearable :inputWidth="215" multiple v-model="queryParams.organizationIds" :type="2"></SelectOrg>
                    </el-form-item>
                    <!-- 选择部门 -->
                    <el-form-item v-if="props.organizationType==20">
                        <SelectOrg authorty clearable :inputWidth="215" multiple v-model="queryParams.organizationIds" :type="3"></SelectOrg>
                    </el-form-item>
                    <!-- 选择员工 -->
                    <el-form-item v-if="props.organizationType==10">
                        <SelectUser authorty multiple v-model="queryParams.organizationIds"></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="table-body" style="margin-top:15px">
            <Table
                ref="dataSummaryTable"
                :isCheckbox=false
                :tableParams="tableParams"
                :btnRole="[]"
            >
                <template #left>
                    <div>
                        新增合计数：成交金额{{ businessCountData?.orderAmountTotal }}元，
                        客户：{{ businessCountData?.customerNewTotalNum }}条，
                        商机：{{ businessCountData?.businessNewTotalNum }}条，
                        订单：{{ businessCountData?.orderNewTotalNum }}条，
                        线索：{{ businessCountData?.leadNewTotalNum }}条，
                        跟进：{{ businessCountData?.followNewTotalNum }}条，
                        邮件：{{ businessCountData?.mailNewTotalNum }}条
                    </div>
                </template>
                <template #right>
                    <el-button style="margin-left: 10px;" @click="exportData">导出</el-button>
                </template>
            </Table>
        </div>
    </div>
    <dataSummaryDetail ref="dialogDetailRef"></dataSummaryDetail>
  </template>

<script setup name="completionDegree" lang="ts">
import Table from '@/components/Table/index.vue'
import { tableTypes } from '@/components/Table/types'
import { getReportTotal,getReport,getCycle } from '@/api/statistics/salesAnalysis'
import { DataSummaryQuery, DataSummaryVO } from '@/api/statistics/salesAnalysis/types';
import dataSummaryDetail from '@/modules/sales/views/statistics/dataSummary/detail.vue';
import datePicker from "@/modules/sales/views/statistics/components/datePicker.vue";
const props = defineProps({
    organizationType: {
        type: Number,
        default: 40
    },
})

const typeList = [
    { label: '周报', value: 10 },
    { label: '月报', value: 20 },
    { label: '季度', value: 30 },
    { label: '半年度', value: 40 },
    { label: '年度', value: 50 }
]
const queryFormRef = ref<ElFormInstance>();

const sketchData = ref()
const dialogDetailRef = ref()
const router = useRouter()
const tableParams = reactive<tableTypes<DataSummaryQuery, DataSummaryVO>>({
    menuId: router.currentRoute.value?.meta?.menuId,
    tableColumn: [
        { show: true, label: '简报类型', prop: 'sketchType',render: ({ column }: { column: DataSummaryVO }) => {
            const targetItem = typeList.find(item => item.value === column?.sketchType);
            const targetLabel = targetItem?.label || '未知类型';
            return [
                h('div', {},targetLabel)
            ]
        } },
        { show: true, label: '简报周期', prop: 'groupTypeName',render: ({ column }: { column: DataSummaryVO }) => {
            return [
                h('div', {},getCycle(column))
            ]
        } },
        { show: props.organizationType!=40, label: '公司名称', prop: props.organizationType == 30 ? 'organizationName' : 'companyName', notSort: props.organizationType == 40 },
        { show: props.organizationType==20 || props.organizationType==10, label: '部门名称', prop: props.organizationType == 20 ? 'organizationName' : 'deptName', notSort: props.organizationType == 40 || props.organizationType == 30 },
        { show: props.organizationType==10, label: '姓名', prop: 'organizationName', notSort: props.organizationType != 10 },
        { show: true, label: '成交总金额', prop: 'orderAmount' },
        { show: true, label: '客户新增数', prop: 'customerNewNum' },
        { show: true, label: '商机新增数', prop: 'businessNewNum' },
        { show: true, label: '订单新增数', prop: 'orderNewNum' },
        { show: true, label: '线索新增数', prop: 'leadNewNum' },
        { show: true, label: '跟进新增数', prop: 'followNewNum' },
        { show: true, label: '邮件新增数', prop: 'mailNewNum' },
        { show: true, label: '操作', prop: 'orderFormNum',render: ({ column }: { column: DataSummaryVO }) => {
            return [
                h(ElButton, {
                    link: true, type: 'primary', onClick: ($event) => {
                        sketchData.value= JSON.parse(column.sketchDataJson)
                        let data = JSON.parse(JSON.stringify(queryParams.value))
                        data.id = column.id
                        dialogDetailRef.value.open(data)
                        console.log(sketchData.value)
                    }
                }, () => '查看详情'),
            ]
        } },
    ],
    queryParams: {
        year: '',
        month: '',
        organizationId: null,
        organizationIds: null,
        sketchType: null,
        ownerByIds: null,
        organizationType: props.organizationType,
        cycle: null,
    },
    listFn: getReport,
    keyId: 'id',
    exportCode: 'EXPORT_SUMMARY_COUNT_EXCEL'
})
const { queryParams } = toRefs(tableParams);

const businessCountData = ref()
const getData = () => {
    let params = JSON.parse(JSON.stringify(queryParams.value))
    getReportTotal(params).then(res => {
        if(res.success) {
            businessCountData.value =  Object.keys(res.result).reduce((acc, key) => {
                acc[key] = res.result[key] === null ? 0 : res.result[key];
                return acc;
            }, {} as Record<string, number>);
        }
    })
}

const getdate = (data) =>{
    if(data){
        queryParams.value.year = data.year
        queryParams.value.month = data.month
        queryParams.value.sketchType = data.type
        switch (data.type) {
            case '10': // 周
                queryParams.value.cycle = data.week
            break;
            case '20': // 月
                queryParams.value.cycle = data.month
            case '30': // 季度
                queryParams.value.cycle = data.quarter
            case '40': // 半年度
                queryParams.value.cycle = data.halfYear
            break;
            case '50': // 年度
                queryParams.value.cycle = data.year
            break;
            default:
            break;
        }
    }
}

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

getData()

const dateSelectorRef = ref()
/** 重置按钮操作 */
const resetQuery = () => {
    queryFormRef.value?.resetFields();
    dateSelectorRef.value.resetDateSelector();
    queryParams.value={
        year: '',
        month: '',
        organizationId: null,
        organizationIds: null,
        sketchType: null,
        ownerByIds: null,
        organizationType: props.organizationType,
        cycle: null,
    },
    handleQuery();
}

const exportData = ()=>{
    dataSummaryTable.value.getData()
    dataSummaryTable.value.handleExport()
}

</script>
