<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.report40.user_code')" v-if="filters.includes('user_code')" >
                            <el-input
                                v-model="queryParams.user_code"
                                clearable
                                style="width: 270px"
                                />
                        </el-form-item>
                        <!-- name -->
                        <el-form-item :label="t('report.report40.user_name')" v-if="filters.includes('name')" >
                            <el-input
                                v-model="queryParams.name"
                                clearable
                                style="width: 270px"
                                />
                        </el-form-item>
                        <!-- user_type -->
                        <el-form-item :label="t('report.report40.user_type')" v-if="filters.includes('user_type')" >
                            <el-select
                                v-model="queryParams.user_type"
                                :placeholder="t('common.selectChoose')"
                                clearable
                                style="width: 270px"
                                >
                                <el-option :label="t('common.ib')" :value="1" ></el-option>
                                <el-option :label="t('common.customer')" :value="2" ></el-option>
                            </el-select>
                        </el-form-item>
                        <!-- login -->
                        <el-form-item :label="t('report.report40.login')" v-if="filters.includes('mt4_login')" >
                            <el-input
                                v-model="queryParams.mt4_login"
                                clearable
                                style="width: 270px"
                                />
                        </el-form-item>
                        <!-- mt4_server -->
                        <el-form-item :label="t('report.report40.mt4_server')" v-if="filters.includes('mt4_server')" >
                            <el-select
                                v-model="queryParams.mt4_server"
                                :placeholder="t('common.selectChoose')"
                                clearable
                                style="width: 270px"
                                @change="handleChangeServer"
                                >
                                <el-option v-for="(item, index) in mtServerList" :key="index" :label="item.server_name" :value="item.id" ></el-option>
                            </el-select>
                        </el-form-item>
                        <!-- mt4_group -->
                        <el-form-item :label="t('report.report40.mt4_group')" v-if="filters.includes('mt4_group')" >
                            <el-select
                                v-model="queryParams.mt4_group"
                                :placeholder="t('common.selectChoose')"
                                clearable
                                style="width: 270px"
                                >
                                <el-option v-for="(item, index) in mtGroupList" :key="index" :label="item.label" :value="item.value" ></el-option>
                            </el-select>
                        </el-form-item>
                        <!-- mt4_leverage -->
                        <el-form-item :label="t('report.report40.mt4_leverage')" v-if="filters.includes('mt4_leverage')" >
                            <el-select
                                v-model="queryParams.mt4_leverage"
                                :placeholder="t('common.selectChoose')"
                                clearable
                                style="width: 270px"
                                >
                                <el-option v-for="(item, index) in leverageList" :key="index" :label="item.label" :value="item.value" ></el-option>
                            </el-select>
                        </el-form-item>
                        <!-- regdate_start/end -->
                        <el-form-item :label="t('report.report40.regdate')" v-if="filters.includes('regdate')" >
                            <el-date-picker
                                v-model="regDateRange" size="large" style="width: 270px;"
                                value-format="YYYY-MM-DD"
                                type="daterange"
                                range-separator="-"
                                :start-placeholder="t('report.report40.start')"
                                :end-placeholder="t('report.report40.end')"
                                :shortcuts="shortcuts"
                            ></el-date-picker>
                        </el-form-item>
                        <!-- regdate_start/end -->
                        <el-form-item :label="t('report.report40.lastdate')" v-if="filters.includes('lastdate')" >
                            <el-date-picker
                                v-model="lastDateRange" size="large" style="width: 270px;"
                                value-format="YYYY-MM-DD"
                                type="daterange"
                                range-separator="-"
                                :start-placeholder="t('report.report40.start')"
                                :end-placeholder="t('report.report40.end')"
                                :shortcuts="shortcuts"
                            ></el-date-picker>
                        </el-form-item>
                        <!-- salesman_name -->
                        <el-form-item :label="t('report.report40.salesman_name')" v-if="filters.includes('salesman_name')" >
                            <el-input
                                v-model="queryParams.salesman_name"
                                clearable
                                style="width: 270px"
                                />
                        </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">
                <template v-if="item.field == 'user_type'" >
                    <div v-html="getUserTypeHtml(scope.row[item.field])"></div>
                </template>
                <!-- <template v-else-if="item.field == 'mt4_server'" >
                    {{ scope.row['mt4_server_name'] }}
                </template> -->
                <template v-else>
                    {{ scope.row[item.field] }}
                </template>
            </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 { getReport40, getFilterColumns } from '@/api/report'
