<template>
    <div class="container">
        <Breadcrumb :items="['menu.taobao', 'menu.taobao.list']" />
        <a-card class="general-card" :title="$t('menu.taobao.list')">
            <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="name" label="账号名">
                                    <a-input v-model="formModel.name" placeholder="输入关键词搜索" />
                                </a-form-item>
                            </a-col>
                            <a-col :span="8">
                                <a-form-item field="lastTime" :label="$t('searchTable.form.lastTime')">
                                    <a-range-picker v-model="formModel.lastTime" style="width: 100%" />
                                </a-form-item>
                            </a-col>
                            <a-col :span="8">
                                <a-form-item field="status" :label="$t('searchTable.form.status')">
                                    <a-select v-model="formModel.status" :options="statusOptions" :placeholder="$t('searchTable.form.selectDefault')
                                        " />
                                </a-form-item>
                            </a-col>
                        </a-row>
                    </a-form>
                </a-col>
                <a-divider style="height: 38px" 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-space>
                        <a-button type="primary">
                            <template #icon>
                                <icon-plus />
                            </template>
                            {{ $t('searchTable.operation.create') }}
                        </a-button>
                    </a-space>
                </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[])" :data="renderData" :bordered="false" :size="size"
                :row-class="getRowClass" @page-change="onPageChange" @page-size-change="onPageSizeChange">
                <template #index="{ record }">
                    {{ record.id }}
                </template>
                <template #name="{ record }">
                    <a-list-item-meta :title="record.company" :description="record.description" />

                </template>
                <template #daily_income_limit="{ record }">
                    <a-tag bordered
                        :color="record.current_amt > record.daily_income_limit && record.daily_income_limit > 0 ? 'red' : ''">
                        {{ record.current_amt }} /
                        {{ record.daily_income_limit }}
                    </a-tag>
                </template>

                <template #nodeName="{ record }">
                    <a-tag color="gray" @click="changePublicIp(record.nodeName)">{{ record.end_point }} - {{
                        record.nodeName }} </a-tag>
                </template>

                <template #suspended_endpoint="{ record }">
                    <a-tag v-if="record.suspended_endpoint" size="small" bordered color="red"
                        @click="changeAttr(record.id, 'check_status', true)">
                        暂停：{{ record.suspended_endpoint }}</a-tag>

                    <a-tag v-else size="small" bordered color="gray"
                        @click="changeAttr(record.id, 'check_status', true)">
                        正常</a-tag>

                </template>
                <template #tags="{ record }">
                    <a-tag v-if="record.is_banned" size="small" bordered color="red">
                        封号
                    </a-tag>
                    <a-tag v-if="record.riskCookie" size="small" bordered color="red">
                        {{ record.riskCookie }}
                    </a-tag>
                    <a-typography-text mark v-if="record.note">
                        {{ record.note }}
                    </a-typography-text>
                    <a-tag v-if="record.parse_type" size="small" bordered color="blue">
                        {{ record.parse_type }}
                    </a-tag>
                    <a-tag v-if="record.riskStrategy" size="small" bordered color="orange">
                        {{ record.riskStrategy }}-{{ record.launchScene }}
                    </a-tag>
                </template>
                <template #status="{ record }">
                    <a-tag v-if="record.status" bordered color="green" @click="changeStatus(record, false)">
                        <template #icon>
                            <icon-check />
                        </template>
                        在线
                    </a-tag>
                    <a-tag v-else bordered color="" @click="changeStatus(record, true)">
                        <template #icon>
                            <icon-stop />
                        </template>
                        下线
                    </a-tag>
                </template>
                <template #actions="{ record }">
                    <a-tag v-if="record.enable_parse" size="small" bordered color="red"
                        @click="changeAttr(record.id, 'enable_parse', false)">
                        转链
                    </a-tag>
                    <a-tag v-else size="small" bordered color="" @click="changeAttr(record.id, 'enable_parse', true)">
                        转链
                    </a-tag>
                    <span style="margin: 5px;">
                        <a-tag v-if="record.enable_coupon" size="small" bordered color="orange"
                            @click="changeAttr(record.id, 'enable_coupon', false)">
                            优惠券
                        </a-tag>
                        <a-tag v-else size="small" bordered color=""
                            @click="changeAttr(record.id, 'enable_coupon', true)">
                            优惠券
                        </a-tag>
                    </span>
                    <a-tag v-if="record.enable_sync_order" size="small" bordered color="arcoblue"
                        @click="changeAttr(record.id, 'enable_sync_order', false)">
                        同步订单
                    </a-tag>
                    <a-tag v-else size="small" bordered color="gray"
                        @click="changeAttr(record.id, 'enable_sync_order', true)">
                        同步订单
                    </a-tag>
                    <span style="margin:0 5px;">
                        <a-tag v-if="record.enable_fake_click" size="small" bordered color="blue"
                            @click="changeAttr(record.id, 'enable_fake_click', false)">
                            补点击
                        </a-tag>
                        <a-tag v-else size="small" bordered color="gray"
                            @click="changeAttr(record.id, 'enable_fake_click', true)">
                            补点击
                        </a-tag>
                    </span>

                    <span style="margin:0 5px;">
                        <a-tag v-if="record.enable_promotionQuery" size="small" bordered color="orangered"
                            @click="changeAttr(record.id, 'enable_promotionQuery', false)">
                            搜同款
                        </a-tag>
                        <a-tag v-else size="small" bordered color="gray"
                            @click="changeAttr(record.id, 'enable_promotionQuery', true)">
                            搜同款
                        </a-tag>
                    </span>

                    <a-tag v-if="record.enable_deep_url" size="small" bordered color="blue"
                        @click="changeAttr(record.id, 'enable_deep_url', false)">
                        下探网址
                    </a-tag>
                    <a-tag v-else size="small" bordered color="gray"
                        @click="changeAttr(record.id, 'enable_deep_url', true)">
                        下探网址
                    </a-tag>

                </template>
                <template #time="{ record }">
                    <div style="color:gray;">
                        <div>注册：{{ dayjs(record.create_time).format('MM-DD HH:mm') }}</div>
                        <div>更新：{{ dayjs(record.last_time).format('MM-DD HH:mm') }}</div>
                        <div v-if="dayjs().diff(dayjs(record.login_time), 'hours') < 48">
                            登录：{{ dayjs(record.login_time).format('MM-DD HH:mm') }}</div>
                        <a-tooltip v-else>
                            <template #content>
                                <div>登录：{{ dayjs(record.login_time).format('MM-DD HH:mm') }}</div>
                                <div>登录状态即将掉线，请尽快处理</div>
                            </template>
                            <div style="color:red;">
                                预计 {{ 72 - dayjs().diff(dayjs(record.login_time), 'hours') }} 小时后掉线
                            </div>
                        </a-tooltip>
                    </div>
                </template>
                <template #operations="{ record }">
                    <a-button type="text" size="small" @click="changeItem(record)">
                        更新
                    </a-button>
                    <a-button type="text" size="small" @click="billView(record)">
                        预计收益
                    </a-button>
                </template>

                <template #summary-cell="{ column, record }">
                    <div style="margin:10px auto" v-if="column.slotName == 'daily_income_limit'">
                        预估： {{ amountFormat(record.current_amt) }}
                    </div>
                </template>

                <template #time_range="{ record }">
                    <WorkHourModel :path="updatePath" :record="record" @change="search" />
                </template>
                <template #hourly_calls_limit="{ record }">
                    <a-tag bordered
                        :color="record.current_hourly_calls > record.hourly_calls_limit && record.hourly_calls_limit > 0 ? 'red' : ''">
                        {{ record.current_hourly_calls }} /
                        {{ record.hourly_calls_limit }}
                    </a-tag>
                </template>

                <template #daily_calls_limit="{ record }">
                    <a-tag bordered
                        :color="record.current_daily_calls > record.daily_calls_limit && record.daily_calls_limit > 0 ? 'red' : ''">
                        {{ record.current_daily_calls }} /
                        {{ record.daily_calls_limit }}
                    </a-tag>
                </template>

            </a-table>
        </a-card>
    </div>
