import { Button, Card, DatePicker, Input, message, Select, Space, Tabs } from 'antd'
import { SelectValue } from 'antd/es/select'
import moment from 'moment'
import React, { useCallback, useEffect, useReducer, useState } from 'react'
import AddTitle from './components/addTitle'
import Tables from '@/components/Tables'
import columns from './tableConfig'
import { useModel } from 'umi'
const { Option } = Select
const { Search } = Input
const { TabPane } = Tabs
import BatchAddLabel from '@/components/BatchAddLabel'
import style from './index.less'

interface State {
    pageNum: number,
    pageSize: number,
    beginDate: string | undefined,  // 上传时间
    endDate: string | undefined,  // 结束时间
    labelIds: SelectValue, // 标签
    novels: string | undefined,  //书籍
    sortRule: string | undefined, // 类型排序
    upOrder: boolean, // 升序降序
    type: number | undefined,  // 素材类型
    isCollect: boolean, // 获取类型
    dataType: string, // 数据类型
    content: string,  // 关键字
}
interface Action {
    type: 'init' | 'begainDate' | 'content' | 'endDate' | 'labelIds' | 'dataType' | 'novels' | 'sortRule' | 'upOrder' | 'type' | 'isCollect' | 'pageNum' | 'pageSize',
    params?: any
}

