<!-- 物联卡管理 -->
<template>
    <page-container class="container">
        <Search
            :columns="columns"
            target="iot-card-management-search"
            @search="handleSearch"
        />
        <JTable
            ref="cardManageRef"
            :columns="columns"
            :request="query"
            :defaultParams="{ sorts: [{ name: 'createTime', order: 'desc' }] }"
            :rowSelection="{
                selectedRowKeys: _selectedRowKeys,
                onChange: onSelectChange,
            }"
            @cancelSelect="cancelSelect"
            :params="params"
        >
            <template #headerTitle>
                <a-space>
                    <a-button type="primary" @click="handleAdd">
                        <AIcon type="PlusOutlined" />新增
                    </a-button>
                    <a-dropdown>
                        <a-button>
                            批量操作
                            <AIcon type="DownOutlined" />
                        </a-button>
                        <template #overlay>
                            <a-menu>
                                <a-menu-item>
                                    <a-button @click="exportVisible = true">
                                        <AIcon type="ExportOutlined" />
                                        批量导出
                                    </a-button>
                                </a-menu-item>
                                <a-menu-item>
                                    <a-button @click="importVisible = true"
                                        ><AIcon
                                            type="ImportOutlined"
                                        />批量导入</a-button
                                    >
                                </a-menu-item>
                                <a-menu-item>
                                    <a-popconfirm
                                        @confirm="handleActive"
                                        title="确认激活吗？"
                                    >
                                        <a-button>
                                            <AIcon type="CheckCircleOutlined" />
                                            批量激活
                                        </a-button>
                                    </a-popconfirm>
                                </a-menu-item>
                                <a-menu-item>
                                    <a-popconfirm
                                        @confirm="handleStop"
                                        title="确认停用吗？"
                                    >
                                        <a-button type="primary" ghost>
                                            <AIcon type="StopOutlined" />
                                            批量停用
                                        </a-button>
                                    </a-popconfirm>
                                </a-menu-item>
                                <a-menu-item>
                                    <a-popconfirm
                                        @confirm="handleResumption"
                                        title="确认复机吗？"
                                    >
                                        <a-button type="primary" ghost>
                                            <AIcon type="PoweroffOutlined" />
                                            批量复机
                                        </a-button>
                                    </a-popconfirm>
                                </a-menu-item>
                                <a-menu-item>
                                    <a-popconfirm
                                        @confirm="handleSync"
                                        title="确认同步状态吗？"
                                    >
                                        <a-button type="primary" ghost>
                                            <AIcon type="SwapOutlined" />
                                            同步状态
                                        </a-button>
                                    </a-popconfirm>
                                </a-menu-item>
                                <a-menu-item v-if="_selectedRowKeys.length > 0">
                                    <a-popconfirm
                                        @confirm="handelRemove"
                                        title="确认删除吗？"
                                    >
                                        <a-button>
                                            <AIcon type="DeleteOutlined" />
                                            批量删除
                                        </a-button>
                                    </a-popconfirm>
                                </a-menu-item>
                            </a-menu>
                        </template>
                    </a-dropdown>
                </a-space>
            </template>
            <template #card="slotProps">
                <CardBox
                    :value="slotProps"
                    @click="handleClick"
                    :actions="getActions(slotProps, 'card')"
                    v-bind="slotProps"
                    :active="_selectedRowKeys.includes(slotProps.id)"
                    :status="slotProps.cardStateType.value"
                    :statusText="slotProps.cardStateType.text"
                    :statusNames="{
                        using: 'success',
                        toBeActivated: 'default',
                        deactivate: 'error',
                    }"
                >
                    <template #img>
                        <slot name="img">
                            <img :src="getImage('/iot-card/iot-card-bg.png')" />
                        </slot>
                    </template>
                    <template #content>
                        <h3
                            class="card-item-content-title"
                            @click.stop="handleView(slotProps.id)"
                        >
                            {{ slotProps.id }}
                        </h3>
                        <a-row>
                            <a-col :span="8">
                                <div class="card-item-content-text">
                                    平台对接
                                </div>
                                <div>{{ slotProps.platformConfigName }}</div>
                            </a-col>
                            <a-col :span="6">
                                <div class="card-item-content-text">类型</div>
                                <div>{{ slotProps.cardType.text }}</div>
                            </a-col>
                            <a-col :span="6">
                                <div class="card-item-content-text">提醒</div>
                                <!-- <div>{{ slotProps.cardType.text }}</div> -->
                            </a-col>
                        </a-row>
                        <a-divider style="margin: 12px 0" />
                        <div v-if="slotProps.usedFlow === 0">
                            <span class="flow-text">
                                {{ slotProps.totalFlow }}
                            </span>
                            <span class="card-item-content-text">
                                M 使用流量</span
                            >
                        </div>
                        <div v-else>
                            <div class="progress-text">
                                <div>
                                    {{
                                        slotProps.totalFlow - slotProps.usedFlow
                                    }}
                                    %
                                </div>
                                <div class="card-item-content-text">
                                    总共 {{ slotProps.totalFlow }} M
                                </div>
                            </div>
                            <a-progress
                                :strokeColor="'#ADC6FF'"
                                :showInfo="false"
                                :percent="
                                    slotProps.totalFlow - slotProps.usedFlow
                                "
                            />
                        </div>
                    </template>
                    <template #actions="item">
                        <a-tooltip
                            v-bind="item.tooltip"
                            :title="item.disabled && item.tooltip.title"
                        >
                            <a-popconfirm
                                v-if="item.popConfirm"
                                v-bind="item.popConfirm"
                                :disabled="item.disabled"
                            >
                                <a-button :disabled="item.disabled">
                                    <AIcon
                                        type="DeleteOutlined"
                                        v-if="item.key === 'delete'"
                                    />
                                    <template v-else>
                                        <AIcon :type="item.icon" />
                                        <span>{{ item.text }}</span>
                                    </template>
                                </a-button>
                            </a-popconfirm>
                            <template v-else>
                                <a-button
                                    :disabled="item.disabled"
                                    @click="item.onClick"
                                >
                                    <AIcon
                                        type="DeleteOutlined"
                                        v-if="item.key === 'delete'"
                                    />
                                    <template v-else>
                                        <AIcon :type="item.icon" />
                                        <span>{{ item.text }}</span>
                                    </template>
                                </a-button>
                            </template>
                        </a-tooltip>
                    </template>
                </CardBox>
            </template>
            <template #deviceId="slotProps">
                {{ slotProps.deviceName }}
            </template>
            <template #totalFlow="slotProps">
                <div>
                    {{
                        slotProps.totalFlow
                            ? slotProps.totalFlow.toFixed(2) + ' M'
                            : ''
                    }}
                </div>
            </template>
            <template #usedFlow="slotProps">
                <div>
                    {{
                        slotProps.usedFlow
                            ? slotProps.usedFlow.toFixed(2) + ' M'
                            : ''
                    }}
                </div>
            </template>
            <template #residualFlow="slotProps">
                <div>
                    {{
                        slotProps.residualFlow
                            ? slotProps.residualFlow.toFixed(2) + ' M'
                            : ''
                    }}
                </div>
            </template>
            <template #cardType="slotProps">
                {{ slotProps.cardType.text }}
            </template>
            <template #cardStateType="slotProps">
                {{ slotProps.cardStateType.text }}
            </template>
            <template #activationDate="slotProps">
                {{
                    slotProps.activationDate
                        ? moment(slotProps.activationDate).format(
                              'YYYY-MM-DD HH:mm:ss',
                          )
                        : ''
                }}
            </template>
            <template #updateTime="slotProps">
                {{
                    slotProps.updateTime
                        ? moment(slotProps.updateTime).format(
                              'YYYY-MM-DD HH:mm:ss',
                          )
                        : ''
                }}
            </template>
            <template #action="slotProps">
                <a-space :size="16">
                    <a-tooltip
                        v-for="i in getActions(slotProps, 'table')"
                        :key="i.key"
                        v-bind="i.tooltip"
                    >
                        <a-popconfirm v-if="i.popConfirm" v-bind="i.popConfirm">
                            <a-button
                                :disabled="i.disabled"
                                style="padding: 0"
                                type="link"
                                ><AIcon :type="i.icon"
                            /></a-button>
                        </a-popconfirm>
                        <a-button
                            style="padding: 0"
                            type="link"
                            v-else
                            @click="i.onClick && i.onClick(slotProps)"
                        >
                            <a-button
                                :disabled="i.disabled"
                                style="padding: 0"
                                type="link"
                                ><AIcon :type="i.icon"
                            /></a-button>
                        </a-button>
                    </a-tooltip>
                </a-space>
            </template>
        </JTable>
        <!-- 批量导入 -->
        <Import v-if="importVisible" @close="importVisible = false" />
        <!-- 批量导出 -->
        <Export
            v-if="exportVisible"
            @close="exportVisible = false"
            :data="_selectedRowKeys"
        />
        <!-- 绑定设备 -->
        <BindDevice
            v-if="bindDeviceVisible"
            :cardId="cardId"
            @change="bindDevice"
        />
        <!-- 新增、编辑 -->
        <Save
            v-if="visible"
            :type="saveType"
            :data="current"
            @change="saveChange"
        />
    </page-container>
