import { App, Button, DatePicker, Input, Modal, Select, Space, Table, Tag, Typography } from "antd";
import style from '../../components/selectExternalAccount/index.less'
import { useEffect, useState } from "react";
import { getAutoLinkInfoApi, getCorpAutoLinkListApi, GetCorpAutoLinkListProps } from "../../API/bookLink";
import { useAjax } from "@/Hook/useAjax";
import { getBindMpListApi } from "../../API/corpUserAssign";
import { LINKTYPE } from "./const";
const { Text, Title } = Typography;
import dayJs from 'dayjs';
import { SearchOutlined, CloseOutlined, CheckOutlined } from '@ant-design/icons'
import { bookLinkTableConfig } from "./tableConfig";

interface Props {
    bookPlatForm: TASK_CREATE.BookPlatFormProps[]
    linkData: { [x: string]: any }[]
    mpAccountId: number | null
    platform: string
    visible?: boolean;
    onClose?: () => void;
    onChange?: (linkStr: string, miniprogramAppid?: string, miniprogramPage?: string) => void;
    linkList?: {
        type: 'link' | 'miniprogram',
        data: any[]
    }
}

/**
 * 选择链接
 * @param param0 
 * @returns 
 */
const SelectBookLink: React.FC<Props> = ({ bookPlatForm, linkData, mpAccountId, visible, onClose, onChange, platform, linkList }) => {

    /*******************************************/
    const { message } = App.useApp()
    const [data, setData] = useState<{ [x: string]: any }[]>(linkData)
    const [selectAdz, setSelectAdz] = useState<number>(1)   // 选择广告主
    const [mpList, setMplist] = useState<{ label: string, value: number }[]>([])
    const [queryParams, setQueryParams] = useState<GetCorpAutoLinkListProps>({ pageNum: 1, pageSize: 20, mpAccountId, platform })
    const [queryParamsNew, setQueryParamsNew] = useState<GetCorpAutoLinkListProps>({ pageNum: 1, pageSize: 20, mpAccountId, platform })

    const getCorpAutoLinkList = useAjax((params) => getCorpAutoLinkListApi(params))
    const getAutoLinkInfo = useAjax((params) => getAutoLinkInfoApi(params))
    const getBindMpList = useAjax(() => getBindMpListApi())
    /*******************************************/

    useEffect(() => {
        if (linkList?.type && linkList?.data?.length > 0 && mpAccountId) {
            const params = { mpAccountId, platform }
            if (linkList?.type === 'link') {
                params['links'] = linkList.data
            } else if (linkList?.type === 'miniprogram') {
                params['miniapps'] = linkList.data
            }
            getAutoLinkInfo.run(params).then(res => {
                if (res?.data?.length) {
                    setData(linkData.map((item, index) => ({ ...item, bookLink: res?.data?.[index] ? [res?.data?.[index]] : undefined })))
                }
            })
        }
    }, [linkList, mpAccountId, platform, linkData])

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

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

    const handleOk = () => {
        if (data?.every(item => item?.bookLink?.length)) {
            const miniprogramAppid: string[] = [];
            const miniprogramPage: string[] = [];
            const linkStr = data.map(item => {
                if (item?.bookLink?.[0]?.wxAppid) {
                    miniprogramAppid.push(item?.bookLink?.[0]?.wxAppid)
                    miniprogramPage.push(item?.bookLink?.[0]?.miniappPagePath)
                }
                return item.bookLink?.[0].link
            }).join(',')
            onChange?.(linkStr, miniprogramAppid?.join(','), miniprogramPage?.join(','))
        } else {
            message.error('请选择链接')
        }
    }

    const handleSelectAdz = (value: number) => {
        if (value === selectAdz) {
            return
        }
        setSelectAdz(value)
    }

    return <Modal
        title={<strong>选择链接</strong>}
        open={visible}
        onCancel={onClose}
        onOk={handleOk}
        width={1200}
        className={`${style.SelectPackage}`}
        styles={{
            body: {
                padding: '0 10px 0 10px'
            }
        }}
    >
        <div className={style.content}>
            <div className={style.left}>
                <h4 className={style.title}>链接</h4>
                <div className={style.accountIdList}>
                    {data?.map((item, index) => {
                        const bookLink = item?.bookLink
                        return <div key={index} onClick={() => { handleSelectAdz(index + 1) }} className={`${style.accItem} ${selectAdz === index + 1 && style.select} `}>
                            <div><Text ellipsis={{ tooltip: true }}>{item?.link?.title}{item?.link?.desc ? `（${item?.link?.desc}）` : ''}</Text></div>
                            {bookLink?.length > 0 && <CheckOutlined style={{ color: '#1890ff' }} />}
                        </div>
                    })}
                </div>
            </div>
            <div className={style.right}>
                <Space style={{ marginBottom: 10 }} align="end" size={5} wrap>
                    <Select
                        value={queryParams?.platform}
                        onChange={(e) => setQueryParams({ ...queryParams, platform: e })}
                        showSearch
                        style={{ width: 110 }}
                        disabled={!!platform}
                        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="公众号"
                        disabled={!!mpAccountId}
                        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 }))}
                    />
                    <DatePicker.RangePicker
                        placeholder={['创建时间开始', '创建时间结束']}
                        allowClear
                        value={queryParams?.createTimeStart ? [dayJs(queryParams?.createTimeStart), dayJs(queryParams?.createTimeEnd)] : undefined}
                        onChange={(_, options) => setQueryParams({ ...queryParams, createTimeStart: options?.[0], createTimeEnd: options?.[1] })}
                    />
                    <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' }]}
                    />
                    <Button type="primary" onClick={() => {
                        setQueryParamsNew({ ...queryParams, pageNum: 1 })
                    }} loading={getCorpAutoLinkList.loading} icon={<SearchOutlined />}>搜索</Button>
                </Space>

                <Table
                    tableLayout='fixed'
                    dataSource={getCorpAutoLinkList?.data?.data?.records}
                    columns={bookLinkTableConfig(true)}
                    loading={getCorpAutoLinkList.loading}
                    scroll={{ y: 400 }}
                    rowKey={'id'}
                    size='small'
                    bordered
                    rowSelection={{
                        selectedRowKeys: data[selectAdz - 1]?.bookLink?.map((item: any) => item?.id),
                        type: 'radio',
                        getCheckboxProps: (record: any) => ({
                            name: record.name,
                        }),
                        onChange(_, selectedRows) {
                            const newData = JSON.parse(JSON.stringify(data))
                            newData[selectAdz - 1].bookLink = selectedRows
                            setData(newData)
                        },
                    }}
                    pagination={{
                        total: getCorpAutoLinkList.data?.data?.total,
                        showTotal: (total) => <Tag color="cyan">总共{total}数据</Tag>,
                        showSizeChanger: true,
                        showLessItems: true,
                        defaultCurrent: 1,
                        defaultPageSize: 20,//默认初始的每页条数
                        current: getCorpAutoLinkList?.data?.data?.current || 1,
                        pageSize: getCorpAutoLinkList?.data?.data?.size || 20,
                        onChange: (page, pageSize) => {
                            setQueryParams({ ...queryParams, pageNum: page, pageSize })
                            setQueryParamsNew({ ...queryParamsNew, pageNum: page, pageSize })
                        }
                    }}
                    onRow={(record) => ({
                        onClick: () => {
                            console.log(record)
                            const newData = JSON.parse(JSON.stringify(data))
                            newData[selectAdz - 1]['bookLink'] = [record];
                            setData(newData)
                        },
                    })}
                />
            </div>
            <div className={style.center}>
                <Title level={5}>已选：{data[selectAdz - 1]?.bookLink?.length || 0}</Title>
                <div className={style.select_content}>
                    {data[selectAdz - 1]?.bookLink?.map(item => <div key={item.id}>
                        <Text ellipsis={{ tooltip: true }} className={style.marketingAssetName}>{item.channelName}</Text>
                        <CloseOutlined className={style.close} onClick={() => {
                            let newData = JSON.parse(JSON.stringify(data))
                            newData[selectAdz - 1].bookLink = newData[selectAdz - 1]?.bookLink?.filter((i: any) => i?.id !== item.id)
                            setData(newData)
                        }} />
                    </div>)}
                </div>
            </div>
        </div>
    </Modal>
}


export default SelectBookLink;