import { useAjax } from "@/Hook/useAjax"
import { setMaterialTencentApi } from "@/services/adqV3/cloudNew"
import { getAccountAssetsGroupListAllApi } from "@/services/adqV3/global"
import { getUserAccountListApi } from "@/services/launchAdq/adAuthorize"
import { getGroupListApi } from "@/services/launchAdq/subgroup"
import { Button, Col, Form, Input, message, Modal, Row, Select, Space, Table } from "antd"
import React, { useEffect, useState } from "react"



interface Props {
    data: any[]
    visible?: boolean
    onClose?: () => void
    onChange?: () => void
}

/**
 * 上传素材到腾讯
 * @param param0 
 * @returns 
 */
const MoveToTencent: React.FC<Props> = ({ data, visible, onClose, onChange }) => {

    /***********************************/
    const [form] = Form.useForm()
    const [queryForm, setQueryForm] = useState<{ putInType?: string, accountIdList?: number[], adUnitTypeList?: string[], groupId?: number, remark?: string, sysGroupId?: number, pageNum: number, pageSize: number }>({ pageNum: 1, pageSize: 50 })
    const [selectedRows, setSelectedRows] = useState<any[]>([])
    const [loading, setLoading] = useState<boolean>(false)

    const getUserAccountList = useAjax((params) => getUserAccountListApi(params))
    const getGroupList = useAjax(() => getGroupListApi())
    const getAccountAssetsGroupListAll = useAjax((params) => getAccountAssetsGroupListAllApi(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(() => {
        getGroupList.run()
    }, [])

    useEffect(() => {
        const { putInType, ...params } = queryForm
        getUserAccountList.run({ ...params, adUnitTypeList: putInType === 'NOVEL' ? ['NOVEL', 'NOVEL_IAA', 'SKIT_IAA'] : putInType === 'GAME' ? ['GAME', 'GAME_IAA'] : undefined })
    }, [queryForm])

    const handleOk = () => {
        console.log(data)
        if (selectedRows.length) {
            const typeDatalist = data.reduce((pre, cur) => {
                if (cur.materialType === 'image') {
                    pre['image']?.length ? pre['image'].push(cur.id) : pre['image'] = [cur.id]
                } else if (cur.materialType === 'video') {
                    pre['video']?.length ? pre['video'].push(cur.id) : pre['video'] = [cur.id]
                }
                return pre
            }, {})
            setLoading(true)
            const ajaxs = Object.keys(typeDatalist).map(key => {
                if (key == 'image') {
                    return setMaterialTencentApi({ type: 'IMAGE', accountId: selectedRows[0].accountId, sysFileId: typeDatalist[key] })
                } else {
                    return setMaterialTencentApi({ type: 'VIDEO', accountId: selectedRows[0].accountId, sysFileId: typeDatalist[key] })
                }
            })
            Promise.all(ajaxs).then(res => {
                setLoading(false)
                console.log('66666666', res)
                message.success('任务提交成功，结果可以到腾讯查看')
            }).catch(() => setLoading(false))
            console.log(typeDatalist)
        } else {
            message.error('请选择账号')
        }
    }

    return <Modal
        title={<strong>素材上传至腾讯</strong>}
        open={visible}
        onCancel={onClose}
        onOk={handleOk}
        className="modalResetCss"
        maskClosable={false}
        confirmLoading={loading}
        width={1000}
    >
        <Space direction="vertical" style={{ width: '100%' }}>
            <Form layout="inline" className='queryForm' name="basicSelectAcc" form={form} onFinish={onFinish}>
                <Row gutter={[0, 6]}>
                    <Col><Form.Item name='putInType'>
                        <Select
                            style={{ width: 120 }}
                            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='sysGroupId'>
                        <Select
                            mode="multiple"
                            style={{ minWidth: 180 }}
                            placeholder="快捷选择媒体账户组"
                            maxTagCount={1}
                            allowClear
                            filterOption={(input: any, option: any) => {
                                return option!.children?.toString().toLowerCase().includes(input.toLowerCase())
                            }}
                        >
                            {getGroupList?.data && getGroupList?.data?.map((item: any) => <Select.Option value={item.groupId} key={item.groupId}>{item.groupName}</Select.Option>)}
                        </Select>
                    </Form.Item></Col>
                    <Col><Form.Item name='groupId'>
                        <Select
                            allowClear
                            showSearch
                            placeholder="账户资产共享组"
                            filterOption={(input: any, option: any) => {
                                return option!.children?.toString().toLowerCase().includes(input.toLowerCase())
                            }}
                            style={{ width: 145 }}
                        >
                            {getAccountAssetsGroupListAll?.data?.map((item: { accountId: any; authMainAccountId: number; id: number; accountGroupName: string }) => <Select.Option value={item.id} key={item.id}>{item.accountGroupName}({item.authMainAccountId})</Select.Option>)}
                        </Select>
                    </Form.Item></Col>
                    <Col>
                        <Space>
                            <Button type="primary" htmlType="submit">搜索</Button>
                            <Button onClick={() => form.resetFields()}>重置</Button>
                        </Space>
                    </Col>
                </Row>
            </Form>

            <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: 180,
                        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: '业务单元ID',
                        dataIndex: 'adUnitAccountId',
                        key: 'adUnitAccountId',
                        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={{
                    selectedRowKeys: selectedRows.map(item => item.accountId),
                    type: 'radio',
                    onChange(_, selectedRows) {
                        setSelectedRows(selectedRows)
                    },
                }}
            />
        </Space>
    </Modal>
}

export default React.memo(MoveToTencent)