import { Button, Card, DatePicker, Input, message, Popconfirm, 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 BatchAddLabel from '@/components/BatchAddLabel'
import { useModel } from 'umi'
const { Option } = Select
const { Search } = Input
const { TabPane } = Tabs
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: 'create_time',
    upOrder: false,
    type: '',
    isCollect: false,
    dataType: 'all',
    content: ''
}
/**广告标题*/
function AdTitle() {
    const [state, dispatch] = useReducer(reducer, initState)
    const { beginDate, endDate, labelIds, dataType, upOrder, type, isCollect, sortRule } = state
    const { getContentList, getLabels, delContents, collects, collectsCancel, setBatchContents } = useModel('useLaunch.useMaterial')

    const [visible, setVisible] = useState<boolean>(false)
    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(() => {
        getContentList.run({ ...state, labelIds: labelIds })
    }, [state])

    /**分页 */
    const pageChange = useCallback((page: string | number, pageSize?: string | number) => {
        dispatch({ type: 'pageNum', params: { pageNum: page } })
        dispatch({ type: 'pageSize', params: { pageSize: pageSize } })
    }, [])
    /** 修改 */
    const edit = useCallback(() => {
        // setCheckboxIds([])
        if (checkboxIds.length > 0) {
            setEditData(checkboxIds[0])
            setVisible(true)
        }
    }, [checkboxIds, editData])
    /** 收藏 */
    const collectsHandle = useCallback(({ id, isCollects }: { id: number, isCollects: boolean }) => {
        let collectsType: number = type === 1 ? 4 : 5
        if (isCollects) { // 收藏
            collects.run({ type: collectsType, contentIds: id.toString(), name: 'contents' }).then(res => {
                getContentList.refresh()
            })
        } else { // 取消收藏
            collectsCancel.run({ type: collectsType, contentIds: id.toString(), name: 'contents' }).then(res => {
                getContentList.refresh()
            })
        }
    }, [getContentList])
    /** 修改 */
    const editHandle = useCallback(({ item }: { item: any }) => {
        // if(checkboxIds.length > 0) {
        setEditData(item)
        setVisible(true)
        // }
    }, [])
    /** 删除 */
    const delHandle = useCallback(() => {
        console.log(checkboxIds);
        let ids = checkboxIds?.map((item: any) => item?.id)
        delContents.run({ ids: ids.toString() }).then(res => {
            getContentList.refresh()
        })
    }, [checkboxIds])

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

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

    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>
                        <Select style={{ width: 150 }} value={sortRule} onChange={(value: SelectValue) => { dispatch({ type: 'sortRule', params: { sortRule: value } }) }} placeholder="选择排序类型" allowClear>
                            <Option value="create_time">按照上传时间排序</Option>
                        </Select>
                        {/* <Search style={{ width: 150 }} placeholder="请输入小说" onSearch={(e) => { dispatch({ type: 'novels', params: { novels: e } }) }} allowClear /> */}
                        <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 === 'false' ? false : true } }) }}>
                            <Option value="false">全部</Option>
                            <Option value="true">我的收藏</Option>
                        </Select>

                        <Search
                            style={{ width: 300 }}
                            placeholder="请输入关键字"
                            onSearch={(e) => { dispatch({ type: 'content', params: { content: e } }) }}
                            allowClear
                            addonBefore={
                                <Select style={{ width: 70 }} value={type ? type : 0} onChange={(value: SelectValue) => { dispatch({ type: 'type', params: { type: value ? value : '' } }) }} placeholder="请选择素材类型">
                                    <Option value={0}>全部</Option>
                                    <Option value={1}>标题</Option>
                                    <Option value={2}>文案</Option>
                                </Select>
                            }
                        />
                    </Space>
                </div>
                <div>
                    <Space>
                        <Button type="primary" disabled={checkboxIds?.length > 1 ? false : true} onClick={batchEdit}>批量添加标签</Button>
                        <Popconfirm placement="top" title='确定删除？' onConfirm={delHandle} okText="Yes" cancelText="No" disabled={checkboxIds.length === 0}>
                            <Button danger disabled={checkboxIds.length === 0}>删除</Button>
                        </Popconfirm>
                        <Button type="primary" onClick={() => { setVisible(true); setEditData({}) }}>上传标题/文案</Button>
                    </Space>
                </div>
            </div>
        </>
    }>
        {visible && <AddTitle visible={visible} hideModal={() => { setVisible(false); }} editData={editData} ajax={getContentList} dataType={dataType}></AddTitle>}
        {/* 批量添加标签 */}
        {batchVisible && <BatchAddLabel show={batchVisible} onClose={()=>{setBatchVisible(false)}} onChange={batchEditOK} ajax={setBatchContents}/>}
        <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" />
            <TabPane tab="组内共享" key="group" />
        </Tabs>
        <Tables
            columns={columns(collectsHandle, editHandle)}
            dataSource={getContentList?.data?.records}
            total={getContentList?.data?.total}
            pageChange={pageChange}
            sizeChange={pageChange}
            size="small"
            bordered
            loading={getContentList?.loading}
            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
