
import HocError from '@/Hoc/HocError'
import { Col, Modal, Row, Input, message, Space, Tabs, Button, Radio, Select } from 'antd'
import React, { useCallback, useEffect, useState } from 'react'
import { columnsMp } from './tableConfig'
import { useAjax } from '@/Hook/useAjax'
import { getAdAccountListApi, GetAdAccountParams, putAdAccountApi } from '@/services/launchAdq/adAuthorize'
import style from './index.less'
import TableData from '../../components/TableData'
import GroupLeft from './groupLeft'
import QQAuth from '../components/qqAuto'
import { MenuFoldOutlined, MenuUnfoldOutlined, PlusOutlined, SwapOutlined } from '@ant-design/icons'
import TeamMembers from '../../components/teamMembers'
import { getAdAccountAllOfMember, getErpUserAll, getServiceProviderAll, putConfigServiceProvider } from '@/services/launchAdq/adq'
import AddAccountToGroup from './addAccountToGroup'
import { delAccountToGroupApi } from '@/services/launchAdq/subgroup'
import { useModel } from 'umi'
import ChangeRecord from './changeRecord'
import CheckAccount from './checkAccount'
import AppointPut from './appointPut'
import SetEarlyWarningsAccount from '@/components/EarlyWarning/setEarlyWarningsAccount'