</template>

<script setup lang="ts">
import type { ActionsType } from '@/components/Table';
import moment from 'moment';
import {
    query,
    queryPlatformNoPage,
    changeDeploy,
    unDeploy,
    resumption,
    del,
    changeDeployBatch,
    unDeployBatch,
    resumptionBatch,
    sync,
    removeCards,
    unbind,
} from '@/api/iot-card/cardManagement';
import { message } from 'ant-design-vue';
import type { CardManagement } from './typing';
import { getImage } from '@/utils/comm';
import BindDevice from './BindDevice.vue';
import Import from './Import.vue';
import Export from './Export.vue';
import Save from './Save.vue';

const router = useRouter();

const cardManageRef = ref<Record<string, any>>({});
const params = ref<Record<string, any>>({});
const _selectedRowKeys = ref<string[]>([]);
const _selectedRow = ref<any[]>([]);
const bindDeviceVisible = ref<boolean>(false);
const visible = ref<boolean>(false);
const exportVisible = ref<boolean>(false);
const importVisible = ref<boolean>(false);
const cardId = ref<any>();
const current = ref<Partial<CardManagement>>({});
const saveType = ref<string>('');

const columns = [
    {
        title: '卡号',
        dataIndex: 'id',
        key: 'id',
        width: 300,
        ellipsis: true,
        fixed: 'left',
        search: {
            type: 'string',
        },
    },
    {
        title: 'ICCID',
        dataIndex: 'iccId',
        key: 'iccId',
        ellipsis: true,
        width: 200,
        search: {
            type: 'string',
        },
    },
    {
        title: '绑定设备',
        dataIndex: 'deviceId',
        key: 'deviceId',
        ellipsis: true,
        scopedSlots: true,
        width: 200,
    },
    {
        title: '平台对接',
        dataIndex: 'platformConfigName',
        key: 'platformConfigName',
        width: 200,
        search: {
            rename: 'platformConfigId',
            type: 'select',
            options: async () => {
                return new Promise((resolve) => {
                    queryPlatformNoPage({
                        sorts: [{ name: 'createTime', order: 'desc' }],
                        terms: [{ column: 'state', value: 'enabled' }],
                    }).then((resp: any) => {
                        const list = resp.result.map((item: any) => ({
                            label: item.name,
                            value: item.id,
                        }));
                        resolve(list);
                    });
                });
            },
        },
    },
    {
        title: '运营商',
        dataIndex: 'operatorName',
        key: 'operatorName',
        width: 120,
        search: {
            type: 'select',
            options: [
                { label: '移动', value: '移动' },
                { label: '电信', value: '电信' },
                { label: '联通', value: '联通' },
            ],
        },
    },
    {
        title: '类型',
        dataIndex: 'cardType',
        key: 'cardType',
        scopedSlots: true,
        width: 120,
        search: {
            type: 'select',
            options: [
                { label: '年卡', value: 'year' },
                { label: '季卡', value: 'season' },
                { label: '月卡', value: 'month' },
                { label: '其他', value: 'other' },
            ],
        },
    },
    {
        title: '总流量',
        dataIndex: 'totalFlow',
        width: 120,
        scopedSlots: true,
    },
    {
        title: '使用流量',
        dataIndex: 'usedFlow',
        width: 120,
        scopedSlots: true,
    },
    {
        title: '剩余流量',
        dataIndex: 'residualFlow',
        width: 120,
        scopedSlots: true,
    },
    {
        title: '激活日期',
        dataIndex: 'activationDate',
        key: 'activationDate',
        scopedSlots: true,
        width: 200,
        search: {
            type: 'date',
        },
    },
    {
        title: '更新时间',
        dataIndex: 'updateTime',
        key: 'updateTime',
        scopedSlots: true,
        width: 200,
        search: {
            type: 'date',
        },
    },
    {
        title: '状态',
        dataIndex: 'cardStateType',
        key: 'cardStateType',
        width: 180,
        scopedSlots: true,
        search: {
            type: 'select',
            options: [
                { label: '正常', value: 'using' },
                { label: '未激活', value: 'toBeActivated' },
                { label: '停机', value: 'deactivate' },
            ],
        },
    },
    {
        title: '操作',
        key: 'action',
        fixed: 'right',
        width: 250,
        scopedSlots: true,
    },
];

