
import HocError from '@/Hoc/HocError'
import { Col, Modal, Row, Input, message, Space, Tabs, Button, Radio } 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 './qqAuto'
import { MenuFoldOutlined, MenuUnfoldOutlined, PlusOutlined, SwapOutlined } from '@ant-design/icons'
import TeamMembers from '../components/teamMembers'
import { getAdAccountAllOfMember, getErpUserAll } 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'

/** 投放管理 */
const AdAuthorize: React.FC = () => {
    let [visible, setVisible] = 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 [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'>('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 })
    /*************************/

    useEffect(() => {
        groupListInit()
        !erpUserALL.data  && erpUserALL.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.id, 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)
    }

    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, del, checkAccount, changeRecord, putUserHandle, 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>
                        <Radio.Group value={switchType} onChange={(e) => { setSwitchType(e.target.value); setSelectAccData([]) }}>
                            <Radio.Button value="account">批量切号</Radio.Button>
                            <Radio.Button value="putUser">批量指派投放助理</Radio.Button>
                        </Radio.Group>
                        <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,'') })
                            }}
                        />
                        <Button onClick={getList} type='primary' loading={getAdAccountList.loading}>搜索</Button>
                        <AddAccountToGroup onChange={() => getAdAccountList.refresh()} />
                        <Button type='primary' onClick={() => setVisible(true)}><PlusOutlined />广告账号授权</Button>
                        {switchType === 'account' ?
                            (selectAccData?.length > 0 && <Button type="primary" ghost icon={<SwapOutlined />} onClick={() => { checkAccount(selectAccData) }}>批量切号</Button>) :
                            (selectAccData?.length > 0 && <Button type="primary" ghost icon={<SwapOutlined />} onClick={() => { putUserHandle(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>
        {/* 广告授权 */}
        {visible && <QQAuth qqVisible={visible} callBack={() => setVisible(false)} />}
        {/* 变更记录 */}
        {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)