<template>
    <a-row>
        <a-col :flex="1">
            <a-form :model="formModel" :label-col-props="{ span: 6 }" :wrapper-col-props="{ span: 18 }"
                label-align="left">
                <a-row :gutter="16">
                    <a-col :span="8">
                        <a-form-item field="query_date" :label="$t('searchTable.form.report_date')">
                            <a-range-picker v-model="formModel.query_date" style="width: 100%" @change="search" />
                        </a-form-item>
                    </a-col>
                </a-row>
            </a-form>
        </a-col>
        <a-divider style="height: 32px" direction="vertical" />
        <a-col :flex="'86px'" style="text-align: right">
            <a-space direction="vertical" :size="18">
                <a-button type="primary" @click="search">
                    <template #icon>
                        <icon-search />
                    </template>
                    {{ $t('searchTable.form.search') }}
                </a-button>
            </a-space>
        </a-col>
    </a-row>
    <a-divider style="margin-top: 0" />
    <a-row style="margin-bottom: 16px">
        <a-col :span="12"> </a-col>
        <a-col :span="12" style="
                        display: flex;
                        align-items: center;
                        justify-content: end;
                    ">
            <a-tooltip :content="$t('searchTable.actions.refresh')">
                <div class="action-icon" @click="search"><icon-refresh size="18" /></div>
            </a-tooltip>
            <a-dropdown @select="handleSelectDensity">
                <a-tooltip :content="$t('searchTable.actions.density')">
                    <div class="action-icon"><icon-line-height size="18" /></div>
                </a-tooltip>
                <template #content>
                    <a-doption v-for="item in densityList" :key="item.value" :value="item.value"
                        :class="{ active: item.value === size }">
                        <span>{{ item.name }}</span>
                    </a-doption>
                </template>
            </a-dropdown>
            <a-tooltip :content="$t('searchTable.actions.columnSetting')">
                <a-popover trigger="click" position="bl" @popup-visible-change="popupVisibleChange">
                    <div class="action-icon"><icon-settings size="18" /></div>
                    <template #content>
                        <div id="tableSetting">
                            <div v-for="(item, index) in showColumns" :key="item.dataIndex" class="setting">
                                <div style="
                                                margin-right: 4px;
                                                cursor: move;
                                            ">
                                    <icon-drag-arrow />
                                </div>
                                <div>
                                    <a-checkbox v-model="item.checked" @change="
                                        handleChange(
                                            $event,
                                            item as TableColumnData,
                                            index
                                        )
                                        ">
                                    </a-checkbox>
                                </div>
                                <div class="title">
                                    {{
                                        item.title === '#'
                                            ? '序列号'
                                            : item.title
                                    }}
                                </div>
                            </div>
                        </div>
                    </template>
                </a-popover>
            </a-tooltip>
        </a-col>
    </a-row>

    <a-table row-key="id" :loading="loading" :pagination="pagination" :summary="true" summary-text="汇总"
        :columns="(cloneColumns as TableColumnData[])" :scroll="scroll" :scrollbar="scrollbar" :data="renderData"
        :bordered="{ headerCell: true }" :size="size" :load-more="loadMore" @page-change="onPageChange"
        @page-size-change="onPageSizeChange">

        <template #index="{ rowIndex }">
            {{ rowIndex + 1 + (pagination.current - 1) * pagination.pageSize }}
        </template>
        <template #xAxis="{ record }">
            <template v-if="record.isLeaf">
                {{ record.accountName }}
            </template>
            <template v-else>
                {{ dayjs(record.log_date).format('YYYY-MM-DD') }}
            </template>
        </template>

        <template #total_count="{ record }">
            <a-popover v-if="record.total_count > 0" popup-container="body" trigger="click">
                <a-tag color="green">{{ record.total_count }}</a-tag>
                <template #content>
                    <CategoriesPercent total_key="total" :record="record" />
                </template>
            </a-popover>
        </template>
        <template #parse_total_count="{ record }">
            <a-popover v-if="record.parse_total_count > 0" popup-container="body" trigger="click">
                <a-tag color="green">{{ record.parse_total_count }}</a-tag>
                <template #content>
                    <CategoriesPercent total_key="parse_total" :record="record" />
                </template>
            </a-popover>
        </template>
        <template #jd_parse_total_count="{ record }">
            <a-popover v-if="record.jd_parse_total_count > 0" popup-container="body" trigger="click">
                <a-tag color="green">{{ record.jd_parse_total_count }}</a-tag>
                <template #content>
                    <CategoriesPercent total_key="jd_parse_total" :record="record" />
                </template>
            </a-popover>
        </template>
        <template #coupon_total_count="{ record }">
            <a-popover v-if="record.coupon_total_count > 0" popup-container="body" trigger="click">
                <a-tag color="green">{{ record.coupon_total_count }}</a-tag>
                <template #content>
                    <CategoriesPercent total_key="coupon_total" :record="record" />
                </template>
            </a-popover>
        </template>

        <template #tool_total_count="{ record }">
            <a-popover v-if="record.tool_total_count > 0" popup-container="body" trigger="click">
                <a-tag color="green">{{ record.tool_total_count }}</a-tag>
                <template #content>
                    <CategoriesPercent total_key="tool_total" :record="record" />
                </template>
            </a-popover>
        </template>

        <template #ks_parse_total_count="{ record }">
            <a-popover v-if="record.ks_parse_total_count > 0" popup-container="body" trigger="click">
                <a-tag color="green">{{ record.ks_parse_total_count }}</a-tag>
                <template #content>
                    <CategoriesPercent total_key="ks_parse_total" :record="record" />
                </template>
            </a-popover>
        </template>
        <template #pdd_parse_total_count="{ record }">
            <a-popover v-if="record.pdd_parse_total_count > 0" popup-container="body" trigger="click">
                <a-tag color="green">{{ record.pdd_parse_total_count }}</a-tag>
                <template #content>
                    <CategoriesPercent total_key="pdd_parse_total" :record="record" />
                </template>
            </a-popover>
        </template>


        <template #summary-cell="{ column, record }">
            <template v-if="column.slotName == 'total_count'">
                <a-tag v-if="record.total_count > 0" color="green">{{ record.total_count }}</a-tag>
            </template>
            <template v-else-if="column.slotName == 'parse_total_count'">
                <a-tag v-if="record.parse_total_count > 0" color="green">
                    {{ record.parse_total_count }}</a-tag>
            </template>
            <template v-else-if="column.slotName == 'coupon_total_count'">
                <a-tag v-if="record.coupon_total_count > 0" color="green">
                    {{ record.coupon_total_count }}</a-tag>
            </template>

            <template v-else-if="column.slotName == 'jd_parse_total_count'">
                <a-tag v-if="record.jd_parse_total_count > 0" color="green">
                    {{ record.jd_parse_total_count }}</a-tag>
            </template>

            <template v-else-if="column.slotName == 'ks_parse_total_count'">
                <a-tag v-if="record.ks_parse_total_count > 0" color="green">
                    {{ record.ks_parse_total_count }}</a-tag>
            </template>

            <template v-else-if="column.slotName == 'pdd_parse_total_count'">
                <a-tag v-if="record.pdd_parse_total_count > 0" color="green">
                    {{ record.pdd_parse_total_count }}</a-tag>
            </template>
            <template v-else>
                <div>{{ toAmount(record[column.dataIndex]) }}</div>
            </template>

        </template>



    </a-table>
