<template>
    <div class="table-box">
      <div class="bg-white pt-2 pl-2">
        <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
          <el-tab-pane
            :label="item.label"
            :name="item.value"
            v-for="(item, index) in tabs"
            :key="index"
          >
          </el-tab-pane>
        </el-tabs>
      </div>
      <div>
        <ProTable
          :config="config"
          v-if="firstLoad"
          ref="caseLRef"
          :api="fn"
          :showPagination="false"
          :paramCallback="paramCallback"
          :dataCallback="dataCallback"
        >
        <template #left_buttons>
            <el-button type="primary" @click="exportEvent">导出</el-button>
        </template>
        </ProTable>
      </div>
    </div>
  </template>
  
  <script setup name="case-audit" lang="jsx">
    import { Download } from '@element-plus/icons-vue';
    import { inject, nextTick } from 'vue';
    import { computed } from 'vue';
    import { ElMessageBox, ElMessage, ElButton, ElTag } from 'element-plus';
    import { getdepartmentTree } from '@/api/departmentManage';
    import { onMounted } from 'vue';
    import { getAppEnvConfig } from '@/utils/env';
    import { getCollectorStatsVo, getCollectorNoDistributeStatsVo, getCollectorProvinceStatsVo } from '@/api/analy';
    import { useUserStore } from '@/stores/modules/user';
    import { getTenantPage } from '@/api/tenant';
    import { useDict } from '@/hooks/useDict';
    const { PhoneResultStatus, ReduceType, FlowStatus, FollowStatus, AuditStatus, CaseStatus } =
      useDict(
        'PhoneResultStatus',
        'ReduceType',
        'FlowStatus',
        'FollowStatus',
        'AuditStatus',
        'CaseStatus'
      );
    const envs = getAppEnvConfig();
    const { userInfo } = useUserStore();
    const departlist = ref([]);
    const userStore = useUserStore();
    console.log('userStore', userStore)
    import { reactive, ref } from 'vue';
    const downloadfile = inject('download');
  
    const allocationModalRef = ref();
    const firstLoad = ref(false);
    const caseLRef = ref();
    const selectdList = ref([]);
    const tabs = ref([
        {label: '催员持案汇总',value: '催员持案汇总'},
        {label: '未分派案件汇总',value: '未分派案件汇总'},
        {label: '属地分派汇总',value: '属地分派汇总'}
    ]);
    const sheetMethod = ({ options, worksheet }) => {
        const data = options.data;
        const columns = options.columns;
        console.log('asdas',options, worksheet)
    }
    const exportEvent = () => {
        if (caseLRef.value && caseLRef.value.element) {
            caseLRef.value.element.exportData({
                type: 'xlsx',
                useStyle: true,
                sheetMethod: sheetMethod,
                isColgroup: true,
                isMerge: true,
                isHeader: true
            });
        }
    };
  
    const activeName = ref('催员持案汇总');
    const fn = (params) => {
        if (activeName.value === '催员持案汇总') {
            return getCollectorStatsVo(params)
        } else if (activeName.value === '未分派案件汇总') {
            return getCollectorNoDistributeStatsVo(params)
        } else {
            return getCollectorProvinceStatsVo(params)
        }
    }
    const paramCallback = (param) => {
      const obj = JSON.parse(JSON.stringify(param));
      return obj;
    };

    const handleClick = () => {
      setTimeout(() => {
        query();
      }, 300);
    };
    const config = reactive({
        columns: [
        ]
    })
    const dataCallback = (data) => {
        console.log('data', data)
        if (activeName.value === '催员持案汇总' || activeName.value === '未分派案件汇总') {
            if (data.length > 0) {
                const key = data[0]['platforms'] ? 'platforms' : 'batchCodeDetailVos'
                data[0][key].forEach((item, index) => {
                    config['columns'].push({
                        title: item.platformName,
                        showOverflow: 'tooltip',
                        children: [
                            { sortable: true, field: `${key}[${index}].totalAmount`, title: '金额', width: 140},
                            { field: `${key}[${index}].borrowerCount`, title: '户数', width: 120 },
                            { field: `${key}[${index}].avgAmount`, title: '户均', width: 120 }
                        ]
                    })
                })
            }
        } else {
            if (data.length > 0) {
                const key = 'provinceDetailVoList'
                data[0][key].forEach((item, index) => {
                    config['columns'].push({
                        title: item.platformName,
                        showOverflow: 'tooltip',
                        children: [
                            { sortable: true, field: `${key}[${index}].disAmount`, title: '已分派', width: 140},
                            { field: `${key}[${index}].noDisAmount`, title: '未分派', width: 120 },
                            { field: `${key}[${index}].totalAmount`, title: '合计', width: 120 }
                        ]
                    })
                })
            }
        }
        return data
    }
    const download = (item) => {
      const name = item.slice(item.lastIndexOf('/') + 1, item.length);
      downloadfile('/sys/static/' + item, {}, name);
    };
    const query = () => {
        firstLoad.value = false
      if (activeName.value === '催员持案汇总') {
        config['columns'] = [{
            title: '催员姓名',
            field: 'collectorName',
            showOverflow: 'tooltip',
            width: 120,
            search: { el: 'input', props: { clearable: true }, key: 'cpeName', labelWidth: 105 },
        }]
        if (userStore.userInfo?.roles && userStore.userInfo?.roles.find(i => i.roleCode === 'admin')) {
            config['columns'].push({
                showOverflow: 'tooltip',
                field: 'tenantName',
                enum: () => getTenantPage({ current: 1, size: 999999999, status: 'enable' }),
                search: { el: 'select', props: { filterable: true, clearable: true }, key: 'tenant', labelWidth: 105 },
                fieldNames: { label: 'name', value: 'id' },
                title: '调解中心',
                width: 120,
            })
        } else if (userStore.userInfo?.roles && userStore.userInfo?.roles.find(i => i.roleCode === 'tenantAdmin')) {
            config['columns'].push({
                field: 'departmentName',
                title: '部门',
                width: 160,
                enum: departlist,
                fieldNames: { label: 'name', value: 'name' },
                search: {
                el: 'tree-select',
                props: { filterable: true, checkStrictly: true },
                labelWidth: 85,
                key: 'departmentName',
                }
            })
        }
      } else if (activeName.value === '未分派案件汇总') {
        config['columns'] = [{
        title: '委案类型',
        field: 'batchCode',
        showOverflow: 'tooltip',
        width: 100
        }]
      } else {
        config['columns'] = [{
        title: '属地',
        field: 'province',
        showOverflow: 'tooltip',
        width: 100
        }]
      }
      nextTick(() => {
        firstLoad.value = true
      })
      setTimeout(()=> {
        caseLRef.value?.search();
      }, 500)
    };
  
    onMounted(() => {
      query();
      getdepartmentTree().then((res) => {
        if (res.success) {
            departlist.value = res.result;
        }
      });
    });
  </script>
  