import { PlusOutlined } from "@ant-design/icons"
import { Button, Form, Input, message, Modal, Select, Table } from "antd"
import React, { useEffect, useState } from "react"
import { useModel } from "umi"
import columnsAdd from "./tableConfigAdd"


interface Props {
    pitcherData: any[],
    onChange: () => void
}
/**
 * 新增媒体账户组
 * @returns 
 */
const KEY = 'ADQUSERS'
const AddGroup: React.FC<Props> = (props) => {

    /**********************/
    const { pitcherData, onChange } = props
    const [visible, setVisible] = useState<boolean>(false)
    const [addVisible, setAddVisible] = useState<boolean>(false)
    const [pitcherDB, setPitcherDB] = useState<any[]>([])
    const [initialValues, setInitialValues] = useState<any>({})

    const [form] = Form.useForm()
    const { currentUser: { userId } }: any = useModel('@@initialState', model => ({ currentUser: model.initialState?.currentUser }))
    /**********************/
    // 进入查找库
    useEffect(() => {
        getList()
    }, [])

    // 
    const getList = () => {
        let data = localStorage.getItem(KEY + userId)
        if (data) {
            setPitcherDB(JSON.parse(data))
        }
        onChange && onChange()
    }

    /** 确定新增 */
    const handleOk = async () => {
        form.submit()
        let data = await form.validateFields()
        console.log(data)
        let length = pitcherDB.length
        if (Object.keys(initialValues).length > 0) { // 修改
            let newPitcherDB = pitcherDB.map((item: { id: number }) => {
                if (initialValues.id === item.id) {
                    return { ...data, id: initialValues.id, users: data.pitcher?.map((str: string) => str.split('_')[1]), ids: data.pitcher?.map((str: string) => str.split('_')[0]) }
                }
                return item
            })
            localStorage.setItem(KEY + userId, JSON.stringify(newPitcherDB))
            message.success('修改成功')
        } else { // 新增
            data.id = length > 0 ? pitcherDB[length - 1].id + 1 : 1
            if (pitcherDB?.some((item: { name: string }) => item.name === data?.name)) {
                message.error('组名重复，请重新输入')
                return
            }
            let newData = data
            newData = { ...data, users: data.pitcher?.map((str: string) => str.split('_')[1]), ids: data.pitcher?.map((str: string) => str.split('_')[0]) }
            pitcherDB.push(newData)
            localStorage.setItem(KEY + userId, JSON.stringify(pitcherDB))
            message.success('新增成功')
        }
        getList()
        setAddVisible(false)
        setInitialValues({})
        form.resetFields()
    }

    /** 删除 */
    const del = (id: number) => {
        let newpitcherDB = pitcherDB.filter((item: { id: number }) => item.id !== id)
        localStorage.setItem(KEY + userId, JSON.stringify(newpitcherDB?.map((item: { id: number }, index: number) => ({ ...item, id: index + 1 }))))
        getList()
        message.success('删除成功')
    }

    /** 修改 */
    const edit = (value: any) => {
        setInitialValues(value)
        form.resetFields()
        setAddVisible(true)
    }

    /** 清空 */
    const clear = () => {
        setInitialValues({})
        form.resetFields()
    }

    return <div>
        <Button type='primary' onClick={() => { setVisible(true) }}><PlusOutlined />新增媒体账户组</Button>

        {visible && <Modal title="媒体账号组" footer={null} visible={visible} width={900} onCancel={() => { setVisible(false) }}>
            <Button type='primary' onClick={() => { setAddVisible(true) }} style={{ marginBottom: 10 }}><PlusOutlined />新增</Button>
            <Table columns={columnsAdd(del, edit)} dataSource={pitcherDB} size='small' bordered rowKey={(e) => { return e.id }} />
        </Modal>}

        {addVisible && <Modal title="新增媒体账号组" visible={visible} width={450} onOk={() => handleOk()} onCancel={() => { setAddVisible(false); clear() }}>
            <Form
                name="basic"
                form={form}
                labelCol={{ span: 4 }}
                wrapperCol={{ span: 20 }}
                autoComplete="off"
                initialValues={initialValues}
            >
                <Form.Item label="组名" name="name" rules={[{ required: true, message: '请输入组名!' }]}>
                    <Input placeholder="请输入组名" max={6} disabled={Object.keys(initialValues).length > 0} />
                </Form.Item>
                <Form.Item label="账号" name="pitcher" rules={[{ required: true, message: '请选择账号!' }]}>
                    <Select
                        placeholder='请输账号ID'
                        showArrow
                        showSearch
                        allowClear
                        maxTagCount={3}
                        filterOption={(input: any, option: any) => {
                            return option!.children?.toString().toLowerCase().includes(input.toLowerCase())
                        }}
                        mode="multiple"
                    >
                        {
                            pitcherData?.map((list: any, eq: number) => {
                                return <Select.Option key={list?.id} value={list?.id + '_' + list.accountId}>
                                    {list.remark ? list.accountId + '——' + list.remark : list.accountId}
                                </Select.Option>
                            })
                        })
                    </Select>
                </Form.Item>
            </Form>
        </Modal>}
    </div>
}


export default React.memo(AddGroup)