</template>

<script lang="ts" setup>
import { useRouter } from 'vue-router';
import { computed, ref, reactive, watch, nextTick } from 'vue';
import { useI18n } from 'vue-i18n';
import dayjs from 'dayjs';
import useLoading from '@/hooks/loading';
import { queryDailyLog, DailyLogRecord, DailyLogParams } from '@/api/app';
import { Pagination } from '@/types/global';
import type { SelectOptionData } from '@arco-design/web-vue/es/select/interface';
import type { TableData, TableColumnData } from '@arco-design/web-vue/es/table/interface';
import cloneDeep from 'lodash/cloneDeep';
import Sortable from 'sortablejs';
import CategoriesPercent from './categories-percent.vue';

type SizeProps = 'mini' | 'small' | 'medium' | 'large';
type Column = TableColumnData & { checked?: true };

const generateFormModel = () => {
    return {
        accountName: 'all',
        current: 1,
        pageSize: 31,
        sort: 'log_date',
        order: 'descending'

    };
};
const router = useRouter();

const { loading, setLoading } = useLoading(true);
const { t } = useI18n();
const renderData = ref<DailyLogRecord[]>([]);
const formModel = ref(generateFormModel());
const cloneColumns = ref<Column[]>([]);
const showColumns = ref<Column[]>([]);

