import { useAjax } from "@/Hook/useAjax"
import { getAllOfOwnerUserApi, getChannelChoiceListApi, getGameListNewApi, getTtAllUserListApi } from "@/services/gameData"
import { GetPolicyConfigProps, configEnableApi, configHandleApi, delConfigRuleApi, getPolicyConfigListApi } from "@/services/gameData/adlist"
import { PlusOutlined } from "@ant-design/icons"
import { Button, Card, Col, Form, Input, Popconfirm, Row, Select, Space, message } from "antd"
import React, { useEffect, useState } from "react"
import ConfigModal from "./configModal"
import Tables from "@/components/Tables"
import style from '../../components/TableData/index.less'
import columnsPos from "./tableConfig"
import WhiteList from "./whiteList"


const Strategy: React.FC = () => {

    /******************************/
    const [form] = Form.useForm()
    const [initialValues, setInitialValues] = useState<any>({})
    const [initialValuesS, setInitialValuesS] = useState<any[]>([])
    const [queryFrom, setQueryForm] = useState<GetPolicyConfigProps>({ pageNum: 1, pageSize: 20 })
    const [gameList, setGameList] = useState<{ id: number, game_name: string }[]>([])
    const [visible, setVisible] = useState<boolean>(false)
    const [accountList, setAccountList] = useState<any[]>([])
    const [whiteVisible, setWhiteVisible] = useState<boolean>(false)
    const [selectedRows, setSelectedRows] = useState<any[]>([])

    const getGameList = useAjax((params) => getGameListNewApi(params))
    const getPolicyConfigList = useAjax((params) => getPolicyConfigListApi(params))
    const delConfigRule = useAjax((params) => delConfigRuleApi(params))
    const configHandle = useAjax((params) => configHandleApi(params))
    const configEnable = useAjax((params) => configEnableApi(params))
    const getChannelChoiceList = useAjax(() => getChannelChoiceListApi()) // 渠道
    const getAllOfOwnerUser = useAjax(() => getAllOfOwnerUserApi()) // 账号
    const getTtAllUserList = useAjax(() => getTtAllUserListApi()) // 账号
    /******************************/

    useEffect(() => {
        getPolicyConfigList.run(queryFrom)
    }, [queryFrom])

    const onFinish = (data: any) => {
        let oldQueryFrom = JSON.parse(JSON.stringify(queryFrom))
        setQueryForm({ ...oldQueryFrom, ...data, pageNum: 1 })
    }

    useEffect(() => {
        getChannelChoiceList.run()
        async function getAccount() {
            let data: any[] = []
            let res1 = await getAllOfOwnerUser.run()
            let data1 = []
            if (res1) {
                data1 = res1?.map((item: any) => ({ label: item.accountId, value: item.accountId, corporationName: item.corporationName }))
            }
            let res2 = await getTtAllUserList.run()
            let data2 = []
            if (res2) {
                data2 = res2?.map((item: any) => ({ label: item.accountId, value: item.accountId, corporationName: item.accountName }))
            }
            data = [...data1, ...data2]
            setAccountList(data)
        }
        getAccount()
    }, [])

    useEffect(() => {
        getGameList.run({ sourceSystem: 'ZX_ONE' }).then(res => {
            if (res) {
                const { gameList } = res
                setGameList(gameList)
            }
        })
    }, [])

    const edit = (value: any, isCopy?: boolean) => {
        let data = JSON.parse(JSON.stringify(value))
        if (isCopy) {
            delete data?.id
            data.ruleName = data.ruleName + '_Copy'
        }
        setInitialValues(data)
        setVisible(true)
    }

    const del = (value: string) => {
        delConfigRule.run(value).then(res => {
            if (res) {
                message.success('删除成功')
                getPolicyConfigList.refresh()
            }
        })
    }

    const handle = (value: any[], type: string) => {
        switch (type) {
            case 'zt': case 'qd':
                configEnable.run({ ids: value.map(item => item.id), isStart: type === 'zt' ? false : true }).then(res => {
                    if (res) {
                        message.success(type === 'zt' ? '暂停成功' : '启用成功')
                        getPolicyConfigList.refresh()
                        setSelectedRows([])
                    }
                })
                break
            case 'bmd':
                setInitialValuesS(value)
                setWhiteVisible(true)
                break
        }
    }

    return <Card
        style={{ borderRadius: 8 }}
        headStyle={{ textAlign: 'left' }}
        bodyStyle={{ padding: '5px 10px' }}
    >
        <div style={{ textAlign: 'center', fontWeight: 'bold', padding: '4px 6px 6px', fontSize: 16, marginBottom: 4, position: 'relative' }}>
            游戏广告策略
        </div>
        <Space style={{ width: '100%' }} direction="vertical" size={10}>
            <Form layout="inline" className='queryForm' initialValues={initialValues} name="basicStrategy" form={form} onFinish={onFinish}>
                <Row gutter={[0, 6]}>
                    <Col><Form.Item name='isStart'>
                        <Select
                            style={{ minWidth: 140 }}
                            allowClear
                            placeholder={'请选择启用状态'}
                            filterOption={(input, option) =>
                                (option?.children as any)?.toLowerCase().indexOf(input.toLowerCase()) >= 0
                            }
                        >
                            <Select.Option value={false}>未启用</Select.Option>
                            <Select.Option value={true}>已启用</Select.Option>
                        </Select>
                    </Form.Item></Col>
                    <Col><Form.Item name='gameId'>
                        <Select
                            maxTagCount={1}
                            showSearch
                            style={{ minWidth: 140 }}
                            allowClear
                            placeholder={'请选择游戏'}
                            filterOption={(input, option) =>
                                (option?.children as any)?.toLowerCase().indexOf(input.toLowerCase()) >= 0
                            }
                        >
                            {gameList?.map((item: any) => <Select.Option value={item.id} key={item.id}>{item.game_name}</Select.Option>)}
                        </Select>
                    </Form.Item></Col>
                    <Col><Form.Item name='mediaType'>
                        <Select
                            style={{ minWidth: 140 }}
                            allowClear
                            placeholder={'请选择媒体类型'}
                            filterOption={(input, option) =>
                                (option?.children as any)?.toLowerCase().indexOf(input.toLowerCase()) >= 0
                            }
                        >
                            <Select.Option value={1}>腾讯</Select.Option>
                            <Select.Option value={2}>头条</Select.Option>
                        </Select>
                    </Form.Item></Col>
                    <Col><Form.Item name='ruleName'>
                        <Input placeholder="规则名称" />
                    </Form.Item></Col>
                    <Col>
                        <Space>
                            <Button type="primary" htmlType="submit">搜索</Button>
                            <Button onClick={() => form.resetFields()}>重置</Button>
                            <Button icon={<PlusOutlined />} type="primary" onClick={() => { setVisible(true); setInitialValues({}) }}>添加规则条件</Button>
                        </Space>
                    </Col>
                </Row>
            </Form>

            <Space>
                <Button type="primary" loading={configEnable.loading} disabled={selectedRows?.length === 0} onClick={() => handle(selectedRows, 'qd')}>批量启用</Button>
                <Button loading={configEnable.loading} disabled={selectedRows?.length === 0} onClick={() => handle(selectedRows, 'zt')}>批量暂停</Button>
                <Button type="primary" disabled={selectedRows?.length === 0} onClick={() => handle(selectedRows, 'bmd')}>批量添加白名单</Button>
                <Popconfirm
                    title="确定删除?"
                    onConfirm={() => { del(selectedRows.map(item => item.id).toString()) }}
                >
                    <Button type="primary" loading={delConfigRule.loading} disabled={selectedRows?.length === 0} danger>批量删除</Button>
                </Popconfirm>
            </Space>

            <div className={`${style['small']}`}>
                <Tables
                    className={`all_table content_table_body`}
                    bordered
                    sortDirections={['ascend', 'descend', null]}
                    current={queryFrom.pageNum}
                    pageSize={queryFrom.pageSize}
                    columns={columnsPos(accountList, getChannelChoiceList, edit, del, handle)}
                    dataSource={getPolicyConfigList?.data?.records}
                    scroll={{ x: 1000, y: 600 }}
                    onChange={(pagination: any, filters: any, sortData: any) => {
                        let { current, pageSize } = pagination
                        let newQueryForm = JSON.parse(JSON.stringify(queryFrom))
                        if (sortData && sortData?.order) {
                            newQueryForm['sortType'] = sortData?.order === 'ascend' ? 'asc' : 'desc'
                            newQueryForm['sortFiled'] = sortData?.field
                        } else {
                            delete newQueryForm['sortType']
                            delete newQueryForm['sortFiled']
                        }
                        newQueryForm.pageNum = current
                        newQueryForm.pageSize = pageSize
                        setQueryForm({ ...newQueryForm })
                    }}
                    size="small"
                    total={getPolicyConfigList?.data?.total}
                    loading={getPolicyConfigList?.loading}
                    defaultPageSize={20}
                    rowSelection={{
                        selectedRowKeys: selectedRows.map(item => item.id + ''),
                        onSelect: (record: { id: number }, selected: boolean) => {
                            if (selected) {
                                selectedRows.push({ ...record })
                                setSelectedRows([...selectedRows])
                            } else {
                                let newSelectAccData = selectedRows.filter((item: { id: number }) => item.id !== record.id)
                                setSelectedRows([...newSelectAccData])
                            }
                        },
                        onSelectAll: (selected: boolean, selectedRowss: { id: number }[], changeRows: { id: number }[]) => {
                            if (selected) {
                                let newSelectAccData = [...selectedRows]
                                changeRows.forEach((item: { id: number }) => {
                                    let index = newSelectAccData.findIndex((ite: { id: number }) => ite.id === item.id)
                                    if (index === -1) {
                                        newSelectAccData.push({ ...item })
                                    }
                                })
                                setSelectedRows([...newSelectAccData])
                            } else {
                                let newSelectAccData = selectedRows.filter((item: { id: number }) => {
                                    let index = changeRows.findIndex((ite: { id: number }) => ite.id === item.id)
                                    if (index !== -1) {
                                        return false
                                    } else {
                                        return true
                                    }
                                })
                                setSelectedRows([...newSelectAccData])
                            }
                        }
                    }}
                />
            </div>
        </Space>


        {visible && <ConfigModal
            visible={visible}
            onClose={() => setVisible(false)}
            accountList={accountList}
            getChannelChoiceList={getChannelChoiceList}
            accountLoading={getChannelChoiceList.loading || getAllOfOwnerUser.loading || getTtAllUserList.loading}
            gameList={gameList}
            initialValues={initialValues}
            onChange={() => {
                setVisible(false)
                getPolicyConfigList.refresh()
            }}
        />}

        {/* 白名单 */}
        {whiteVisible && <WhiteList
            visible={whiteVisible}
            onClose={() => setWhiteVisible(false)}
            onChange={() => {
                setWhiteVisible(false)
                getPolicyConfigList.refresh()
            }}
            initialValues={initialValuesS}
        />}
    </Card>
}

export default Strategy