</template>

<script lang="ts" setup>
import { useRouter, useRoute } 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 { queryTkPool, TkPoolRecord, TkPoolParams, TkUpdateAccountModel, TkUpdateAccount } from '@/api/taobao';
import { changePublicIpByName } from '@/api/proxy';
import { Pagination } from '@/types/global';
import { Modal, Message } from '@arco-design/web-vue';
import type { SelectOptionData } from '@arco-design/web-vue/es/select/interface';
import type { TableColumnData } from '@arco-design/web-vue/es/table/interface';
import cloneDeep from 'lodash/cloneDeep';
import Sortable from 'sortablejs';
import { numberFormat, amountFormat } from '@/utils/util';
import { UpdateAccountModel, UpdateAccount } from '@/api/app';
import WorkHourModel from '@/components/WorkHourModel.vue';

const updatePath = '/api/taobao/update';


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

const generateFormModel = () => {
    return {
        name: '',
        lastTime: [],
        status: '',
        show_hide: false,
        sort: 'status',
        order: 'descending',
    };
};
const router = useRouter();
const route = useRoute();

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


const cloneColumns = ref<Column[]>([]);
const showColumns = ref<Column[]>([]);

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

const basePagination: Pagination = {
    current: 1,
    pageSize: 50,
    showPageSize: true,
    showTotal: true,
    pageSizeOptions: [10, 20, 50, 100, 200, 500]
};
const pagination = reactive({
    ...basePagination,
});
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 columns = computed<TableColumnData[]>(() => [
    {
        title: '#',
        dataIndex: 'index',
        slotName: 'index',
        width: 50,
    },
    {
        title: '账号名',
        dataIndex: 'name',
        slotName: 'name',
        width: 200,
    },
    {
        title: '',
        slotName: 'tags',
        width: 40,
    },
    {
        title: '工作时间',
        dataIndex: 'time_range',
        slotName: 'time_range',
        align: 'right',
        width: 200,
    },
    {
        title: '小时调用',
        slotName: 'hourly_calls_limit',
        dataIndex: 'current_hourly_calls',
        align: 'right',
        width: 120,
    },
    {
        title: '当日调用',
        slotName: 'daily_calls_limit',
        dataIndex: 'current_daily_calls',
        align: 'right',
        width: 150,
    },
    {
        title: '每日收益限额',
        slotName: 'daily_income_limit',
        dataIndex: 'current_amt',
        align: 'right',
        width: 180,
    },
    {
        title: '可提现余额',
        dataIndex: 'draw_balance',
        width: 120,
    },
    {
        title: '运行节点',
        slotName: 'nodeName',
        width: 120,
    },
    {
        title: '挂起节点',
        slotName: 'suspended_endpoint',
        width: 120,
    },
    {
        title: '状态',
        slotName: 'status',
        width: 100,
    },
    {
        title: '分类',
        slotName: 'actions',
        width: 400,
        align: 'center',
    },
    {
        title: '时间',
        slotName: 'time',
        width: 170,
    },
    {
        title: '操作',
        dataIndex: 'operations',
        slotName: 'operations',
        align: 'right',
        width: 150,
    },
]);

