import Selector from "@/pages/launchSystemNew/launchManage/createAd/selector"
import React, { useEffect, useState } from "react"
import style from './index.less'
import { Button, Col, Form, Input, Row, Select, Space, Table, Tag, Tooltip, Typography } from "antd";
import { CloseCircleFilled } from "@ant-design/icons";
import { useAjax } from "@/Hook/useAjax";
import { getUserAccountListApi } from "@/services/launchAdq/adAuthorize";
import { arraysHaveSameValues } from "@/utils/utils";
import '@/pages/launchSystemV3/tencentAdPutIn/index.less'
const { Text } = Typography;

interface Props {
    value?: number[]
    onChange?: (value?: number[] | number, data?: any[] | any) => void
    type?: 'checkbox' | 'radio'
    /**  是否第一次获取的时候返回值 */
    isReturnFirstValue?: boolean
    allowClear?: boolean
    initialValues?: any
}



const SelectAdAccount: React.FC<Props> = ({ value, onChange, isReturnFirstValue, type = 'checkbox', allowClear = true, initialValues = {} }) => {

    value = value && typeof value !== 'object' ? [value] : value
    /***********************************/
    const [form] = Form.useForm()
    const [visible, setVisible] = useState<boolean>(false)
    const [selectedRows, setSelectedRows] = useState<any[]>([])
    const [queryForm, setQueryForm] = useState<{ accountIdList?: number[], adUnitTypeList?: string[], groupId?: number, remark?: string, putInType?: 'NOVEL' | 'GAME', sysGroupId?: number, pageNum: number, pageSize: number }>({ pageNum: 1, pageSize: 50, ...initialValues })
    const [isFirstReturn, setIsFirstReturn] = useState<boolean>(false)

    const getUserAccountList = useAjax((params) => getUserAccountListApi(params))
    /***********************************/

    const onFinish = (data: any) => {
        let oldQueryFrom = JSON.parse(JSON.stringify(queryForm))
        let params = { ...oldQueryFrom, ...data, pageNum: 1 }
        if (params?.accountIdList) {
            params.accountIdList = params?.accountIdList.split(/[,，\n\s]+/ig).filter((item: any) => item)
        } else {
            delete params?.accountIdList
        }
        setQueryForm(params)
    }


    useEffect(() => {
        if (visible) {
            setSelectedRows(value?.map(accountId => ({ accountId })) || [])
        }
    }, [value, visible])

    useEffect(() => {
        if (visible || isReturnFirstValue) {
            let params = { ...queryForm }
            if (queryForm?.putInType) {
                params.adUnitTypeList = queryForm?.putInType === 'NOVEL' ? ['NOVEL', 'NOVEL_IAA', 'SKIT_IAA'] : ['GAME', 'GAME_IAA']
                delete queryForm.putInType
            } else {
                delete params?.adUnitTypeList
            }
            getUserAccountList.run(params).then(res => {
                if (isReturnFirstValue && !isFirstReturn) {
                    setIsFirstReturn(() => true)
                    if (res?.records?.length && !value || value?.length === 0) {
                        onChange?.(res.records[0].accountId, res.records[0])
                    }
                }
            })
        }
    }, [queryForm, visible, isFirstReturn])

    useEffect(() => {
        return () => {
            document.body.style.overflow = 'auto';
        }
    }, [])

    const handleCancel = () => {
        document.body.style.overflow = 'auto';
        setSelectedRows([])
        setVisible(false)
    }


    return <div className={style.selectAccount}>
        <div className={style.selectAccount_row} style={{ zIndex: visible ? 1000 : 1 }}>
            <Selector
                label={visible ? '选择账户' : '媒体账户'}
                style={visible ? { borderColor: '#1890ff' } : {}}
                titleStyle={visible ? { borderColor: '#1890ff', color: '#1890ff' } : {}}
            >
                <div
                    className={style.selectAccount_select}
                    onClick={() => {
                        document.body.style.overflow = 'hidden';
                        setVisible(true)
                    }}
                >
                    <div className={style.selectAccount_select_content}>
                        {(visible && selectedRows.length > 0) ? <>
                            <Tag
                                closable={type === 'checkbox'}
                                color="#F5F5F5"
                                key={selectedRows[0].accountId}
                                className={style.content_tag}
                                onClose={() => {
                                    setSelectedRows(selectedRows.slice(1))
                                }}
                            >{selectedRows[0].accountId}</Tag>
                            {selectedRows?.length > 1 && <Tooltip
                                color="#FFF"
                                title={<span style={{ color: '#000' }}>
                                    {selectedRows?.filter((_, index) => index !== 0)?.map((item) => <Tag
                                        color="#F5F5F5"
                                        className={style.content_tag}
                                        key={item.accountId}
                                        closable
                                        onClose={() => {
                                            setSelectedRows(selectedRows?.filter(item1 => item1.accountId !== item.accountId))
                                        }}
                                    >{item.accountId}</Tag>)}</span>
                                }
                            >
                                <Tag color="#F5F5F5" className={style.content_tag}>+{selectedRows.length - 1}</Tag>
                            </Tooltip>}
                        </> : (!visible && value && value?.length > 0) ? <>
                            <Tag
                                closable={type === 'checkbox'}
                                color="#F5F5F5"
                                className={style.content_tag}
                                key={value[0]}
                                onClose={() => {
                                    onChange?.(value.slice(1))
                                }}
                            >{value[0]}</Tag>
                            {value?.length > 1 && <Tooltip
                                color="#FFF"
                                title={<span style={{ color: '#000' }}>
                                    {value?.filter((_, index) => index !== 0)?.map((accountId) => <Tag
                                        className={style.content_tag}
                                        color="#F5F5F5"
                                        key={accountId}
                                        closable
                                        onClose={() => {
                                            onChange?.(value?.filter(accountId1 => accountId1 !== accountId))
                                        }}
                                    >{accountId}</Tag>)}</span>
                                }
                            >
                                <Tag color="#F5F5F5" className={style.content_tag}>+{value.length - 1}</Tag>
                            </Tooltip>}
                        </> : <Text type="secondary">请选择媒体账户</Text>}
                    </div>
                    {visible}
                    {((visible && selectedRows.length > 0) || (!visible && value && value?.length > 0)) && allowClear && <a className={style.clear} onClick={(e) => {
                        e.stopPropagation()
                        if (visible) {
                            setSelectedRows([])
                        } else {
                            onChange?.(type === 'checkbox' ? [] : undefined, type === 'checkbox' ? [] : undefined)
                        }
                    }}><CloseCircleFilled /></a>}
                </div>
            </Selector>
            {visible && <div className={style.selectAccount_list}>
                <div className={style.selectAccount_list_header}>
                    <Form
                        layout="inline"
                        className='queryForm'
                        name="basicSelectAcc"
                        form={form}
                        onFinish={onFinish}
                        initialValues={initialValues}
                    >
                        <Row gutter={[0, 6]}>
                            <Col><Form.Item name={'putInType'}>
                                <Select
                                    style={{ width: 160 }}
                                    placeholder="选择账户类型"
                                    allowClear
                                    filterOption={(input: any, option: any) => {
                                        return option!.children?.toString().toLowerCase().includes(input.toLowerCase())
                                    }}
                                >
                                    <Select.Option value='NOVEL'>小说/短剧</Select.Option>
                                    <Select.Option value='GAME'>游戏</Select.Option>
                                </Select>
                            </Form.Item></Col>
                            <Col><Form.Item name='accountIdList'>
                                <Input.TextArea
                                    rows={1}
                                    autoSize={{ minRows: 1, maxRows: 1 }}
                                    placeholder="账户(多个，,空格换行)"
                                    style={{ width: 180 }}
                                    allowClear
                                />
                            </Form.Item></Col>
                            <Col><Form.Item name='remark'>
                                <Input
                                    placeholder="备注"
                                    style={{ width: 120 }}
                                    allowClear
                                />
                            </Form.Item></Col>
                            <Col><Form.Item name='adUnitAccount'>
                                <Select
                                    style={{ width: 130 }}
                                    placeholder="是否业务单元"
                                    allowClear
                                    filterOption={(input: any, option: any) => {
                                        return option!.children?.toString().toLowerCase().includes(input.toLowerCase())
                                    }}
                                >
                                    <Select.Option value={1}>是</Select.Option>
                                    <Select.Option value={0}>否</Select.Option>
                                </Select>
                            </Form.Item></Col>
                            <Col>
                                <Space>
                                    <Button type="primary" htmlType="submit">搜索</Button>
                                    <Button onClick={() => form.resetFields()}>重置</Button>
                                </Space>
                            </Col>
                        </Row>
                    </Form>
                </div>
                <div className={style.selectAccount_list_table}>
                    <Table
                        size={'small'}
                        bordered
                        dataSource={getUserAccountList?.data?.records}
                        rowKey={'accountId'}
                        scroll={{ y: 220 }}
                        pagination={{
                            pageSize: getUserAccountList?.data?.size || 50,
                            current: getUserAccountList?.data?.current || 1,
                            showTotal: total => `总共 ${total} 账户`,
                            total: getUserAccountList?.data?.total,
                            showSizeChanger: true,
                            showLessItems: true,
                            defaultCurrent: 1,
                            defaultPageSize: 50,//默认初始的每页条数
                            onChange: (page, pageSize) => {
                                setQueryForm({ ...queryForm, pageNum: page, pageSize })
                            }
                        }}
                        loading={getUserAccountList.loading}
                        columns={[
                            {
                                title: '账号',
                                dataIndex: 'accountId',
                                key: 'accountId',
                                width: 80,
                                align: 'center',
                                render(value) {
                                    return <span style={{ fontSize: 12 }}>{value}</span>
                                }
                            },
                            {
                                title: '企业',
                                dataIndex: 'corporationName',
                                key: 'corporationName',
                                width: 160,
                                ellipsis: true,
                                render(value) {
                                    return <span style={{ fontSize: 12 }}>{value || '--'}</span>
                                }
                            },
                            {
                                title: '企业标识',
                                dataIndex: 'corporationLicence',
                                key: 'corporationLicence',
                                width: 150,
                                ellipsis: true,
                                render(value) {
                                    return <span style={{ fontSize: 12 }}>{value || '--'}</span>
                                }
                            },
                            {
                                title: '业务单元账号',
                                dataIndex: 'adUnitAccountId',
                                key: 'adUnitAccountId',
                                width: 100,
                                align: 'center',
                                render(value) {
                                    return <span style={{ fontSize: 12 }}>{value || '--'}</span>
                                }
                            },
                            {
                                title: '业务单元号?',
                                dataIndex: 'adUnitAccount',
                                key: 'adUnitAccount',
                                width: 90,
                                align: 'center',
                                render(value) {
                                    return <span style={{ fontSize: 12 }}>{value ? '是' : '否'}</span>
                                }
                            },
                            {
                                title: '备注',
                                dataIndex: 'remark',
                                key: 'remark',
                                ellipsis: true,
                                render(value) {
                                    return <span style={{ fontSize: 12 }}>{value || '--'}</span>
                                }
                            },
                        ]}
                        rowSelection={type === 'checkbox' ? {
                            selectedRowKeys: selectedRows.map(item => item.accountId),
                            type,
                            onSelect: (record: { accountId: number }, selected: boolean) => {
                                if (selected) {
                                    selectedRows.push({ ...record })
                                    setSelectedRows([...selectedRows])
                                } else {
                                    let newSelectAccData = selectedRows.filter((item: { accountId: number }) => item.accountId !== record.accountId)
                                    setSelectedRows([...newSelectAccData])
                                }
                            },
                            onSelectAll: (selected: boolean, selectedRowss: { accountId: number }[], changeRows: { accountId: number }[]) => {
                                if (selected) {
                                    let newSelectAccData = [...selectedRows]
                                    changeRows.forEach((item: { accountId: number }) => {
                                        let index = newSelectAccData.findIndex((ite: { accountId: number }) => ite.accountId === item.accountId)
                                        if (index === -1) {
                                            let data: any = { ...item }
                                            newSelectAccData.push(data)
                                        }
                                    })
                                    setSelectedRows([...newSelectAccData])
                                } else {
                                    let newSelectAccData = selectedRows.filter((item: { accountId: number }) => {
                                        let index = changeRows.findIndex((ite: { accountId: number }) => ite.accountId === item.accountId)
                                        if (index !== -1) {
                                            return false
                                        } else {
                                            return true
                                        }
                                    })
                                    setSelectedRows([...newSelectAccData])
                                }
                            }
                        } : {
                            selectedRowKeys: selectedRows.map(item => item.accountId),
                            type,
                            onChange(selectedRowKeys, selectedRows, info) {
                                setSelectedRows(selectedRows)
                            },
                        }}
                    />
                </div>
                <div className={style.selectAccount_list_footer}>
                    <Button className={style.resetCss} onClick={handleCancel}>取消</Button>
                    <Button
                        className={style.resetCss}
                        type="primary"
                        style={{ marginLeft: 8 }}
                        onClick={() => {
                            if (value?.length && arraysHaveSameValues(value, selectedRows.map(item => item.accountId))) {
                                handleCancel()
                                return
                            }
                            document.body.style.overflow = 'auto';
                            onChange?.(type === 'checkbox' ? selectedRows.map(item => item.accountId) : selectedRows?.[0]?.accountId, type === 'checkbox' ? selectedRows : selectedRows?.[0])
                            setSelectedRows([])
                            setVisible(false)
                        }}
                    >确定</Button>
                </div>
            </div>}
        </div>
        {visible && <div className={style.selectAccount_mask}></div>}
    </div>
}


export default React.memo(SelectAdAccount)