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';

/**
 * 书城自动链接管理
 * @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
        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]
        })
        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 - 74px)', overflow: 'hidden' } }}
    >
        <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'
                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)));