const statusOptions = computed<SelectOptionData[]>(() => [
    {
        label: '全部',
        value: '',
    },
    {
        label: '在线',
        value: 'online',
    },
    {
        label: '下线',
        value: 'offline',
    },
]);

const getRowClass = (record: TkPoolRecord) => {
    return record.is_hide ? 'special-table-row' : '';
};


if (route.query.show_hide === '1') {
    formModel.value.show_hide = true;
}
const fetchData = async (
    params: TkPoolParams = {
        current: 1,
        pageSize: 50,
        show_hide: false,
        sort: 'status',
        order: 'descending',
        getTotal: true,
    }
) => {
    if (route.query.show_hide === '1') {
        params.show_hide = true;
    }

    setLoading(true);
    try {
        const { data } = await queryTkPool(params);
        if (!data) return;
        // const { data } = await queryTkPool(params);
        renderData.value = data.list;
        pagination.current = data.page;
        pagination.total = data.count;
    } catch (err) {
        console.log(err);
        // you can report use errorHandler or other
    } finally {
        setLoading(false);
    }
};

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

const billView = async (data: TkPoolRecord) => {
    router.push({ name: 'taobao_bill_dailys', query: { name: data.company } });
};



const changeStatus = async (data: TkPoolRecord, val: any) => {
    if (data.is_banned && val) {
        Message.error('被封账号，不能上线！');
        return;
    }
    const args = {
        id: data.id,
        name: 'status',
        val
    } as TkUpdateAccountModel;


    Modal.confirm({
        title: '确认提示',
        content: '确定要更改状态吗？',
        okText: '确认',
        cancelText: '取消',
        async onOk() {
            setLoading(true);

            try {
                const { data } = await TkUpdateAccount(args);
                console.log(data, data.msg);
                const msg = data.msg || '更新成功!';
                if (data.success) {
                    Message.success(msg);
                    search();
                } else {
                    Message.error(data.msg);
                }

            } catch (e) {
                console.log(e);
            }
            setLoading(false);
        }
    });
};

const changeAttr = async (id: number, name: string, val: any) => {
    const args = {
        id,
        name,
        val
    } as TkUpdateAccountModel;


    Modal.confirm({
        title: '确认提示',
        content: '确定要更改状态吗？',
        okText: '确认',
        cancelText: '取消',
        async onOk() {
            setLoading(true);
            try {

                const { data } = await TkUpdateAccount(args);
                console.log(data, data.msg);
                const msg = data.msg || '更新成功!';
                if (data.success) {
                    Message.success(msg);
                    search();
                } else {
                    Message.error(data.msg);
                }
            } catch (e) { console.log(e) }
            setLoading(false);
        }
    });

};

const changePublicIp = async (nodeName: string) => {
    Modal.confirm({
        title: '确认提示',
        content: `确定要更改节点 ${nodeName} 的公网IP吗？`,
        okText: '确认',
        cancelText: '取消',
        async onOk() {
            setLoading(true);

            try {
                const { data } = await changePublicIpByName(nodeName);
                console.log(data);
                const msg = data.msg || '更新IP成功!';
                if (data.success) {
                    Message.success(msg);
                    search();
                } else {
                    Message.error(data.msg);
                }
            } catch (e) {
                console.log(e);
            } finally {
                setLoading(false);
            }
        }
    });
};




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

const onPageSizeChange = (current: number) => {
    basePagination.pageSize = current;
    pagination.pageSize = current;
    fetchData({
        ...basePagination,
        ...formModel.value,
        current: 1,
    } as unknown as TkPoolParams);
};

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;
    }
}

:deep(.special-table-row td) {
    background-color: var(--color-warning-light-2) !important;
}
</style>
