<template>
    <div style="margin-top: 20px">
        <div class="filter-wrap" v-show="showFilter" >
            <div class="filters" :class="{'auto-height': expand}" >
                <div ref="filterRef" style="flex-shrink: 1;" >
                    <el-form  autocapitalize="off" :inline="true" size="large" label-position="top" >
                        <!-- mt4_server -->
                        <el-form-item :label="t('report.report24.mt4_server')" v-if="filters.includes('mt4_server')" >
                            <el-select
                                v-model="queryParams.mt4_server"
                                :placeholder="t('common.selectChoose')"
                                :clearable="false"
                                style="width: 270px"
                                >
                                <el-option v-for="(item, index) in mtServerList" :key="index" :label="item.server_name" :value="item.id" ></el-option>
                            </el-select>
                        </el-form-item>
                        <!-- login -->
                        <el-form-item :label="t('report.report24.login')" v-if="filters.includes('login')" >
                            <el-select
                                v-model="queryParams.login_formula"
                                :clearable="false"
                                style="width: 110px;margin-right: 10px;"
                                >
                                <el-option :label="t('report.report24.formula0')" :value="0" ></el-option>
                                <el-option :label="t('report.report24.formula1')" :value="1" ></el-option>
                                <el-option :label="t('report.report24.formula2')" :value="2" ></el-option>
                                <el-option :label="t('report.report24.formula3')" :value="3" ></el-option>
                            </el-select>
                            <el-input
                                v-model="queryParams.login"
                                clearable
                                style="width: 150px"
                                />
                        </el-form-item>
                        <!-- cmd -->
                        <el-form-item :label="t('report.report24.cmd')" v-if="filters.includes('cmd')" >
                            <el-select
                                v-model="queryParams.cmd"
                                :placeholder="t('common.selectChoose')"
                                :clearable="false"
                                style="width: 270px"
                                >
                                <el-option v-for="(item, index) in cmdList" :key="index" :label="item.label" :value="item.value" ></el-option>
                            </el-select>
                        </el-form-item>
                        <!-- close_time_start/end -->
                        <el-form-item :label="t('report.report24.close_time')" v-if="filters.includes('close_time')" >
                            <el-date-picker
                                v-model="closeDateRange" size="large" style="width: 270px;"
                                value-format="YYYY-MM-DD"
                                type="daterange"
                                range-separator="-"
                                :start-placeholder="t('report.report24.start')"
                                :end-placeholder="t('report.report24.end')"
                                :shortcuts="shortcuts"
                            ></el-date-picker>
                        </el-form-item>
                    </el-form>
                </div>
                <div style="flex-shrink: 0;margin-top: 34px;">
                    <el-switch :loading="totalBtn && loading" @change="handleTotal" v-model="totalBtn" :active-text="t('form.total')" style="margin-right: 10px;" />
                    <el-button type="primary" icon="Search" @click="handleQuery" >{{ t('form.search') }}</el-button>
                    <el-button v-if="btnPower.includes('export')" icon="Download" :loading="exportLoading" @click="handleExport">{{ t('form.export') }}
                        <template #loading>
                            <l-ring-2 size="20" stroke="2" stroke-length="0.25" bg-opacity="0.1" speed="0.8" color="rgb(41, 187, 228)" style="margin-right: 17px;" ></l-ring-2>
                        </template>
                    </el-button>
                </div>
            </div>
            <div style="text-align: center;width: 100%;padding: 20px;user-select: none;" >
                <el-text type="primary" style="cursor: pointer;" @click="expand = !expand" > {{ expand?t('form.collapse'):t('form.expand') }} 
                    <el-icon v-if="!expand" ><ArrowDown /></el-icon> 
                    <el-icon v-else ><ArrowUp /></el-icon>
                </el-text>
            </div>
        </div>

        <el-table v-htfx-loading="loading" :data="dataList" style="width: 100%;" :summary-method="getSummaries" :show-summary="totalBtn" @sort-change="handleSort" >
          <el-table-column type="index" :label="t('form.rowNum.label')" width="80" />  
          <el-table-column v-for="(item,index) in colList" :key="index" :label="item.title" :align="item.align" :sortable="item.sortable?'custom':false"
          :prop="item.field" :width="(item.field.endsWith('Time') || item.field.endsWith('time'))?184:'164'" >
            <template #default="scope">
                {{ scope.row[item.field] }}
            </template>
          </el-table-column>
        </el-table>

        <pagination v-show="total > 0" :total="total" :autoScroll="false"
            v-model:page="queryParams.curr_page"
            v-model:limit="queryParams.page_size"
            @pagination="getList" />
    </div>
</template>

<script setup>
import { useLocale } from 'element-plus'
import { onMounted, onUnmounted, ref, computed } from "vue"
import { generateShortcuts, recent3Month, today, recentWeek, recentMonth } from '@/utils/shortcutsUtils';
import { getReport24, getFilterColumns } from '@/api/report'
import { mtServer, getPageBtnPower, getDataPower } from '@/api/common'
import { serverLang } from '@/utils/i18n'

const { proxy } = getCurrentInstance();
const { t } = useLocale()
const shortcuts = ref(generateShortcuts(t))
const filterRef = ref(null)
const expand = ref(false)
const mtServerList = ref([])
const cmdList = ref([
    {label: t('report.report24.deposit'), value: 'deposit'},
    {label: t('report.report24.withdraw'), value: 'withdraw'}
])