function reducer(state: State, action: Action) {
    let { type, params } = action
    switch (type) {
        case 'begainDate':
            return { ...state, beginDate: params.beginDate }
        case 'endDate':
            return { ...state, endDate: params.endDate }
        case 'labelIds':
            return { ...state, labelIds: params.labelIds }
        case 'novels':
            return { ...state, novels: params.novels }
        case 'sortRule':
            return { ...state, sortRule: params.sortRule }
        case 'upOrder':
            return { ...state, upOrder: params.upOrder }
        case 'type':
            return { ...state, type: params.type }
        case 'isCollect':
            return { ...state, isCollect: params.isCollect }
        case 'dataType':
            return { ...state, dataType: params.dataType }
        case 'pageNum':
            return { ...state, pageNum: params.pageNum }
        case 'pageSize':
            return { ...state, pageSize: params.pageSize }
        case 'content':
            return { ...state, content: params.content }
        case 'init':
            return { ...initState }
        default:
            return { ...state }
    }
}
const initState = {
    pageNum: 1,
    pageSize: 20,
    beginDate: undefined,
    endDate: undefined,
    labelIds: [],
    novels: undefined,
    sortRule: 'consume_amount',
    upOrder: false,
    type: 1,
    isCollect: false,
    dataType: 'all',
    content: ''
}
/**广告标题*/
function AdTitle() {
    const [state, dispatch] = useReducer(reducer, initState)
    const { beginDate, endDate, labelIds, dataType, sortRule, upOrder, type, isCollect } = state
    const [visible, setVisible] = useState<boolean>(false)
    const { dataList, getLabels, datacollects, setTagContent } = useModel('useLaunch.useMaterial')
    const [checkboxIds, setCheckboxIds] = useState<any>([])  // 勾选ID
    const [editData, setEditData] = useState<any>({})
    const [batchVisible, setBatchVisible] = useState<boolean>(false)  // 批量添加标签弹窗控制

    useEffect(() => {
        getLabels.run({ pageNum: 1, pageSize: 200 })
    }, [])

    useEffect(() => {
        dataList.run({ ...state, labelIds, name: 'contentList' })
    }, [state])

    /**分页 */
    const pageChange = useCallback((page: string | number, pageSize?: string | number) => {
        dispatch({ type: 'pageNum', params: { pageNum: page } })
        dispatch({ type: 'pageSize', params: { pageSize: pageSize } })
    }, [])
    /** 收藏 */
    const collectsHandle = useCallback(({ id, isCollects }: { id: number, isCollects: boolean }) => {
        let collectsType: number = type === 1 ? 4 : 5
        datacollects.run({ type: collectsType, contentIds: id.toString(), name: 'contentCollect', collect: isCollects }).then(res => {
            dataList.refresh()
        })
    }, [dataList])
    /** 修改 */
    const editHandle = useCallback(({ item }: { item: any }) => {
        setEditData(item)
        setVisible(true)
    }, [])

    // 批量添加标签
    const batchEdit = useCallback(() => {
        setBatchVisible(true)
    }, [batchVisible])

    // 批量添加标签确定
    const batchEditOK = useCallback((value: string[]) => {
        setTagContent.run({mediaIds: checkboxIds?.map((item: {id: number}) => item?.id).toString(), labelIds: value.toString()}).then(() => {
            dataList.refresh()
            setBatchVisible(false)
            // setCheckboxIds([])
        })
    }, [batchVisible, checkboxIds, dataList])

    return <Card className={style.adOrigin} title={
        <>
            <div className={style.headerItem}>
                <div>
                    <Space>
                        <DatePicker style={{ width: 120 }} value={beginDate ? moment(beginDate) : null} onChange={(e: moment.Moment | null) => { dispatch({ type: 'begainDate', params: { beginDate: e ? moment(e).format('YYYY-MM-DD') : null } }) }} placeholder='消耗开始时间' />
                        <DatePicker style={{ width: 120 }} value={endDate ? moment(endDate) : null} onChange={(e: moment.Moment | null) => { dispatch({ type: 'endDate', params: { endDate: e ? moment(e).format('YYYY-MM-DD') : null } }) }} placeholder='消耗结束时间' />
                        <Select style={{ width: 160 }} maxTagCount='responsive' value={labelIds} onChange={(value: SelectValue) => { dispatch({ type: 'labelIds', params: { labelIds: value } }) }} placeholder="选择标签" allowClear mode="multiple">
                            {getLabels?.data?.records.map((item: any) => (<Option value={item?.id} key={item?.id}>{item?.label}</Option>))}
                        </Select>
                        <Search style={{ width: 150 }} placeholder="请输入小说" onSearch={(e) => { dispatch({ type: 'novels', params: { novels: e } }) }} allowClear />
                        <Select style={{ width: 150 }} value={sortRule} onChange={(value: SelectValue) => { dispatch({ type: 'sortRule', params: { sortRule: value } }) }} placeholder="选择排序类型" allowClear>
                            <Option value="view_times">浏览次数</Option>
                            <Option value="consume_amount">消耗金额</Option>
                            <Option value="click_rate">点击率</Option>
                        </Select>
                        <Select style={{ width: 70 }} value={upOrder ? '1' : '2'} onChange={(value: SelectValue) => { dispatch({ type: 'upOrder', params: { upOrder: value === '1' ? true : false } }) }} >
                            <Option value="1">升序</Option>
                            <Option value="2">降序</Option>
                        </Select>
                        <Select style={{ width: 100 }} value={isCollect ? 'true' : 'false'} onChange={(value: SelectValue) => { dispatch({ type: 'isCollect', params: { isCollect: value === 'true' ? true : false } }) }}>
                            <Option value="false">全部</Option>
                            <Option value="true">我的收藏</Option>
                        </Select>
                        <Select style={{ width: 70 }} value={type} onChange={(value: SelectValue) => { dispatch({ type: 'type', params: { type: value } }) }} placeholder="请选择素材类型">
                            <Option value={1}>标题</Option>
                            <Option value={2}>文案</Option>
                        </Select>
                        <Search style={{ width: 160 }} placeholder="请输入关键字" onSearch={(e) => { dispatch({ type: 'content', params: { content: e } }) }} allowClear />
                    </Space>
                </div>
                <div>
                    <Space>
                        <Button type="primary" disabled={checkboxIds?.length > 1 ? false : true} onClick={batchEdit}>批量添加标签</Button>
                    </Space>
                </div>
            </div>
        </>
    }>
        {visible && <AddTitle visible={visible} hideModal={() => { setVisible(false); }} editData={editData} ajax={dataList} dataType={dataType}></AddTitle>}
        {/* 批量添加标签 */}
        {batchVisible && <BatchAddLabel show={batchVisible} onClose={()=>{setBatchVisible(false)}} onChange={batchEditOK} ajax={setTagContent}/>}
        <Tabs onChange={(e) => { dispatch({ type: 'dataType', params: { dataType: e } }) }} type="card" size='small' className={style.tabs} activeKey={dataType}>
            <TabPane tab="公司云共享" key="all" />
            <TabPane tab="个人云共享" key="personal" />
        </Tabs>
        <Tables
            columns={columns(collectsHandle, editHandle)}
            dataSource={dataList?.data?.records.map((item: any) => ({...item, id: Number(item?.id)}))}
            total={dataList?.data?.total}
            pageChange={pageChange}
            sizeChange={pageChange}
            size="small"
            bordered
            loading={dataList?.loading}
            scroll={{ x: 2000 }}
            rowSelection={{
                selectedRowKeys: checkboxIds?.map((item: any) => item?.id?.toString()),
                getCheckboxProps: (record: any) => ({
                    disabled: checkboxIds?.find((item1: any) => item1?.id === record?.id) ? false : checkboxIds.length >= 20 ? true : false
                }),
                onSelect: (record: any, selected: any, selectedRows: any, nativeEvent: any) => {
                    setCheckboxIds([...selectedRows])
                },
                onSelectAll: (selected: any, selectedRows: any, changeRows: any) => {
                    if (selectedRows.length > 20) {
                        message.error('最多选择20个')
                        selectedRows = selectedRows.splice(0, 20)
                    }
                    setCheckboxIds([...selectedRows])
                }
            }}
        />
    </Card>
}
export default AdTitle