const getActions = (
    data: Partial<Record<string, any>>,
    type: 'card' | 'table',
): ActionsType[] => {
    if (!data) return [];
    return [
        {
            key: 'edit',
            text: '编辑',
            tooltip: {
                title: '编辑',
            },
            icon: 'EditOutlined',
            onClick: () => {
                visible.value = true;
                current.value = data;
                saveType.value = 'edit';
            },
        },
        {
            key: 'view',
            text: '查看',
            tooltip: {
                title: '查看',
            },
            icon: 'EyeOutlined',
            onClick: () => {
                router.push({
                    path: `/iot-card/CardManagement/detail/${data.id}`,
                });
            },
        },
        {
            key: 'bindDevice',
            text: data.deviceId ? '解绑设备' : '绑定设备',
            tooltip: {
                title: data.deviceId ? '解绑设备' : '绑定设备',
            },
            icon: data.deviceId ? 'DisconnectOutlined' : 'LinkOutlined',
            popConfirm: data.deviceId
                ? {
                      title: '确认解绑设备？',
                      onConfirm: async () => {
                          unbind(data.id).then((resp: any) => {
                              if (resp.status === 200) {
                                  message.success('操作成功');
                                  cardManageRef.value?.reload();
                              }
                          });
                      },
                  }
                : undefined,
            onClick: () => {
                if (!data.deviceId) {
                    bindDeviceVisible.value = true;
                    cardId.value = data.id;
                }
            },
        },
        {
            key: 'activation',
            text:
                data.cardStateType?.value === 'toBeActivated'
                    ? '激活'
                    : data.cardStateType?.value === 'deactivate'
                    ? '复机'
                    : '停用',
            tooltip: {
                title:
                    data.cardStateType?.value === 'toBeActivated'
                        ? '激活'
                        : data.cardStateType?.value === 'deactivate'
                        ? '复机'
                        : '停用',
            },
            icon:
                data.cardStateType?.value === 'toBeActivated'
                    ? 'CheckCircleOutlined'
                    : data.cardStateType?.value === 'deactivate'
                    ? 'PoweroffOutlined'
                    : 'StopOutlined',
            popConfirm: {
                title:
                    data.cardStateType?.value === 'toBeActivated'
                        ? '确认激活？'
                        : data.cardStateType?.value === 'deactivate'
                        ? '确认复机？'
                        : '确认停用?',
                onConfirm: async () => {
                    if (data.cardStateType?.value === 'toBeActivated') {
                        changeDeploy(data.id).then((resp) => {
                            if (resp.status === 200) {
                                message.success('操作成功');
                                cardManageRef.value?.reload();
                            }
                        });
                    } else if (data.cardStateType?.value === 'deactivate') {
                        resumption(data.id).then((resp) => {
                            if (resp.status === 200) {
                                message.success('操作成功');
                                cardManageRef.value?.reload();
                            }
                        });
                    } else {
                        unDeploy(data.id).then((resp) => {
                            if (resp.status === 200) {
                                message.success('操作成功');
                                cardManageRef.value?.reload();
                            }
                        });
                    }
                },
            },
        },
        {
            key: 'delete',
            text: '删除',
            tooltip: {
                title: '删除',
            },
            popConfirm: {
                title: '确认删除?',
                onConfirm: async () => {
                    const resp: any = await del(data.id);
                    if (resp.status === 200) {
                        message.success('操作成功！');
                        cardManageRef.value?.reload();
                    } else {
                        message.error('操作失败！');
                    }
                },
            },
            icon: 'DeleteOutlined',
        },
    ];
};