const closeDateRange = ref(today())

const props = defineProps({
    showFilter: {
        type: Boolean,
        default: false
    },
    structureValue: {
        type: [String, Number],
        default: ''
    },
    structureType: {
        type: String,
        default: ''
    }
})

const queryParams = ref({
    qcc_structure_value: props.structureValue,
    qcc_structure_type: props.structureType,
    qcc_sort_field: undefined,
    qcc_sort_type: undefined,
    totalBtn: '0',
    qcc_language: serverLang(),
    curr_page: 1,
    page_size: 10,
    mt4_server: undefined,
    login: undefined,
    login_formula: 0,
    cmd: undefined,
    close_time_start: undefined,
    close_time_end: undefined
})
const totalBtn = ref(false)
const loading = ref(false)
const exportLoading = ref(false)
const dataList = ref([])
const colList = ref([])
const total = ref(0)
const filters = ref([])

const pageId = '624'
const btnPower = ref([])

// 合计行数据
let totalRow = null

function getSummaries(param) {
    const { columns, data } = param
    const sums = []
    columns.forEach((column, index) => {
        if (index === 0) {
            sums[index] = t('form.total');
            return;
        }
        else {
            if (totalRow) {
                const prop = column.property
                const value = totalRow[prop]
                sums[index] = value
            }
        }
    });
    return sums;
}

function loadServerList() {
    mtServer({
        qcc_language: serverLang()
    }).then(resp => {
        if (resp.data) {
            mtServerList.value = resp.data
            if (resp.data.length) {
                queryParams.value.mt4_server = resp.data[0].id
                getList()
            }
        }
    })
}

function getList() {
    if (closeDateRange.value && closeDateRange.value.length && filters.value.includes('close_time')) {
        queryParams.value.close_time_start = closeDateRange.value[0]
        queryParams.value.close_time_end = closeDateRange.value[1]
    } else {
        queryParams.value.close_time_start = undefined
        queryParams.value.close_time_end = undefined
    }
    queryParams.value.qcc_structure_value = props.structureValue
    queryParams.value.qcc_structure_type = props.structureType
    loading.value = true
    getReport24(queryParams.value).then(resp => {
        if (resp.data) {
            if (resp.data.records && resp.data.records.length) {
                totalRow = resp.data.records.pop()
            }
            dataList.value = resp.data.records
            total.value = resp.data.totalRecords
        }
        loading.value = false
    })
}

function handleQuery() {
    queryParams.value.curr_page = 1;
    getList();
}

function handleTotal(value) {
    queryParams.value.totalBtn = value ? '1' : '0'
    getList()
}

function handleSort(data) {
    const { prop, order } = data
    if (order == null) {
        queryParams.value.qcc_sort_field = undefined
        queryParams.value.qcc_sort_type = undefined
    }
    else {
        queryParams.value.qcc_sort_field = prop
        queryParams.value.qcc_sort_type = order === 'ascending' ? 'asc' : 'desc'
    }
    getList()
}

function handleExport() {
    if (closeDateRange.value && closeDateRange.value.length && filters.value.includes('close_time')) {
        queryParams.value.close_time_start = closeDateRange.value[0]
        queryParams.value.close_time_end = closeDateRange.value[1]
    } else {
        queryParams.value.close_time_start = undefined
        queryParams.value.close_time_end = undefined
    }
    queryParams.value.qcc_structure_value = props.structureValue
    queryParams.value.qcc_structure_type = props.structureType
    exportLoading.value = true
    proxy.download("/app/report/getReport24Export", {
    ...queryParams.value
  }, `report24.xlsx`,null , () => {
    exportLoading.value = false
  });
}

const emit = defineEmits(['structure'])

function loadPower() {
    getPageBtnPower({
        menu_id: pageId
    }).then(resp => {
        if (resp.data) {
            btnPower.value = JSON.parse(resp.data)
        }
        if (btnPower.value) {
            if (btnPower.value.includes('structure')) {
                getDataPower({
                    qcc_page_id: pageId
                }).then(resp => {
                    emit('structure', { show: true, page_data_power: resp.data.power, pageId: pageId })
                })
            }
        }
    })
}

onMounted(() => {
    getFilterColumns({
        qcc_page_id: pageId,
        qcc_language: serverLang()
    }).then(resp => {
        if(resp.data) {
            colList.value = resp.data
            filters.value = resp.data.filter(i => i.ifFilter).map(i => i.field)
        }
        loadServerList()
    })
})

onUnmounted(() => {
    emit('structure', { show: false, page_data_power: null, pageId: null })
})

defineExpose({
    handleQuery
})

loadPower()
</script>

<style lang="scss" scoped>
.filter-wrap {
    width: 100%;
    min-height: 160px;
    margin-bottom: 20px;
    box-shadow: var(--el-box-shadow-light);

    .filters {
        width: 100%;
        padding-top: 24px;
        padding-left: 24px;
        padding-right: 24px;
        height: 100px;
        overflow: hidden;
        display: flex;
        flex-direction: row;
        flex-wrap: nowrap;
        align-items: flex-start;
        justify-content: space-between;
    }
}
</style>