import React, { useState, useEffect } from 'react';
import { useAjax } from "@/Hook/useAjax";
import { Button, Card, Table, Input, Badge, Select, Tag, Space, Tooltip } from "antd";
import { QuestionCircleOutlined, SearchOutlined } from "@ant-design/icons";
import SearchBox from "@/pages/weComTask/components/searchBox";
import { getLicenseCodeListApi, GetLicenseCodeListProps } from "@/pages/weComTask/API/weChatApiLicense";
import { copy } from '@/utils/utils';
import ActiveCode from './activeCode';
import TransferCode from './transferCode';
import dayjs from 'dayjs';

const typeEnum = {
    1: <Tag color="#f50">基础账号</Tag>,
    2: <Tag color="#2db7f5">互通账号</Tag>
}

const statusEnum = {
    1: <Badge status="default" text="未绑定" />,
    2: <Badge status="success" text="已绑定且有效" />,
    3: <Badge status="error" text="已过期" />,
    4: <Badge status="processing" text="待转移" />,
    5: <Badge color='gold' text="已合并" />,
    6: <Badge color="lime" text="已分配给下游" />,
}

const SeatDetails: React.FC = () => {
    /***********************************/
    const [queryParams, setQueryParams] = useState<GetLicenseCodeListProps>({ pageNum: 1, pageSize: 20 })
    const [oldQueryParams, setOldQueryParams] = useState<GetLicenseCodeListProps>({ pageNum: 1, pageSize: 20 })
    const [selectedRows, setselectedRows] = useState<any[]>([])
    const [visible, setVisible] = useState<boolean>(false)
    const [visibleTr, setVisibleTr] = useState<boolean>(false)

    const getLicenseCodeList = useAjax((params) => getLicenseCodeListApi(params))
    /***********************************/

    useEffect(() => {
        getLicenseCodeList.run(queryParams)
    }, [queryParams])

    return <Card>
        <SearchBox
            bodyPadding={`0 0 10px`}
            buttons={<>
                <Button type="primary" onClick={() => {
                    setQueryParams({ ...oldQueryParams, pageNum: 1, pageSize: queryParams.pageSize })
                }} loading={getLicenseCodeList.loading} icon={<SearchOutlined />}>搜索</Button>
                <Button type="primary" disabled={selectedRows?.length === 0} onClick={() => setVisible(true)}>激活码激活</Button>
                <Button type="primary" disabled={selectedRows?.length === 0} onClick={() => setVisibleTr(true)}>激活码继承</Button>
            </>}
        >
            <>
                <Input
                    placeholder="企业名称"
                    style={{ width: 120 }}
                    allowClear
                    onChange={(e) => setOldQueryParams({ ...oldQueryParams, corpName: e.target.value })}
                    value={oldQueryParams?.corpName}
                />
                <Input
                    placeholder="账号激活码"
                    style={{ width: 120 }}
                    allowClear
                    onChange={(e) => setOldQueryParams({ ...oldQueryParams, activeCode: e.target.value })}
                    value={oldQueryParams?.activeCode}
                />
                <Select
                    allowClear
                    placeholder="账号状态"
                    showSearch
                    options={Object.keys(statusEnum).map(key => ({ label: statusEnum[key], value: key }))}
                    filterOption={(input, option) =>
                        ((option?.label ?? '') as string).toLowerCase().includes(input.toLowerCase())
                    }
                    style={{ width: 160 }}
                    value={oldQueryParams?.status}
                    onChange={(e) => setOldQueryParams({ ...oldQueryParams, status: e })}
                />
            </>
        </SearchBox>

        {/* 表 */}
        <Table
            style={{ marginTop: 10 }}
            dataSource={getLicenseCodeList?.data?.data?.records}
            loading={getLicenseCodeList?.loading}
            bordered
            columns={[
                {
                    title: '企业名称',
                    dataIndex: 'corpName',
                    key: 'corpName',
                    width: 200,
                    ellipsis: true,
                    render: (text) => <a onClick={() => copy(text)}>{text}</a>
                },
                {
                    title: '企业ID',
                    dataIndex: 'corpId',
                    key: 'corpId',
                    width: 250,
                    ellipsis: true,
                },
                {
                    title: '账号激活码',
                    dataIndex: 'activeCode',
                    key: 'activeCode',
                    width: 190,
                    ellipsis: true,
                },
                {
                    title: '账号类型',
                    dataIndex: 'type',
                    key: 'type',
                    width: 100,
                    align: 'center',
                    render: (text) => typeEnum[text]
                },
                {
                    title: '账号状态',
                    dataIndex: 'status',
                    key: 'status',
                    width: 120,
                    align: 'center',
                    render: (text) => statusEnum[text]
                },
                {
                    title: '账号绑定激活的企业成员名称',
                    dataIndex: 'userName',
                    key: 'userName',
                    width: 260,
                    align: 'center',
                    ellipsis: true,
                    render: (text, re: any) => text + `（${re?.userId}）`
                },
                {
                    title: <Space>
                        <span>创建时间</span>
                        <Tooltip title="订单支付成功后立即创建">
                            <QuestionCircleOutlined />
                        </Tooltip>
                    </Space>,
                    dataIndex: 'createTime',
                    key: 'createTime',
                    width: 135,
                    align: 'center',
                    ellipsis: true,
                    render: (text) => text || '--'
                },
                {
                    title: <Space>
                        <span>首次激活绑定用户的时间</span>
                        <Tooltip title="未激活则不返回该字段">
                            <QuestionCircleOutlined />
                        </Tooltip>
                    </Space>,
                    dataIndex: 'activeTime',
                    key: 'activeTime',
                    width: 155,
                    align: 'center',
                    ellipsis: true,
                    render: (text) => text || '--'
                },
                {
                    title: <Space>
                        <span>过期时间</span>
                        <Tooltip title="为首次激活绑定的时间加上购买时长。未激活则不返回该字段">
                            <QuestionCircleOutlined />
                        </Tooltip>
                    </Space>,
                    dataIndex: 'expireTime',
                    key: 'expireTime',
                    width: 155,
                    align: 'center',
                    render: (text) => {
                        return <span style={dayjs(text).diff(dayjs(), 'day') < 7 ? { color: 'red' } : {}}>{text || '--'}</span>
                    }
                },
                {
                    title: '数据更新时间',
                    dataIndex: 'updateTime',
                    key: 'updateTime',
                    width: 135,
                    align: 'center',
                    ellipsis: true,
                    sorter: true,
                    render: (text) => text || '--'
                }
            ]}
            scroll={{ x: 1000 }}
            rowKey={'activeCode'}
            size='small'
            pagination={{
                total: getLicenseCodeList?.data?.data?.total,
                showTotal: (total) => <Tag color="cyan">总共{total}数据</Tag>,
                showSizeChanger: true,
                showLessItems: true,
                defaultCurrent: 1,
                defaultPageSize: 20,//默认初始的每页条数
                current: getLicenseCodeList?.data?.data?.current || 1,
                pageSize: getLicenseCodeList?.data?.data?.size || 20,
            }}
            onChange={(pagination, _, sortData: any) => {
                let { current, pageSize } = pagination
                let newQueryForm = JSON.parse(JSON.stringify(queryParams))
                let newOldQueryParams = JSON.parse(JSON.stringify(oldQueryParams))
                if (sortData && sortData?.order) {
                    newQueryForm['sortAsc'] = sortData?.order === 'ascend' ? true : false
                    newQueryForm['sortFiled'] = sortData?.field
                } else {
                    delete newQueryForm['sortAsc']
                    delete newQueryForm['sortFiled']
                }
                newQueryForm.pageNum = current || newQueryForm.pageNum
                newQueryForm.pageSize = pageSize || newQueryForm.pageSize
                setQueryParams({ ...newQueryForm })
                setOldQueryParams({ ...newOldQueryParams })
            }}
            rowSelection={{
                selectedRowKeys: selectedRows?.map((item: any) => item?.activeCode),
                getCheckboxProps: (record: any) => ({
                    disabled: selectedRows.length > 0 ? record.corpId !== selectedRows[0].corpId : false
                }),
                onSelect: (record: { activeCode: string }, selected: boolean) => {
                    let newData = JSON.parse(JSON.stringify(selectedRows))
                    if (selected) {
                        newData.push({ ...record })
                    } else {
                        newData = newData.filter((item: { activeCode: string }) => item.activeCode !== record.activeCode)
                    }
                    setselectedRows(newData)
                },
                onSelectAll: (selected: boolean, _: { activeCode: string }[], changeRows: { activeCode: string, corpId: string }[]) => {
                    let newData = JSON.parse(JSON.stringify(selectedRows || '[]'))
                    if (selected) {
                        const firstCorpId = newData?.length > 0 ? newData?.[0].corpId : changeRows?.[0]?.corpId
                        changeRows.forEach((item: { activeCode: string, corpId: string }) => {
                            const index = newData.findIndex((ite: { activeCode: string }) => ite.activeCode === item.activeCode)
                            if (index === -1 && item.corpId === firstCorpId) {
                                newData.push(item)
                            }
                        })
                    } else {
                        const newSelectAccData = newData.filter((item: { activeCode: string }) => {
                            const index = changeRows.findIndex((ite: { activeCode: string }) => ite.activeCode === item.activeCode)
                            if (index !== -1) {
                                return false
                            } else {
                                return true
                            }
                        })
                        newData = newSelectAccData
                    }
                    setselectedRows(newData)
                }
            }}
        />

        {/* 激活激活码 */}
        {visible && <ActiveCode
            visible={visible}
            onChange={() => {
                setVisible(false)
                setselectedRows([])
            }}
            selectedRows={selectedRows}
            onClose={() => {
                setVisible(false)
            }}
        />}

        {/* 激活码继承 */}
        {visibleTr && <TransferCode
            visible={visibleTr}
            onChange={() => {
                setVisibleTr(false)
                setselectedRows([])
            }}
            selectedRows={selectedRows}
            onClose={() => {
                setVisibleTr(false)
            }}
        />}
    </Card>
};

export default SeatDetails;