import { useAjax } from '@/Hook/useAjax';
import { cancelProjectApi, delProjectApi, getProjectListApi } from '@/pages/weComTask/API/businessPlan/create';
import { App, Button, Card, DatePicker, Input, Popconfirm, Space, Table } from 'antd';
import React, { useEffect, useState } from 'react';
import taskListColumns from './tableConfig';
import dayjs from 'dayjs';
import { SearchOutlined, DeleteOutlined, PauseCircleOutlined, PlusCircleOutlined } from '@ant-design/icons';
import Log from './log';
import { inject, observer } from 'mobx-react';
import { toJS } from 'mobx';
import { getBindMpListApi } from '@/pages/weComTask/API/corpUserAssign';
import { getCorpAllListApi } from '@/API/global';
import Select, { DefaultOptionType } from 'antd/es/select';
import AddToGroup from '../../../businessPlan/taskList/components/addToGroup';

/**
 * 任务列表
 * @returns 
 */
const TaskList: React.FC<{ weComTaskStore: { data: { bookList: TASK_CREATE.BookListProps[], bookPlatForm: TASK_CREATE.BookPlatFormProps[] } } }> = ({ weComTaskStore }) => {

    /***********************************************/
    const projectName = sessionStorage.getItem('CAMPCORP_OFFICIAL')
    const { message } = App.useApp();
    const { bookList, bookPlatForm } = toJS(weComTaskStore.data)
    const [queryForm, setQueryForm] = useState<BUSINES_SPLAN_API.GetProjectListProps>({ pageNum: 1, pageSize: 20, projectName, projectType: 2 })
    const [queryFormNew, setQueryFormNew] = useState<BUSINES_SPLAN_API.GetProjectListProps>({ pageNum: 1, pageSize: 20, projectName, projectType: 2 })
    const [logOpenData, setLogOpenData] = useState<{ visible: boolean, data: any }>({ visible: false, data: {} })
    const [selectedRows, setselectedRows] = useState<any[]>([])
    const [mpList, setMpList] = useState<DefaultOptionType[]>([])
    const [corpList, setCorpList] = useState<DefaultOptionType[]>([])
    const [addToGroupData, setAddToGroupData] = useState<{ visible: boolean, data: any[] }>({ visible: false, data: undefined })

    const getProjectList = useAjax((params) => getProjectListApi(params))
    const delProject = useAjax((params) => delProjectApi(params))
    const cancelProject = useAjax((params) => cancelProjectApi(params))
    const getBindMpList = useAjax(() => getBindMpListApi())
    const getCorpAllList = useAjax((param) => getCorpAllListApi(param))
    /***********************************************/

    useEffect(() => {
        getBindMpList.run().then(res => {
            if (res?.data)
                setMpList(res.data.map((item: any) => ({ label: item.name, value: item.id, appId: item.appId })))
        })
        getCorpAllList.run({}).then(res => {
            if (res?.data)
                setCorpList(res.data.map((item: any) => ({ label: item.corpName, value: item.corpId })))
        })
    }, [])

    useEffect(() => {
        const projectName = sessionStorage.getItem('CAMPCORP_OFFICIAL')
        if (projectName) {
            sessionStorage.removeItem('CAMPCORP_OFFICIAL')
        }
    }, [])

    useEffect(() => {
        getProjectList.run(queryFormNew)
    }, [queryFormNew])

    // 日志
    const handleLog = (data: any) => {
        setLogOpenData({ visible: true, data })
    }

    // 复制
    const handleCopy = (data: any, isCopy: boolean, isEditSc?: boolean) => {
        sessionStorage.setItem('ROBOT_OFFICIALTASKID', JSON.stringify({ id: data.id, isCopy, isEditSc: isEditSc || false }))
        sessionStorage.setItem('oldPath', '/weComTask/groupChatSend/robot/create')
        window.location.href = '/weComTask#/weComTask/groupChatSend/robot/create'
    }

    // 删除
    const handleDel = (data: { projectIds: number[] }, type: 'del' | 'cancel' | 'open') => {
        const hide = message.loading(type === 'del' ? '正在删除...' : '正在取消...', 0)
        switch (type) {
            case 'del':
                delProject.run(data).then(res => {
                    hide()
                    setselectedRows([])
                    if (res?.data) {
                        message.success('删除成功')
                        getProjectList.refresh()
                    } else {
                        message.error('删除失败')
                    }
                }).catch(() => hide())
                break
            case 'cancel':
            case 'open':
                cancelProject.run({ ...data, pause: type === 'cancel' ? false : true }).then(res => {
                    hide()
                    setselectedRows([])
                    if (res?.data) {
                        message.success(type === 'cancel' ? '取消成功' : '启用成功')
                        getProjectList.refresh()
                    } else {
                        message.error(type === 'cancel' ? '取消失败' : '启用失败')
                    }
                }).catch(() => hide())
                break
        }

    }

    return <Card>
        <div style={{ display: 'flex', gap: 10, marginBottom: 10 }}>
            <Space.Compact>
                <Button>任务名称</Button>
                <Input placeholder='请输入任务名称' allowClear value={queryForm?.projectName} onChange={(e) => setQueryForm({ ...queryForm, projectName: e.target.value })} />
            </Space.Compact>
            <Space.Compact>
                <Button>创建时间</Button>
                <DatePicker.RangePicker
                    placeholder={["创建时间开始", "创建时间结束"]}
                    value={queryForm?.createTimeMin ? [dayjs(queryForm?.createTimeMin), dayjs(queryForm?.createTimeMax)] : undefined}
                    onChange={(_, options) => {
                        const newQueryForm = { ...queryForm }
                        if (options?.[0]) {
                            newQueryForm.createTimeMin = options?.[0] + ' 00:00:00'
                            newQueryForm.createTimeMax = options?.[1] + ' 23:59:59'
                        } else {
                            delete newQueryForm?.createTimeMin
                            delete newQueryForm?.createTimeMax
                        }
                        setQueryForm(newQueryForm)
                    }}
                />
            </Space.Compact>
            <Space.Compact>
                <Button>状态</Button>
                <Select
                    style={{ width: 120 }}
                    onChange={(e) => {
                        setQueryForm({ ...queryForm, status: e })
                    }}
                    placeholder="请选择状态"
                    allowClear
                    options={[
                        { value: 1, label: '可用' },
                        { value: 3, label: '暂停' },
                    ]}
                />
            </Space.Compact>
            <Button
                type='primary'
                onClick={() => {
                    setQueryFormNew({ ...queryForm, pageNum: 1 })
                }}
                icon={<SearchOutlined />}
            >搜索</Button>
            <Button
                type='primary'
                icon={<PlusCircleOutlined />}
                disabled={selectedRows.length === 0}
                onClick={() => {
                    setAddToGroupData({ visible: true, data: selectedRows })
                }}
            >添加到项目组</Button>
            <Popconfirm
                title="确定删除？"
                onConfirm={() => { handleDel({ projectIds: selectedRows.map(i => i.id) }, 'del') }}
                disabled={selectedRows.length === 0}
            >
                <Button type='primary' danger icon={<DeleteOutlined />} loading={delProject.loading} disabled={selectedRows.length === 0}>删除</Button>
            </Popconfirm>
            <Popconfirm
                title="确定暂停？"
                onConfirm={() => { handleDel({ projectIds: selectedRows.map(i => i.id) }, 'cancel') }}
                disabled={selectedRows.length === 0}
            >
                <Button type='primary' style={{ backgroundColor: 'orange', borderColor: 'orange' }} loading={cancelProject.loading} icon={<PauseCircleOutlined />} disabled={selectedRows.length === 0}>暂停任务</Button>
            </Popconfirm>
            <Popconfirm
                title="确定启用？"
                onConfirm={() => { handleDel({ projectIds: selectedRows.map(i => i.id) }, 'open') }}
                disabled={selectedRows.length === 0}
            >
                <Button type='primary' style={{ backgroundColor: '#87d068', borderColor: '#87d068' }} loading={cancelProject.loading} icon={<PauseCircleOutlined />} disabled={selectedRows.length === 0}>启用任务</Button>
            </Popconfirm>
        </div>
        <Table
            dataSource={getProjectList?.data?.data?.records}
            columns={taskListColumns(mpList, corpList, handleLog, handleCopy, handleDel)}
            rowKey={'id'}
            bordered={true}
            size='small'
            scroll={{ y: 600, x: 1200 }}
            loading={getProjectList?.loading}
            pagination={{
                current: getProjectList?.data?.data?.current,
                pageSize: getProjectList?.data?.data?.size,
                total: getProjectList?.data?.data?.total,
                showSizeChanger: true,
                onChange: (page, pageSize) => {
                    setQueryFormNew({ ...queryFormNew, pageNum: page, pageSize })
                    setQueryForm({ ...queryForm, pageNum: page, pageSize })
                }
            }}
            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)
                }
            }}
        />

        {/* 日志 */}
        {logOpenData.visible && <Log
            {...logOpenData}
            bookList={bookList}
            bookPlatForm={bookPlatForm}
            onClose={() => {
                setLogOpenData({ visible: false, data: undefined })
            }}
        />}

        {/* 加入到项目组 */}
        {addToGroupData?.visible && <AddToGroup
            {...addToGroupData}
            onClose={() => {
                setAddToGroupData({ visible: false, data: undefined })
            }}
            onChange={() => {
                setAddToGroupData({ visible: false, data: undefined })
                setselectedRows([])
                getProjectList.refresh()
            }}
        />}
    </Card>
};

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