const size = ref<SizeProps>('medium');

const scrollbar = ref(true);
const scroll = {
    x: '100%',
    y: '100%',
    maxHeight: 'calc( 100vh - 420px)',
};

const basePagination: Pagination = {
    current: 1,
    pageSize: 31,
};
const pagination = reactive({
    ...basePagination,
    showTotal: true,
    showJumper: true,
    showMore: true,
    showPageSize: true,
    pageSizeOptions: [10, 20, 30, 31, 50, 100, 200],
    sizePageSize: true,

});
const densityList = computed(() => [
    {
        name: t('searchTable.size.mini'),
        value: 'mini',
    },
    {
        name: t('searchTable.size.small'),
        value: 'small',
    },
    {
        name: t('searchTable.size.medium'),
        value: 'medium',
    },
    {
        name: t('searchTable.size.large'),
        value: 'large',
    },
]);


const toAmount = (val: any): any => {
    console.log(val);
    if (typeof val === 'number' && !Number.isNaN(val)) {
        return parseFloat(val.toFixed(2));
    }
    return val;
}

const columns = computed<TableColumnData[]>(() => [
    {
        title: '日期',
        dataIndex: 'xAxis',
        slotName: 'xAxis',
        width: 250,
        fixed: 'left',
    },
    {
        title: '转链API调用',
        children: [
            {
                title: '调用',
                slotName: 'parse_total_count',
                dataIndex: 'parse_total_count',
                width: 100,
                align: 'right'
            },
            {
                title: '成功',
                dataIndex: 'parse_success_count',
                width: 100,
                align: 'right'
            },
            {
                title: '成功(%)',
                dataIndex: 'parse_success_percentage',
                width: 90,
                align: 'right'
            },
            {
                title: '放弃',
                dataIndex: 'parse_abandon_count',
                width: 100,
                align: 'right'
            },
            {
                title: '放弃(%)',
                dataIndex: 'parse_abandon_percentage',
                width: 90,
                align: 'right'
            },
        ]
    },
    {
        title: '优惠券API调用',
        children: [
            {
                title: '调用',
                slotName: 'coupon_total_count',
                dataIndex: 'coupon_total_count',
                width: 100,
                align: 'right'
            },
            {
                title: '成功',
                dataIndex: 'coupon_success_count',
                width: 100,
                align: 'right'
            },
            {
                title: '成功(%)',
                dataIndex: 'coupon_success_percentage',
                width: 90,
                align: 'right'
            },
            {
                title: '放弃',
                dataIndex: 'coupon_abandon_count',
                width: 100,
                align: 'right'
            },
            {
                title: '放弃(%)',
                dataIndex: 'coupon_abandon_percentage',
                width: 90,
                align: 'right'
            },
        ]
    },
    {
        title: '京东转链API调用',
        children: [
            {
                title: '调用',
                slotName: 'jd_parse_total_count',
                dataIndex: 'jd_parse_total_count',
                width: 100,
                align: 'right'
            },
            {
                title: '成功',
                dataIndex: 'jd_parse_success_count',
                width: 100,
                align: 'right'
            },
            {
                title: '成功(%)',
                dataIndex: 'jd_parse_success_percentage',
                width: 90,
                align: 'right'
            },
            {
                title: '放弃',
                dataIndex: 'jd_parse_abandon_count',
                width: 100,
                align: 'right'
            },
            {
                title: '放弃(%)',
                dataIndex: 'jd_parse_abandon_percentage',
                width: 90,
                align: 'right'
            },
        ]
    },
    {
        title: '拼多多转链API调用',
        children: [
            {
                title: '调用',
                slotName: 'pdd_parse_total_count',
                dataIndex: 'pdd_parse_total_count',
                width: 100,
                align: 'right'
            },
            {
                title: '成功',
                dataIndex: 'pdd_parse_success_count',
                width: 100,
                align: 'right'
            },
            {
                title: '成功(%)',
                dataIndex: 'pdd_parse_success_percentage',
                width: 90,
                align: 'right'
            },
            {
                title: '放弃',
                dataIndex: 'pdd_parse_abandon_count',
                width: 100,
                align: 'right'
            },
            {
                title: '放弃(%)',
                dataIndex: 'pdd_parse_abandon_percentage',
                width: 90,
                align: 'right'
            },
        ]
    },
    {
        title: '快手转链API调用',
        children: [
            {
                title: '调用',
                slotName: 'ks_parse_total_count',
                dataIndex: 'ks_parse_total_count',
                width: 100,
                align: 'right'
            },
            {
                title: '成功',
                dataIndex: 'ks_parse_success_count',
                width: 100,
                align: 'right'
            },
            {
                title: '成功(%)',
                dataIndex: 'ks_parse_success_percentage',
                width: 90,
                align: 'right'
            },
            {
                title: '放弃',
                dataIndex: 'ks_parse_abandon_count',
                width: 100,
                align: 'right'
            },
            {
                title: '放弃(%)',
                dataIndex: 'ks_parse_abandon_percentage',
                width: 90,
                align: 'right'
            },
        ]
    },

    {
        title: '工具API调用',
        children: [
            {
                title: '调用',
                dataIndex: 'tool_total_count',
                slotName: 'tool_total_count',
                width: 100,
                align: 'right'
            },
            {
                title: '成功',
                dataIndex: 'tool_success_count',
                width: 100,
                align: 'right'
            },
            {
                title: '成功(%)',
                dataIndex: 'tool_success_percentage',
                width: 90,
                align: 'right'
            },
            {
                title: '放弃',
                dataIndex: 'tool_abandon_count',
                width: 100,
                align: 'right'
            },
            {
                title: '放弃(%)',
                dataIndex: 'tool_abandon_percentage',
                width: 90,
                align: 'right'
            },
        ]
    },
    {
        title: '第三方API调用',
        children: [
            {
                title: '调用',
                dataIndex: 'total_count',
                slotName: 'total_count',
                width: 100,
                align: 'right'
            },
            {
                title: '成功',
                dataIndex: 'success_count',
                width: 100,
                align: 'right'
            },
            {
                title: '成功(%)',
                dataIndex: 'success_percentage',
                width: 90,
                align: 'right'
            },
            {
                title: '放弃',
                dataIndex: 'abandon_count',
                width: 100,
                align: 'right'
            },
            {
                title: '放弃(%)',
                dataIndex: 'abandon_percentage',
                width: 90,
                align: 'right'
            },
        ]
    },
]);