/** 投放管理 */
const AdAuthorize: React.FC = () => {
    let [visible, setVisible] = useState(false)
    let [newVisible, setNewVisible] = useState(false)
    /*************************/
    const { groupListInit } = useModel('useLaunchAdq.useAdAuthorize')
    const userInfo = useModel('@@initialState', model => model.initialState?.currentUser)
    const [queryForm, setQueryForm] = useState<GetAdAccountParams>({ pageNum: 1, pageSize: 20 })
    const [remarkData, set_remarkData] = useState<{ visible: boolean, remark: string, data: any }>({
        visible: false,
        remark: '',
        data: null
    })
    const [activeKey, setActiveKey] = useState<string>('1')
    const [showLeft, setShowLeft] = useState<boolean>(false)
    const [crShow, setCrShow] = useState<boolean>(false) // 变更记录控制
    const [crData, setCrData] = useState<{ name: number, id: number } | null>(null)
    const [checkAccShow, setCheckAccShow] = useState<boolean>(false)
    const [openServer, setOpenServer] = useState<any[]>([])//配置服务商数据
    const [serverName, setServerName] = useState<any>(null)//选择的服务商名称
    const [data, setData] = useState<{
        putResourceId?: number | undefined,
        beginTime?: string | undefined,
        gdtAccountId?: number,
        accountIds?: string,
        accountId?: string,
        gdtAccountIds?: string,
        advertiserId?: string,
        accountName?: string,
        account?: string,
        accountPassword?: string,
        quickAppAccountIds?: string
        resourceNames?: string
    } | undefined>(undefined)
    const [selectAccData, setSelectAccData] = useState<any[]>([])
    const [puShow, setPuShow] = useState<boolean>(false)
    const [puData, setPuData] = useState<any[]>([])
    const [switchType, setSwitchType] = useState<'account' | 'putUser' | 'setServer'>('account')
    const putRemark = useAjax((adAccountId: any, remark: any) => putAdAccountApi(adAccountId, remark))
    const delAccountToGroup = useAjax((params) => delAccountToGroupApi(params))
    const getAdAccountList = useAjax((params) => getAdAccountListApi(params), { formatResult: true })
    const allOfMember = useAjax(() => getAdAccountAllOfMember(), { formatResult: true })
    const erpUserALL = useAjax(() => getErpUserAll(), { formatResult: true })
    const api_getServiceProviderAll = useAjax(() => getServiceProviderAll(), { formatResult: true })
    const api_putConfigServiceProvider = useAjax((params) => putConfigServiceProvider(params), { formatResult: true })
    /*************************/

    useEffect(() => {
        groupListInit()
        !erpUserALL.data && erpUserALL.run()
        !api_getServiceProviderAll.data && api_getServiceProviderAll.run()
    }, [])

    useEffect(() => {
        getList()
    }, [queryForm])

    /** 获取账号列表 */
    const getList = () => {
        let params = JSON.parse(JSON.stringify(queryForm))
        if (params.accountIds) {
            params.accountIds = params.accountIds.split(/[\,\，]/)
        } else {
            delete params?.accountIds
        }
        getAdAccountList.run(params)
    }

    const remark = () => {
        if (remarkData.remark && remarkData.data) {
            putRemark.run(remarkData.data.accountId, remarkData.remark).then(res => {
                set_remarkData({ ...remarkData, visible: false, remark: '', data: null })
                getList()
            })
        } else {
            message.error('请输入备注！')
        }

    }
    const edit = useCallback((data) => {
        set_remarkData({ ...remarkData, visible: true, data, remark: data.remark })
    }, [remarkData])

    /** 移除分组里账号 */
    const del = (groupId: number, accountId: number) => {
        delAccountToGroup.run({ currGroupId: groupId, accountIds: [accountId] }).then(res => {
            message.success('移出成功')
            getAdAccountList.refresh()
        })
    }

    /** 切号 */
    const checkAccount = (value: any[]) => {
        let ids = value?.map((item: any) => item.id)
        setData({ resourceNames: value?.map((item: any) => item.putResourceName).toString(), accountIds: value?.map((item: any) => item.accountId).toString(), gdtAccountIds: ids.toString(), putResourceId: undefined, beginTime: undefined })
        setCheckAccShow(true);
    }

    /** 变更记录 */
    const changeRecord = (name: number, id: number) => {
        setCrData({ name, id })
        setCrShow(true)
    }

    /** 指派投手 */
    const putUserHandle = (data: any[]) => {
        setPuData(data)
        setPuShow(true)
    }
    // 批量配置服务商
    const setServiceProviderName = (accountIds: any) => {
        api_putConfigServiceProvider.run({ accountIds, serviceProviderName: serverName.label }).then(res => {
            if (res.data) {
                message.success("配置成功！")
                setOpenServer([]);
                setServerName(null)
                getAdAccountList.refresh()
            } else {
                message.error("配置失败！")
            }
        })
    }


    return <div style={{ height: '100%' }}>
        <Tabs
            tabBarStyle={{ marginBottom: 1 }}
            activeKey={activeKey}
            type="card"
            // tabBarExtraContent={<Button type='primary' onClick={()=>setVisible(true)}><PlusOutlined />广告账号授权</Button>}
            onChange={(activeKey) => {
                if (activeKey !== 'contract') {
                    let newQueryForm = JSON.parse(JSON.stringify(queryForm))
                    delete newQueryForm?.groupId
                    delete newQueryForm?.putUserId
                    setQueryForm(newQueryForm)
                    setActiveKey(activeKey)
                } else {
                    setShowLeft(!showLeft)
                }
            }}
        >
            <Tabs.TabPane tab='我的' key='1' />
            <Tabs.TabPane tab='组员' key='2' />
            <Tabs.TabPane tab={showLeft ? <MenuUnfoldOutlined /> : <MenuFoldOutlined />} key='contract' />
        </Tabs>

        <div className={style.manage}>
            {!showLeft && activeKey === '1' && <GroupLeft onChange={(groupId) => setQueryForm({ ...queryForm, groupId, pageNum: 1 })} value={queryForm?.groupId} />}
            {!showLeft && activeKey === '2' && <TeamMembers allOfMember={allOfMember} onChange={(putUserId) => setQueryForm({ ...queryForm, putUserId, pageNum: 1 })} value={queryForm?.putUserId} />}

            <div className={style.manage__left} style={showLeft ? { width: '100%' } : { width: 'calc(100% - 200px)' }}>
                <TableData
                    ajax={getAdAccountList}
                    dataSource={getAdAccountList?.data?.data?.records}
                    loading={getAdAccountList?.loading}
                    columns={() => columnsMp(edit, setOpenServer, del, checkAccount, changeRecord, putUserHandle, () => getAdAccountList.refresh(), activeKey, userInfo?.userId?.toString(), queryForm?.groupId, getAdAccountList)}
                    total={getAdAccountList?.data?.data?.total}
                    page={getAdAccountList?.data?.data?.current}
                    pageSize={getAdAccountList?.data?.data?.size}
                    size="small"
                    scroll={{ y: 600 }}
                    leftChild={<Space wrap>
                        <Select
                            style={{ width: 120 }}
                            placeholder="选择操作类型"
                            onChange={(e) => {
                                setSwitchType(e);
                                setSelectAccData([])
                            }}
                            value={switchType}
                            dropdownMatchSelectWidth={false}
                            options={[{ label: '批量切号', value: 'account' }, { label: '批量指派投放助理', value: 'putUser' }, { label: '批量配置服务商', value: 'setServer' }]}
                        />
                        <Input.TextArea
                            placeholder="多个广告账号以，隔开(id1,id2)"
                            allowClear
                            style={{ minWidth: 200 }}
                            value={queryForm?.accountIds}
                            rows={1}
                            onChange={(e) => {
                                setQueryForm({ ...queryForm, accountIds: e.target.value.replaceAll(/\s/ig, '') })
                            }}
                        />
                        <Select
                            style={{ width: 120 }}
                            placeholder="是3.0账号?"
                            allowClear
                            onChange={(e) => {
                                setQueryForm({ ...queryForm, addV3: e })
                            }}
                            value={queryForm?.addV3}
                            options={[{ label: '是', value: true }, { label: '否', value: false }]}
                        />
                        <Select
                            style={{ width: 120 }}
                            placeholder="是业务单元?"
                            allowClear
                            onChange={(e) => {
                                setQueryForm({ ...queryForm, adUnitAccount: e })
                            }}
                            value={queryForm?.adUnitAccount}
                            options={[{ label: '是', value: true }, { label: '否', value: false }]}
                        />
                        <Button onClick={getList} type='primary' loading={getAdAccountList.loading}>搜索</Button>
                        <AddAccountToGroup onChange={() => getAdAccountList.refresh()} />
                        <Button type='primary' onClick={() => setVisible(true)}><PlusOutlined />广告账号授权</Button>
                        <Button type='primary' onClick={() => setNewVisible(true)}><PlusOutlined />广告业务单元批量授权</Button>
                        {switchType === 'account' ?
                            (selectAccData?.length > 0 && <>
                                <Button type="primary" ghost icon={<SwapOutlined />} onClick={() => { checkAccount(selectAccData) }}>批量切号</Button>
                                <SetEarlyWarningsAccount onChange={() => { setSelectAccData([]); }} accountIds={selectAccData.map(item => item.accountId)?.toString()} />
                            </>) :
                            switchType === 'putUser' ? (selectAccData?.length > 0 && <Button type="primary" ghost icon={<SwapOutlined />} onClick={() => { putUserHandle(selectAccData) }}>批量指派投放助理</Button>) :
                                selectAccData?.length > 0 && <Button type="primary" ghost icon={<SwapOutlined />} onClick={() => { setOpenServer(selectAccData) }}>批量配置服务商</Button>
                        }
                    </Space>}
                    rowSelection={{
                        selectedRowKeys: selectAccData?.map((item: any) => item.id?.toString()),
                        getCheckboxProps: (record: any) => ({
                            disabled: switchType === 'putUser' ? activeKey === '2' || userInfo?.userId !== record?.putUserInfo?.userId : false
                        }),
                        onSelect: (record: { id: number, mpName: string }, selected: boolean) => {
                            if (selected) {
                                selectAccData.push({ ...record })
                                setSelectAccData([...selectAccData])
                            } else {
                                let newSelectAccData = selectAccData.filter((item: { id: number }) => item.id !== record.id)
                                setSelectAccData([...newSelectAccData])
                            }
                        },
                        onSelectAll: (selected: boolean, selectedRows: { id: number }[], changeRows: { id: number }[]) => {
                            if (selected) {
                                let newSelectAccData = [...selectAccData]
                                changeRows.forEach((item: { id: number }) => {
                                    let index = newSelectAccData.findIndex((ite: { id: number }) => ite.id === item.id)
                                    if (index === -1) {
                                        newSelectAccData.push({ ...item })
                                    }
                                })
                                setSelectAccData([...newSelectAccData])
                            } else {
                                let newSelectAccData = selectAccData.filter((item: { id: number }) => {
                                    let index = changeRows.findIndex((ite: { id: number }) => ite.id === item.id)
                                    if (index !== -1) {
                                        return false
                                    } else {
                                        return true
                                    }
                                })
                                setSelectAccData([...newSelectAccData])
                            }
                        }
                    }}
                    onChange={(props: any) => {
                        let { pagination } = props
                        let { current, pageSize } = pagination
                        setQueryForm({ ...queryForm, pageNum: current, pageSize })
                    }}
                />
            </div>
        </div>
        {/* 批量设置服务商 */}
        {openServer.length > 0 && <Modal
            title="配置服务商"
            onOk={() => setServiceProviderName(openServer?.map(item => item.accountId))}
            onCancel={() => { setOpenServer([]); setServerName(null) }}
            visible={openServer.length > 0}
            confirmLoading={api_putConfigServiceProvider.loading}
        >
            <Row gutter={[20, 20]}>
                <Col span={24}>
                    <Row>
                        <Col span={3}><b>广告主：</b></Col>
                        <Col span={21}>
                            {openServer.map((item, index) => {
                                return index === openServer.length - 1 ? item.accountId : item.accountId + ','
                            })}
                        </Col>
                    </Row>
                </Col>
                <Col span={24}>
                    <Row>
                        <Col span={3}><b>服务商：</b></Col>
                        <Col span={21}>
                            <Select
                                style={{ minWidth: 200 }}
                                showSearch
                                allowClear
                                placeholder="请选择服务商"
                                optionFilterProp="children"
                                onChange={(value: any, option: any) => {
                                    setServerName(option)
                                }}
                                filterOption={(input, option: any) =>
                                    (option?.label ?? '').toLowerCase().includes(input.toLowerCase())
                                }
                                value={serverName}
                                options={api_getServiceProviderAll?.data?.data?.map((item: { id: any, serviceProviderName: any }) => {
                                    return { value: item.id, label: item.serviceProviderName }
                                })}
                            />
                        </Col>
                    </Row>
                </Col>
            </Row>

        </Modal>}
        {/* 广告授权 */}
        {visible && <QQAuth qqVisible={visible} callBack={() => setVisible(false)} adAppType={0} title='小说广告账号授权' isOld={true}/>}
        {/* 广告业务单元批量授权 */}
        {newVisible && <QQAuth qqVisible={newVisible} callBack={() => setNewVisible(false)} adAppType={0} smType={"WX"}  title='小说广告业务单元批量授权'/>}
        {/* 变更记录 */}
        {crShow && <ChangeRecord visible={crShow} data={crData} onClose={() => { setCrShow(false); setCrData(null) }} />}
        {/* 切号 */}
        {checkAccShow && <CheckAccount value={data} visible={checkAccShow} onChange={() => { getList(); setCheckAccShow(false); setSelectAccData([]) }} onClose={() => { setCheckAccShow(false) }} />}
        {/* 指派 */}
        {puShow && <AppointPut value={puData} visible={puShow} onClose={() => { setPuShow(false) }} allOfMember={erpUserALL} onChange={() => { setPuShow(false); getAdAccountList.refresh(); setSelectAccData([]) }} />}

        {remarkData.visible && <Modal
            visible={remarkData.visible}
            title='编辑账户'
            onCancel={() => { set_remarkData({ ...remarkData, visible: false, data: null }) }}
            onOk={remark}
            confirmLoading={putRemark.loading}
        >
            <Row gutter={[20, 20]}>
                <Col span={24} className={style.boxCol}><strong>广告主ID：</strong><span>{remarkData?.data.accountId}</span></Col>
                <Col span={24} className={style.boxCol}><strong>类型：</strong><span>{remarkData?.data.sourceType === 0 ? '微信' : 'QQ'}</span></Col>
                <Col span={24} className={style.boxCol}><strong>公众号信息：</strong><span>{remarkData?.data.wechatAccountName || '无'}</span></Col>
                <Col span={24} className={style.boxCol}><strong>企业名称：</strong><span>{remarkData?.data.corporationName || '无'}</span></Col>
                <Col span={24} className={style.boxCol}><strong>服务商ID列表：</strong><span>{remarkData?.data.agencyIdList ? remarkData.data.agencyIdList?.join() : '无'}</span></Col>
                <Col span={24} className={style.boxCol}><strong>行业ID：</strong><span>{remarkData?.data.systemIndustryId || '无'}</span></Col>
                <Col span={24} className={style.boxCol}><strong>授权状态：</strong><span>{remarkData?.data.authStatus || '无'}</span></Col>
                <Col span={24} className={style.boxCol}><strong>日限额(分)：</strong><span>{remarkData?.data.dailyBudget || '无'}</span></Col>
                <Col span={24} className={style.boxCol}><strong>授权时间：</strong><span>{remarkData?.data.createTime || '无'}</span></Col>
                <Col span={24} className={style.boxCol}><strong>备注：</strong><span><Input.TextArea rows={5} maxLength={200} value={remarkData.remark} onChange={(e) => {
                    let value = e.target.value
                    set_remarkData({ ...remarkData, remark: value })
                }} /></span></Col>
            </Row>
        </Modal>}
    </div>
}

export default HocError(AdAuthorize)