import { App, Button, DatePicker, Input, Pagination, Popconfirm, Select, Table } from 'antd';
import Card from 'antd/es/card/Card';
import React, { useEffect, useRef, useState } from 'react';
import { delAutoLinkApi, getCorpAutoLinkListApi, GetCorpAutoLinkListProps } from '../../API/bookLink';
import style from './index.less'
import { useAjax } from '@/Hook/useAjax';
import SearchBox from '../../components/searchBox';
import { SearchOutlined, PlusOutlined, DeleteOutlined } from '@ant-design/icons';
import { getBindMpListApi } from '../../API/corpUserAssign';
import { inject, observer } from 'mobx-react';
import { toJS } from 'mobx';
import { LINKTYPE } from './const';
import ModalBookLink from './modalBooklink';
import { useSize } from 'ahooks';
import { bookLinkTableConfig } from './tableConfig';
import dayJs from 'dayjs';
import '../groupLeaderManage/global.less'

/**
 * 书城自动链接管理
 * @returns 
 */
const BookLink: React.FC<{ weComTaskStore: { data: { bookList: TASK_CREATE.BookListProps[], bookPlatForm: TASK_CREATE.BookPlatFormProps[] } } }> = ({ weComTaskStore }) => {

    /******************************************/
    const { message } = App.useApp()
    const { bookPlatForm } = toJS(weComTaskStore.data)
    const ref = useRef<HTMLDivElement>(null)
    const size = useSize(ref)

    const [queryParams, setQueryParams] = useState<GetCorpAutoLinkListProps>({ pageNum: 1, pageSize: 20 })
    const [queryParamsNew, setQueryParamsNew] = useState<GetCorpAutoLinkListProps>({ pageNum: 1, pageSize: 20 })
    const [mpList, setMplist] = useState<{ label: string, value: number }[]>([])
    const [visible, setVisible] = useState<boolean>(false)
    const [initialValues, setInitialValues] = useState<any>()
    const [selectedRows, setselectedRows] = useState<any[]>([])

    const getCorpAutoLinkList = useAjax((params) => getCorpAutoLinkListApi(params))
    const delAutoLink = useAjax((params) => delAutoLinkApi(params))
    const getBindMpList = useAjax(() => getBindMpListApi())
    /******************************************/

    useEffect(() => {
        getCorpAutoLinkList.run(queryParamsNew)
    }, [queryParamsNew])

    useEffect(() => {
        getBindMpList.run().then(res => {
            setMplist(res?.data?.map((item: any) => ({ label: item.name, value: item.id })))
        })
    }, [])

    const handleCopy = (value: any) => {
        const { linkType, linkContext, channelName, channelType, platform, mpAccountId } = value
        if (platform === 'YUE_WEN') {  // 阅文
            const yueWenCreateLinkDTO: { [x: string]: any } = {
                linkType: linkType + '',
                channelName,
                channelType: channelType + ''
            }
            switch (linkType) {
                case 1:
                    yueWenCreateLinkDTO.pagePromoLinkCreateDTO = {
                        ...linkContext,
                        pageType: linkContext.pageType + ''
                    }
                    break
                case 2:
                    yueWenCreateLinkDTO.bookPromoLinkCreateDTO = { ...linkContext, forceStyle: Number(linkContext.forceStyle) }
                    break
                case 3:
                    yueWenCreateLinkDTO.rechargeActivityLinkDTO = {
                        ...linkContext,
                        activityTheme: linkContext.activityTheme + '',
                        activityTime: [dayJs(linkContext.startTime), dayJs(linkContext.endTime)],
                        display: linkContext?.display ? linkContext?.display?.split(',') : []
                    }
                    break
                case 4:
                    yueWenCreateLinkDTO.giftActivityLinkDTO = {
                        ...linkContext,
                        // activityTheme: Number(linkContext.activityTheme), 
                        activityTime: [dayJs(linkContext.startTime), dayJs(linkContext.endTime)],
                        display: linkContext?.display ? linkContext?.display?.split(',') : [],
                        resourceType: linkContext.resourceType + ''
                    }
                    break
                case 5:
                    yueWenCreateLinkDTO.consumeActivityLinkDTO = {
                        ...linkContext,
                        activityTheme: linkContext.activityTheme + '',
                        activityTime: [dayJs(linkContext.startTime), dayJs(linkContext.endTime)],
                        display: linkContext?.display ? linkContext?.display?.split(',') : [],
                    }
                    break
            }
            setInitialValues({
                platform,
                mpAccountIds: [mpAccountId],
                yueWenCreateLinkDTOList: [yueWenCreateLinkDTO]
            })
        } else if (platform === 'FAN_QIE') { // 番茄
            const fanQieCreateLinkDTO: { [x: string]: any } = {
                linkType: linkType + '',
                channelName
            }
            switch (linkType) {
                case 1:
                    fanQieCreateLinkDTO.pagePromoLinkCreateDTO = {
                        ...linkContext,
                        pageType: linkContext.pageType + ''
                    }
                    break
                case 2:
                    fanQieCreateLinkDTO.bookPromoLinkCreateDTO = { ...linkContext }
                    break
                case 3:
                    fanQieCreateLinkDTO.rechargeActivityLinkDTO = {
                        ...linkContext,
                        activityTime: [dayJs(linkContext.startTime), dayJs(linkContext.endTime)]
                    }
                    break
                case 4:
                    fanQieCreateLinkDTO.giftActivityLinkDTO = {
                        ...linkContext,
                        activityTime: [dayJs(linkContext.startTime), dayJs(linkContext.endTime)]
                    }
                    break
                case 5:
                    fanQieCreateLinkDTO.consumeActivityLinkDTO = {
                        ...linkContext,
                        activityTime: [dayJs(linkContext.startTime), dayJs(linkContext.endTime)],
                    }
                    break
            }
            setInitialValues({
                platform,
                mpAccountIds: [mpAccountId],
                fanQieCreateLinkDTOList: [fanQieCreateLinkDTO]
            })
        } else if (platform === 'HUA_SHENG') { // 花生
            const huaShengCreateLinkDTO: { [x: string]: any } = {
                linkType: linkType + '',
                channelName,
                channelType: channelType + ''
            }

            switch (linkType) {
                case 1:
                    huaShengCreateLinkDTO.bookPromoLinkCreateDTO = { ...linkContext }
                    break;
                case 2:
                    const [rechargeAmount, giftAmount] = linkContext.productName.split('-')
                    huaShengCreateLinkDTO.rechargeActivityLinkDTO = {
                        ...linkContext,
                        activityTime: [dayJs(linkContext.startTime), dayJs(linkContext.endTime)],
                        display: linkContext?.display ? linkContext?.display?.split(',') : [],
                        rechargeAmount,
                        giftAmount
                    }
                    break;
                case 3:
                    huaShengCreateLinkDTO.giftActivityLinkDTO = {
                        ...linkContext,
                        activityTime: [dayJs(linkContext.startTime), dayJs(linkContext.endTime)],
                        display: linkContext?.display ? linkContext?.display?.split(',') : []
                    }
                    break
            }
            setInitialValues({
                platform,
                mpAccountIds: [mpAccountId],
                huaShengCreateLinkDTOList: [huaShengCreateLinkDTO]
            })
        } else if (platform === 'WEN_DING') { // 文鼎
            const wenDingCreateLinkDTO: { [x: string]: any } = {
                linkType: linkType + '',
                channelName,
                channelType: channelType
            }

            switch (linkType) {
                case 1:
                    wenDingCreateLinkDTO.bookPromoLinkCreateDTO = { ...linkContext, linkClassify: linkContext.linkClassify + '' }
                    break;
                case 2:
                    wenDingCreateLinkDTO.rechargeActivityLinkDTO = {
                        ...linkContext,
                        activityTime: [dayJs(linkContext.startTime), dayJs(linkContext.endTime)],
                    }
                    break;
            }
            console.log('wenDingCreateLinkDTO--->', wenDingCreateLinkDTO)
            setInitialValues({
                platform,
                mpAccountIds: [mpAccountId],
                wenDingCreateLinkDTOList: [wenDingCreateLinkDTO]
            })
        }

        setVisible(true)
    }

    const handleDel = (value: { linkIds: number[] }) => {
        const hide = message.loading('正在删除...', 0)
        delAutoLink.run(value).then(res => {
            hide()
            setselectedRows([])
            if (res?.data) {
                message.success('删除成功')
                getCorpAutoLinkList.refresh()
            } else {
                message.error('删除失败')
            }
        }).catch(() => hide())
    }

    return <Card
        styles={{ body: { padding: 0, display: 'flex', flexDirection: 'column', height: 'calc(100vh - 88px)' } }}
    >
        <div>
            <SearchBox
                bodyPadding={`10px 16px 4px`}
                buttons={<>
                    <Button type="primary" onClick={() => {
                        setQueryParamsNew({ ...queryParams, pageNum: 1 })
                    }} loading={getCorpAutoLinkList.loading} icon={<SearchOutlined />}>搜索</Button>
                    <Button type="primary" icon={<PlusOutlined />} onClick={() => setVisible(true)}>链接生成</Button>
                    <Popconfirm
                        title="确定删除？"
                        onConfirm={() => { handleDel({ linkIds: selectedRows.map(i => i.id) }) }}
                        disabled={selectedRows.length === 0}
                    >
                        <Button type='primary' danger icon={<DeleteOutlined />} loading={delAutoLink.loading} disabled={selectedRows.length === 0}>删除</Button>
                    </Popconfirm>
                </>}
            >
                <>
                    <Select
                        value={queryParams?.platform}
                        onChange={(e) => setQueryParams({ ...queryParams, platform: e })}
                        showSearch
                        style={{ width: 110 }}
                        placeholder="书城"
                        filterOption={(input, option) =>
                            ((option?.label ?? '') as string).toLowerCase().includes(input.toLowerCase())
                        }
                        allowClear
                        options={bookPlatForm.map(item => ({ value: item.platformKey, label: item.platformName }))}
                    />
                    <Select
                        value={queryParams?.mpAccountId}
                        onChange={(e) => setQueryParams({ ...queryParams, mpAccountId: e })}
                        showSearch
                        style={{ width: 110 }}
                        placeholder="公众号"
                        filterOption={(input, option) =>
                            ((option?.label ?? '') as string).toLowerCase().includes(input.toLowerCase())
                        }
                        allowClear
                        options={mpList}
                    />
                    <Select
                        value={queryParams?.linkType}
                        onChange={(e) => setQueryParams({ ...queryParams, linkType: e })}
                        showSearch
                        style={{ width: 110 }}
                        placeholder="链接类型"
                        filterOption={(input, option) =>
                            ((option?.label ?? '') as string).toLowerCase().includes(input.toLowerCase())
                        }
                        allowClear
                        options={Object.keys(LINKTYPE).map(key => ({ label: LINKTYPE[key], value: key }))}
                    />
                    <Input placeholder='请输入渠道名称' style={{ width: 150 }} allowClear value={queryParams?.channelName} onChange={(e) => setQueryParams({ ...queryParams, channelName: e.target.value })} />
                    <Select
                        style={{ width: 110 }}
                        showSearch
                        placeholder="推广类型"
                        value={queryParams?.channelType}
                        onChange={(value) => setQueryParams({ ...queryParams, channelType: value })}
                        filterOption={(input, option) =>
                            ((option?.label ?? '') as string).toLowerCase().includes(input.toLowerCase())
                        }
                        allowClear
                        options={[{ label: '外部', value: '1' }, { label: '内部', value: '2' }]}
                    />
                    <DatePicker.RangePicker
                        placeholder={['创建时间开始', '创建时间结束']}
                        allowClear
                        value={queryParams?.createTimeStart ? [dayJs(queryParams?.createTimeStart), dayJs(queryParams?.createTimeEnd)] : undefined}
                        onChange={(_, options) => setQueryParams({ ...queryParams, createTimeStart: options?.[0], createTimeEnd: options?.[1] })}
                    />
                </>
            </SearchBox>
        </div>
        <div className={style.bookLinkTable} ref={ref}>
            <Table
                dataSource={getCorpAutoLinkList?.data?.data?.records}
                columns={bookLinkTableConfig(false, handleCopy, handleDel)}
                bordered
                pagination={false}
                rowKey={'id'}
                size='small'
                className='resetTable'
                loading={getCorpAutoLinkList?.loading}
                scroll={{ y: size?.height && ref.current ? size?.height - ref.current.querySelector('.ant-table-thead').clientHeight : 300 }}
                rowSelection={{
                    selectedRowKeys: selectedRows?.map((item: any) => item?.id),
                    onSelect: (record: { id: string }, selected: boolean) => {
                        let newData = JSON.parse(JSON.stringify(selectedRows))
                        if (selected) {
                            newData.push({ ...record })
                        } else {
                            newData = newData.filter((item: { id: string }) => item.id !== record.id)
                        }
                        setselectedRows(newData)
                    },
                    onSelectAll: (selected: boolean, _: { id: string }[], changeRows: { id: string }[]) => {
                        let newData = JSON.parse(JSON.stringify(selectedRows || '[]'))
                        if (selected) {
                            changeRows.forEach((item: { id: string }) => {
                                let index = newData.findIndex((ite: { id: string }) => ite.id === item.id)
                                if (index === -1) {
                                    newData.push(item)
                                }
                            })
                        } else {
                            let newSelectAccData = newData.filter((item: { id: string }) => {
                                let index = changeRows.findIndex((ite: { id: string }) => ite.id === item.id)
                                if (index !== -1) {
                                    return false
                                } else {
                                    return true
                                }
                            })
                            newData = newSelectAccData
                        }
                        setselectedRows(newData)
                    }
                }}
            />
        </div>
        <div className={style.bookLinkPagination}>
            <Pagination
                size="small"
                total={getCorpAutoLinkList?.data?.data?.total || 0}
                showSizeChanger
                showQuickJumper
                pageSize={getCorpAutoLinkList?.data?.data?.size || 20}
                current={getCorpAutoLinkList?.data?.data?.current || 1}
                onChange={(page: number, pageSize: number) => {
                    // ref.current?.scrollTo({ top: 0 })
                    setTimeout(() => {
                        setQueryParams({ ...queryParams, pageNum: page, pageSize })
                        setQueryParamsNew({ ...queryParamsNew, pageNum: page, pageSize })
                    }, 50)
                }}
                showTotal={(total: number) => <span style={{ fontSize: 12 }}>共 {total} 条</span>}
            />
        </div>

        {/* 链接生成 模态框 */}
        {visible && <ModalBookLink
            mpList={mpList}
            bookPlatForm={bookPlatForm}
            visible={visible}
            initialValues={initialValues}
            onChange={() => {
                setInitialValues(undefined)
                setVisible(false)
                getCorpAutoLinkList.refresh()
            }}
            onClose={() => {
                setInitialValues(undefined)
                setVisible(false)
            }}
        />}
    </Card>
};

export default inject('store')(observer((props: any) => BookLink(props.store)));