const onPageSizeChange = (current: number) => {
    basePagination.pageSize = current;
    pagination.pageSize = current;
    fetchData({
        ...basePagination,
        ...formModel.value,
        current: 1,
    });
};
const fetchData = async (
    params: DailyLogParams = {
        accountName: 'all',
        pageSize: basePagination.pageSize,
        current: 1,
        sort: 'log_date',
        order: 'descending'
    }
) => {
    setLoading(true);
    try {

        const { data } = await queryDailyLog(params);
        console.log(data);
        if (!data) return;
        // const { data } = await queryDailyLog(params);
        renderData.value = data.list;
        pagination.current = data.page;
        pagination.total = data.count;
        console.log(data)
    } catch (err) {

        console.log(err)
        // you can report use errorHandler or other
    } finally {
        setLoading(false);
    }
};

const loadMore = async (row: TableData, done: (data: TableData[]) => void) => {
    setLoading(true);
    try {

        const params: DailyLogParams = {
            query_date: [row.log_date, row.log_date],
            current: 1, pageSize: 999, sort: 'id', order: 'descending'
        };

        const { data } = await queryDailyLog(params);
        console.log(data);
        if (!data) return;

        const list: TableData[] = data.list.map((item: DailyLogRecord) => ({
            ...item,
            isLeaf: true
        }));
        done(list);
    } catch (err) {
        console.log(err)
    } finally {
        setLoading(false);
    }
};