const handleSearch = (params: any) => {
    console.log(params);
    params.value = params;
};

const onSelectChange = (keys: string[], rows: []) => {
    _selectedRowKeys.value = [...keys];
    _selectedRow.value = [...rows];
};

const cancelSelect = () => {
    _selectedRowKeys.value = [];
};

const handleClick = (dt: any) => {
    if (_selectedRowKeys.value.includes(dt.id)) {
        const _index = _selectedRowKeys.value.findIndex((i) => i === dt.id);
        _selectedRowKeys.value.splice(_index, 1);
    } else {
        _selectedRowKeys.value = [..._selectedRowKeys.value, dt.id];
    }
};

/**
 * 查看
 */
const handleView = (id: string) => {
    message.warn(id + '暂未开发');
};

/**
 * 新增
 */
const handleAdd = () => {
    visible.value = true;
    current.value = {};
    saveType.value = 'add';
};

/**
 * 新增、编辑关闭弹窗
 * @param val 加载表格
 */
const saveChange = (val: any) => {
    visible.value = false;
    current.value = {};
    if (val) {
        cardManageRef.value?.reload();
    }
};

/**
 * 绑定设备关闭窗口
 * @param val
 */
const bindDevice = (val: boolean) => {
    bindDeviceVisible.value = false;
    cardId.value = '';
    if (val) {
        cardManageRef.value?.reload();
    }
};

