import { App, Card, Form, Modal, Popover, Space } from "antd";
import React, { useContext, useEffect, useRef, useState } from "react";
import '../../../../businessPlan/create/global.less'
import { QuestionCircleFilled, RightOutlined, DownOutlined } from '@ant-design/icons';
import PreviewTime from "@/pages/weComTask/components/previewTime";
import { getAllWxListApi } from "@/pages/weComTask/API/corpUserAssign";
import { useAjax } from "@/Hook/useAjax";
import AddGroupObject from "./addGroupObject";
import { DispatchGroupChatCreate } from "../..";
import NewSteps from "@/pages/weComTask/components/newSteps";

/**
 * 群聊创建进群对象配置
 * @param param0 
 * @returns 
 */
const SettingsGroupUser: React.FC<GROUP_CHAT_CREATE.FoundationProps<any>> = ({ visible, onClose, value, onChange }) => {


    /***************************************/
    const { bookPlatForm, bookList } = useContext(DispatchGroupChatCreate)!;
    const ref1 = useRef<HTMLDivElement>(null)

    const { message } = App.useApp();
    const [form] = Form.useForm();
    const strategyList = Form.useWatch('strategyList', form)
    const [activeKey, setActiveKey] = useState<number[]>([])
    const [stepsList, setStepsList] = useState<any>([])

    const getAccountList = useAjax(() => getAllWxListApi())
    /***************************************/

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

    useEffect(() => {
        const strategyList = value?.strategyList?.map(item => {
            return {
                ...item,
                groupObjectList: item?.groupObjectList || []
            }
        })
        form.setFieldsValue({
            strategyList
        })
        filedUpdateChange({ strategyList })
    }, [value])

    const handleOk = () => {
        form.validateFields().then((values) => {
            console.log(values)
            onChange?.(values)
        }).catch(() => {
            form.submit()
        });
    };

    const filedUpdateChange = ({ strategyList }: any) => {
        const stepsData = strategyList?.map((item, index) => {
            const { strategyName } = item
            return { title: `策略${index + 1}: ${strategyName}`, description: `进群对象名称、进群对象配置、群递增起始编号、群固定人数...`, id: `strategy_${index + 1}`, checked: item?.groupObjectList?.length > 0 }
        })
        setStepsList(stepsData)
    }

    return <Modal
        title={<strong>群聊创建群配置</strong>}
        open={visible}
        onCancel={onClose}
        width={1000}
        onOk={handleOk}
        className={`settingsModal`}
    >
        <div className={`body_steps`}>
            <NewSteps
                items={stepsList}
                onChange={(e) => {
                    if (e?.id)
                        ref1.current?.querySelector('#' + e?.id)?.scrollIntoView({ behavior: 'smooth' })
                }}
            />
        </div>
        <div className={`body_content`} ref={ref1}>
            <Form
                form={form}
                name="newGroupUser"
                labelAlign='left'
                labelCol={{ span: 6 }}
                colon={false}
                labelWrap
                scrollToFirstError={{
                    behavior: 'smooth',
                    block: 'center'
                }}
                onFinishFailed={({ errorFields }) => {
                    console.log('errorFields--->', errorFields)
                    setActiveKey(data => data?.filter(item => item != errorFields?.[0]?.name?.[1]))
                    message.error(errorFields?.[0]?.errors?.[0])
                }}
                onFinish={handleOk}
                initialValues={{
                    // strategyList: [{ id: Date.now() }]
                }}
                onFieldsChange={() => {
                    filedUpdateChange(form.getFieldsValue())
                }}
                preserve={true}
            >
                <Form.List name="strategyList">
                    {(fields) => (
                        <>
                            {fields.map(({ key, name, ...restField }, index) => {
                                const strategyItem = strategyList[index]
                                return <Card
                                    key={key}
                                    title={<Space>
                                        <strong>{strategyItem?.strategyName}</strong>
                                        <Popover
                                            placement="right"
                                            content={<div>
                                                <PreviewTime
                                                    {...strategyItem}
                                                />
                                            </div>}
                                            styles={{ body: { width: 300, overflow: 'hidden', overflowY: 'auto', maxHeight: 400 } }}
                                        >
                                            <a style={{ color: '#000' }}><QuestionCircleFilled /></a>
                                        </Popover>
                                    </Space>}
                                    style={{ background: '#fff', marginBottom: 10 }}
                                    hoverable
                                    id={`strategy_${index + 1}`}
                                    extra={<a
                                        style={{ padding: 2 }}
                                        onClick={() => setActiveKey(data => {
                                            if (data.includes(index)) {
                                                return data.filter(item => item !== index)
                                            }
                                            return [...new Set([...data, index])]
                                        })}
                                    >{activeKey.includes(index) ? <RightOutlined /> : <DownOutlined />}</a>}
                                    styles={{
                                        body: {
                                            transition: 'height 0.3s ease-in-out',
                                            overflow: 'hidden',
                                            height: !activeKey.includes(index) ? 'auto' : 0,
                                            padding: !activeKey.includes(index) ? '16px' : 0
                                        }
                                    }}
                                >
                                    <Form.Item
                                        {...restField}
                                        name={[name, 'groupObjectList']}
                                        rules={[{ required: true, message: '请新增群配置!' }]}
                                    >
                                        <AddGroupObject
                                            bookPlatForm={bookPlatForm}
                                            bookList={bookList}
                                            strategyList={strategyList}
                                            index={index}
                                            onCopy={(data, index) => {
                                                form.setFieldsValue({
                                                    strategyList: strategyList.map((item, i) => {
                                                        if (i === index - 1) {
                                                            const groupObjectList = item?.groupObjectList || []
                                                            groupObjectList.push(data)
                                                            return {
                                                                ...item,
                                                                groupObjectList
                                                            }
                                                        }
                                                        return item
                                                    })
                                                })
                                            }}
                                        />
                                    </Form.Item>
                                </Card>
                            })}
                        </>
                    )}
                </Form.List>
            </Form>
        </div>
    </Modal>
}

export default React.memo(SettingsGroupUser);