<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" >
                        <!-- user_code -->
                        <el-form-item :label="t('report.report28.user_code')" v-if="filters.includes('user_code')" >
                            <el-input
                                v-model="queryParams.user_code"
                                clearable
                                style="width: 270px"
                                />
                        </el-form-item>
                        <!-- record_type -->
                        <el-form-item :label="t('report.report28.record_type')" v-if="filters.includes('record_type')" >
                            <el-select
                                v-model="queryParams.record_type"
                                :placeholder="t('common.selectChoose')"
                                :clearable="false"
                                style="width: 270px"
                                >
                                <el-option v-for="(item, index) in recordTypeList" :key="index" :label="item.label" :value="item.value" ></el-option>
                            </el-select>
                        </el-form-item>
                        <!-- create_time_start/end -->
                        <el-form-item :label="t('report.report28.create_time')" v-if="filters.includes('create_time')" >
                            <el-date-picker
                                v-model="createDateRange" size="large" style="width: 270px;"
                                value-format="YYYY-MM-DD"
                                type="daterange"
                                range-separator="-"
                                :start-placeholder="t('report.report28.start')"
                                :end-placeholder="t('report.report28.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 { getReport28, getFilterColumns } from '@/api/report'
import { getDictByCode, 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 recordTypeList = ref([])

const createDateRange = 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,
    user_name: undefined,
    ticket: undefined,
    ticket_formula: 0,
    trade_direction: undefined,
    create_time_start: undefined,
    create_time_end: undefined,
    symbol: 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 = '628'
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 getRecordType() {
    getDictByCode({
        dict_code: 'record_type',
        qcc_language: serverLang()
    }).then(resp => {
        recordTypeList.value = resp.data.map(i => {
            return { label: i.fun_item_text, value: i.fun_item_code }
        })
    })
}

function getList() {
    if (createDateRange.value && createDateRange.value.length && filters.value.includes('create_time')) {
        queryParams.value.create_time_start = createDateRange.value[0]
        queryParams.value.create_time_end = createDateRange.value[1]
    } else {
        queryParams.value.create_time_start = undefined
        queryParams.value.create_time_end = undefined
    }
    queryParams.value.qcc_structure_value = props.structureValue
    queryParams.value.qcc_structure_type = props.structureType
    loading.value = true
    getReport28(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 (createDateRange.value && createDateRange.value.length && filters.value.includes('create_time')) {
        queryParams.value.create_time_start = createDateRange.value[0]
        queryParams.value.create_time_end = createDateRange.value[1]
    } else {
        queryParams.value.create_time_start = undefined
        queryParams.value.create_time_end = undefined
    }
    queryParams.value.qcc_structure_value = props.structureValue
    queryParams.value.qcc_structure_type = props.structureType
    exportLoading.value = true
    proxy.download("/app/report/getReport28Export", {
    ...queryParams.value
  }, `report28.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)
        }
        getList()
    })
    getRecordType()
})

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>