/**
 * 批量激活
 */
const handleActive = () => {
    if (
        _selectedRowKeys.value.length >= 10 &&
        _selectedRowKeys.value.length <= 100
    ) {
        changeDeployBatch(_selectedRowKeys.value).then((res: any) => {
            if (res.status === 200) {
                message.success('操作成功');
            }
        });
    } else {
        message.warn('仅支持同一个运营商下且最少10条数据,最多100条数据');
    }
};

/**
 * 批量停用
 */
const handleStop = () => {
    if (
        _selectedRowKeys.value.length >= 10 &&
        _selectedRowKeys.value.length <= 100
    ) {
        unDeployBatch(_selectedRowKeys.value).then((res: any) => {
            if (res.status === 200) {
                message.success('操作成功');
            }
        });
    } else {
        message.warn('仅支持同一个运营商下且最少10条数据,最多100条数据');
    }
};

/**
 * 批量复机
 */
const handleResumption = () => {
    if (
        _selectedRowKeys.value.length >= 10 &&
        _selectedRowKeys.value.length <= 100
    ) {
        resumptionBatch(_selectedRowKeys.value).then((res: any) => {
            if (res.status === 200) {
                message.success('操作成功');
            }
        });
    } else {
        message.warn('仅支持同一个运营商下且最少10条数据,最多100条数据');
    }
};

/**
 * 同步状态
 */
const handleSync = () => {
    sync().then((res: any) => {
        if (res.status === 200) {
            cardManageRef.value?.reload();
            message.success('同步状态成功');
        }
    });
};

/**
 * 批量删除
 */
const handelRemove = async () => {
    const resp = await removeCards(_selectedRow.value);
    if (resp.status === 200) {
        message.success('操作成功！');
        _selectedRowKeys.value = [];
        _selectedRow.value = [];
        cardManageRef.value?.reload();
    }
};
</script>

<style scoped lang="less">
.container {
    .search {
        width: calc(100% - 330px);
    }
    .flow-text {
        font-size: 20px;
        font-weight: 600;
    }

    .progress-text {
        display: flex;
        justify-content: space-between;
        align-items: center;
    }
    :deep(.ant-progress-inner) {
        border-radius: 0px;
    }
    :deep(.ant-progress-bg) {
        border-radius: 0px;
    }
}
</style>