import { getDictByCode, getPageBtnPower, getDataPower, mtServer, getMtGroup } from '@/api/common'
import { serverLang } from '@/utils/i18n'
import { getUserTypeHtml } from '@/utils/htfx'

const { proxy } = getCurrentInstance();
const { t } = useLocale()
const shortcuts = ref(generateShortcuts(t))
const filterRef = ref(null)
const expand = ref(false)
const mtServerList = ref([])
const mtGroupList = ref([])
const leverageList = ref([])

const regDateRange = ref([])
const lastDateRange = ref([])

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,
    name: undefined,
    user_type: undefined,
    mt4_login: undefined,
    mt4_server: undefined,
    mt4_group: undefined,
    mt4_leverage: undefined,
    trade_direction: undefined,
    regdate_start: undefined,
    regdate_end: undefined,
    lastdate_start: undefined,
    lastdate_end: undefined,
    salesman_name: 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 = '640'
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 getLeverage() {
    getDictByCode({
        dict_code: 'leverage',
        qcc_language: serverLang()
    }).then(resp => {
        leverageList.value = resp.data.map(i => {
            return { label: i.fun_item_text, value: i.fun_item_code }
        })
    })
}

function loadServerList() {
    mtServer({
        qcc_language: serverLang()
    }).then(resp => {
        if (resp.data) {
            mtServerList.value = resp.data
        }
    })
}

function loadGroupList(serverCode) {
    getMtGroup({
        qcc_mt_server: serverCode
    }).then(resp => {
        if (resp.data) {
            mtGroupList.value = resp.data.map(i => ({label: i.mt_group, value: i.mt_group}))
        }
    })
}

function handleChangeServer(value) {
    mtGroupList.value = []
    queryParams.mt_group = undefined
    if (value) {
        loadGroupList(value)
    }
}

function getList() {
    if (regDateRange.value && regDateRange.value.length && filters.value.includes('regdate')) {
        queryParams.value.regdate_start = regDateRange.value[0]
        queryParams.value.regdate_end = regDateRange.value[1]
    } else {
        queryParams.value.regdate_start = undefined
        queryParams.value.regdate_end = undefined
    }
    if (lastDateRange.value && lastDateRange.value.length && filters.value.includes('lastdate')) {
        queryParams.value.lastdate_start = lastDateRange.value[0]
        queryParams.value.lastdate_end = lastDateRange.value[1]
    } else {
        queryParams.value.lastdate_start = undefined
        queryParams.value.lastdate_end = undefined
    }
    queryParams.value.qcc_structure_value = props.structureValue
    queryParams.value.qcc_structure_type = props.structureType
    loading.value = true
    getReport40(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 (regDateRange.value && regDateRange.value.length && filters.value.includes('regdate')) {
        queryParams.value.regdate_start = regDateRange.value[0]
        queryParams.value.regdate_end = regDateRange.value[1]
    } else {
        queryParams.value.regdate_start = undefined
        queryParams.value.regdate_end = undefined
    }
    if (lastDateRange.value && lastDateRange.value.length && filters.value.includes('lastdate')) {
        queryParams.value.lastdate_start = lastDateRange.value[0]
        queryParams.value.lastdate_end = lastDateRange.value[1]
    } else {
        queryParams.value.lastdate_start = undefined
        queryParams.value.lastdate_end = undefined
    }
    queryParams.value.qcc_structure_value = props.structureValue
    queryParams.value.qcc_structure_type = props.structureType
    exportLoading.value = true
    proxy.download("/app/report/getReport40Export", {
    ...queryParams.value
  }, `report40.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()
    })
    getLeverage()
    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>