import { useAjax } from "@/Hook/useAjax"
import { App, Button, DatePicker, Drawer, Form, Input, Modal, Select, Space, Table, Tag } from "antd"
import React, { useEffect, useState } from "react"
import { CorpMailListProps, getBindMpListApi, getChangeLogApi, getCorpMailListApi, putCorpSysUserApi } from "../../API/corpUserAssign"
import SearchBox from "../../components/searchBox"
import { SearchOutlined, SwapOutlined } from '@ant-design/icons';
import { TableChangeLogConfig, TableMailConfig } from "./tableConfig"
import { getUserAllListApi } from "@/pages/login/API"
import dayjs from "dayjs"
import OperZs from "./operZs"
import AssignAccount from "./assignAccount"

interface Props {
    defindConfig: {
        title: string,
        corpId: string
    }
    visible?: boolean
    onClose?: () => void
    onChange?: () => void
}
const MailList: React.FC<Props> = ({ defindConfig, visible, onClose, onChange }) => {

    /**************************************/
    const [queryForm, setQueryForm] = useState<CorpMailListProps>({ pageNum: 1, pageSize: 20 })
    const [editSelectedRow, setEditSelectedRow] = useState<any[]>([])
    const [open, setOpen] = useState<boolean>(false)
    const [accountOpen, setAccountOpen] = useState<any>(null)//公众号指派弹窗
    const [changeLog, setChangeLog] = useState<any>(null)//公众号变更记录弹窗
    const [logData, setLogData] = useState<any[]>([])//变更记录数据
    const [params, setParams] = useState<any[]>([])
    const [mpList, setMplist] = useState<{ label: string, value: number }[]>([])//已入库公众号列表
    const [form] = Form.useForm()
    const { message } = App.useApp()
    const [operData, setOperData] = useState<{ visible: boolean, data: any[] }>({ visible: false, data: [] })

    const getCorpMailList = useAjax((params) => getCorpMailListApi(params))
    const putCorpSysUser = useAjax((params) => putCorpSysUserApi(params))
    const getUserAllList = useAjax(() => getUserAllListApi())
    const getChangeLog = useAjax((params) => getChangeLogApi(params))
    const getBindMpList = useAjax(() => getBindMpListApi())
    /**************************************/

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

    useEffect(() => {
        getList()
    }, [queryForm, defindConfig.corpId])
    useEffect(() => {
        if (changeLog) {
            getChangeLog.run({ corpId: changeLog.corpId, corpUserId: changeLog.corpUserId }).then(res => {
                setLogData(res.data)
            })
        }
    }, [changeLog])
    const getList = () => {
        getCorpMailList.run({ ...queryForm, corpId: defindConfig.corpId })
    }

    const handle = (data: any[], type?: string) => {
        if (type === 'zs') {
            setOperData({ visible: true, data })
        } else {
            if (data.length === 1) {
                form.setFieldsValue({ beginTime: dayjs(), operUserId: data[0].operUserId, putUserId: data[0].putUserId })
            } else {
                form.setFieldsValue({ beginTime: dayjs(), operUserId: undefined, putUserId: undefined })
            }
            setParams(data)
            setOpen(true)
        }
    }

    const handleOk = async () => {
        form.submit()
        let data = await form.validateFields()
        data.beginTime = dayjs(data.beginTime).format('YYYY-MM-DD')
        putCorpSysUser.run({ ...data, corpId: defindConfig.corpId, corpUserIds: params.map((item: any) => item.corpUserId) }).then(res => {
            message.success('指派成功')
            getList()
            setParams([])
            setEditSelectedRow([])
            setOpen(false)
        })
    }
    return <>
        <Drawer title={`${defindConfig.title} 企微通讯录`} width={1300} placement="right" onClose={onClose} open={visible}>
            <SearchBox
                bodyPadding={`16px 0 12px`}
                buttons={<Space>
                    <Button type="primary" onClick={() => getList()} loading={getCorpMailList.loading} icon={<SearchOutlined />}>搜索</Button>
                    <Button type="primary" disabled={editSelectedRow.length === 0} onClick={() => handle(editSelectedRow)} loading={getCorpMailList.loading} icon={<SwapOutlined />}>批量指派</Button>
                    <Button type="primary" disabled={editSelectedRow.length === 0} onClick={() => handle(editSelectedRow, 'zs')} loading={getCorpMailList.loading} icon={<SwapOutlined />}>批量指派运营助手</Button>
                    <Button type="primary" disabled={editSelectedRow.length === 0} onClick={() => setAccountOpen({})} loading={getCorpMailList.loading} icon={<SwapOutlined />}>批量指派公众号</Button>
                </Space>}
            >
                <>
                    <Input onChange={(e) => setQueryForm({ ...queryForm, name: e.target.value, pageNum: 1 })} value={queryForm?.name} placeholder="企微号名称" allowClear />
                    <Select
                        value={queryForm?.mpAccountId}
                        onChange={(e) => setQueryForm({ ...queryForm, mpAccountId: e })}
                        showSearch
                        style={{ width: 110 }}
                        placeholder="公众号"
                        filterOption={(input, option) =>
                            ((option?.label ?? '') as string).toLowerCase().includes(input.toLowerCase())
                        }
                        allowClear
                        options={mpList}
                    />
                    <Select
                        value={queryForm?.operUserIds}
                        onChange={(e) => setQueryForm({ ...queryForm, operUserIds: e })}
                        mode="multiple"
                        showSearch
                        style={{ minWidth: 110 }}
                        allowClear
                        placeholder="选择运营"
                        filterOption={(input, option) =>
                            (option?.children as any)?.toLowerCase().indexOf(input.toLowerCase()) >= 0
                        }
                    >
                        {getUserAllList?.data?.data?.map((item: any) => <Select.Option value={item.userId} key={item.userId}>{item.nickname}</Select.Option>)}
                    </Select>
                    <Select
                        value={queryForm?.putUserIds}
                        onChange={(e) => setQueryForm({ ...queryForm, putUserIds: e })}
                        mode="multiple"
                        showSearch
                        style={{ minWidth: 110 }}
                        allowClear
                        placeholder="选择投手"
                        filterOption={(input, option) =>
                            (option?.children as any)?.toLowerCase().indexOf(input.toLowerCase()) >= 0
                        }
                    >
                        {getUserAllList?.data?.data?.map((item: any) => <Select.Option value={item.userId} key={item.userId}>{item.nickname}</Select.Option>)}
                    </Select>
                    <Select
                        value={queryForm?.operAssistantIds}
                        onChange={(e) => setQueryForm({ ...queryForm, operAssistantIds: e })}
                        mode="multiple"
                        showSearch
                        style={{ minWidth: 110 }}
                        allowClear
                        placeholder="选择运营助手"
                        filterOption={(input, option) =>
                            (option?.children as any)?.toLowerCase().indexOf(input.toLowerCase()) >= 0
                        }
                    >
                        {getUserAllList?.data?.data?.map((item: any) => <Select.Option value={item.userId} key={item.userId}>{item.nickname}</Select.Option>)}
                    </Select>
                </>
            </SearchBox>

            <Table
                style={{ marginBottom: 1 }}
                dataSource={getCorpMailList.data?.data?.records}
                columns={TableMailConfig(handle, setAccountOpen, setChangeLog)}
                scroll={{ x: 1300 }}
                rowKey={(s: { corpUserId: any; }) => {
                    return s.corpUserId
                }}
                loading={getCorpMailList.loading}
                size='small'
                pagination={{
                    total: getCorpMailList.data?.data?.total,
                    showTotal: (total) => <Tag color="cyan">总共{total}数据</Tag>,
                    showSizeChanger: true,
                    showLessItems: true,
                    defaultCurrent: 1,
                    defaultPageSize: 20,//默认初始的每页条数
                    current: getCorpMailList?.data?.data?.current || 1,
                    pageSize: getCorpMailList?.data?.data?.size || 20,
                    onChange: (page, pageSize) => {
                        setQueryForm({ ...queryForm, pageNum: page, pageSize })
                    }
                }}
                rowSelection={{
                    type: 'checkbox',
                    selectedRowKeys: editSelectedRow?.map(item => item.corpUserId),
                    onSelect: (record: { corpUserId: any; }, selected: any) => {
                        if (selected) {
                            setEditSelectedRow([...editSelectedRow, record])
                        } else {
                            setEditSelectedRow(editSelectedRow?.filter(item => item.corpUserId !== record.corpUserId))
                        }
                    },
                    onSelectAll: (selected: any, rows: any, changeRows: any[]) => {
                        if (selected) {
                            setEditSelectedRow([...editSelectedRow, ...changeRows])
                        } else {
                            let newArr = editSelectedRow?.filter(item => changeRows.every(i => i?.corpUserId !== item?.corpUserId))
                            setEditSelectedRow(newArr)
                        }
                    }
                }}
            />
        </Drawer>

        {/* 指派 */}
        {open && <Modal
            title='指派'
            open={open}
            onCancel={() => {
                setOpen(false)
            }}
            onOk={handleOk}
            confirmLoading={putCorpSysUser.loading}
        >
            <Form
                name="basicZhiPai"
                form={form}
                labelCol={{ span: 4 }}
                wrapperCol={{ span: 20 }}
                autoComplete="off"
                labelAlign="left"
                colon={false}
                initialValues={{ beginTime: dayjs() }}
            >
                <Form.Item label="开始时间" name="beginTime" rules={[{ required: true, message: '请选择开始时间!' }]}>
                    <DatePicker />
                </Form.Item>
                <Form.Item label="运营" name="operUserId" rules={[{ required: true, message: '请选择运营!' }]}>
                    <Select
                        showSearch
                        style={{ minWidth: 180 }}
                        allowClear
                        placeholder="选择运营"
                        filterOption={(input, option) =>
                            (option?.children as any)?.toLowerCase().indexOf(input.toLowerCase()) >= 0
                        }
                    >
                        {getUserAllList?.data?.data?.map((item: any) => <Select.Option value={item.userId} key={item.userId}>{item.nickname}</Select.Option>)}
                    </Select>
                </Form.Item>
                <Form.Item label="投手" name="putUserId" rules={[{ required: true, message: '请选择投手!' }]}>
                    <Select
                        showSearch
                        style={{ minWidth: 180 }}
                        allowClear
                        placeholder="选择投手"
                        filterOption={(input, option) =>
                            (option?.children as any)?.toLowerCase().indexOf(input.toLowerCase()) >= 0
                        }
                    >
                        {getUserAllList?.data?.data?.map((item: any) => <Select.Option value={item.userId} key={item.userId}>{item.nickname}</Select.Option>)}
                    </Select>
                </Form.Item>
            </Form>
        </Modal>}

        {/* 指派运营助手 */}
        {operData?.visible && <OperZs
            {...operData}
            getUserAllList={getUserAllList}
            corpId={defindConfig.corpId}
            onChange={() => {
                getCorpMailList.refresh()
                setEditSelectedRow([])
                setOperData({ visible: false, data: [] })
            }}
            onClose={() => {
                setOperData({ visible: false, data: [] })
            }}
        />}
        {/* 批量指派公众号 */}
        {
            !!accountOpen && <AssignAccount
                visible={accountOpen}
                editSelectedRow={editSelectedRow}
                onClose={() => {
                    setAccountOpen(null)
                }}
                onChange={() => {
                    getCorpMailList.refresh()
                    setEditSelectedRow([])
                }}
                corpId={defindConfig.corpId}
            />
        }
        {/* 变更记录 */}
        {
            logData?.length > 0 && <Modal
                open={!!changeLog}
                onCancel={() => {
                    setChangeLog(null)
                    setLogData([])
                }}
                footer={null}
                title={'变更记录'}
            >
                <Table
                    columns={TableChangeLogConfig()}
                    dataSource={logData}
                    pagination={false}
                    rowKey={'id'}
                />
            </Modal>
        }
    </>
}

export default React.memo(MailList)