const changeItem = async (
    data: DailyLogRecord
) => {
    router.push({ name: 'updateCookies' });
};



const search = () => {
    fetchData({
        ...basePagination,
        ...formModel.value,
    } as unknown as DailyLogParams);
};
const onPageChange = (current: number) => {
    fetchData({
        ...basePagination,
        ...formModel.value,
        current
    });
};

fetchData();
const reset = () => {
    formModel.value = generateFormModel();
};

const handleSelectDensity = (
    val: string | number | Record<string, any> | undefined,
    e: Event
) => {
    size.value = val as SizeProps;
};

const handleChange = (
    checked: boolean | (string | boolean | number)[],
    column: Column,
    index: number
) => {
    if (!checked) {
        cloneColumns.value = showColumns.value.filter(
            (item) => item.dataIndex !== column.dataIndex
        );
    } else {
        cloneColumns.value.splice(index, 0, column);
    }
};

const exchangeArray = <T extends Array<any>>(
    array: T,
    beforeIdx: number,
    newIdx: number,
    isDeep = false
): T => {
    const newArray = isDeep ? cloneDeep(array) : array;
    if (beforeIdx > -1 && newIdx > -1) {
        // 先替换后面的，然后拿到替换的结果替换前面的
        newArray.splice(
            beforeIdx,
            1,
            newArray.splice(newIdx, 1, newArray[beforeIdx]).pop()
        );
    }
    return newArray;
};

const popupVisibleChange = (val: boolean) => {
    if (val) {
        nextTick(() => {
            const el = document.getElementById('tableSetting') as HTMLElement;
            const sortable = new Sortable(el, {
                onEnd(e: any) {
                    const { oldIndex, newIndex } = e;
                    exchangeArray(cloneColumns.value, oldIndex, newIndex);
                    exchangeArray(showColumns.value, oldIndex, newIndex);
                },
            });
        });
    }
};

watch(
    () => columns.value,
    (val) => {
        cloneColumns.value = cloneDeep(val);
        cloneColumns.value.forEach((item, index) => {
            item.checked = true;
        });
        showColumns.value = cloneDeep(cloneColumns.value);
    },
    { deep: true, immediate: true }
);
</script>

<script lang="ts">
export default {
    name: 'SearchTable',
};
</script>

<style scoped lang="less">
.container {
    padding: 0 20px 20px 20px;
}

:deep(.arco-table-th) {
    &:last-child {
        .arco-table-th-item-title {
            margin-left: 16px;
        }
    }
}

.action-icon {
    margin-left: 12px;
    cursor: pointer;
}

.active {
    color: #0960bd;
    background-color: #e3f4fc;
}

.setting {
    display: flex;
    align-items: center;
    width: 200px;

    .title {
        margin-left: 12px;
        cursor: pointer;
    }
}
</style>
