import React, { useState, useRef, useEffect } from 'react';
import { Modal, Button, AutoComplete, Input, Avatar, Tooltip, message, Form, TreeSelect } from 'antd';
import { connect } from "react-redux";

import { getTagByKeywordAndCreator, batchAddTagResource, getSupportTagForm, saveTag,newbatchAddTagResource } from '../../../../service/TagService';

import './AddTagModal.less';
import TreeSelectItem from './TreeSelectItem';

const { TextArea } = Input;

const AddTagModal = (props) => {
    const { visible, onCancel, id, type, creator,callback } = props;
    const [form] = Form.useForm();

    const [ step, setStep ] = useState(0);
    const [ keyword, setKeyword ] = useState('');
    const [ selectTag, setSelectTag ] = useState(null);
    const [ matchTags, setMatchTags ] = useState([]);
    const [ options, setOptions ] = useState();
    const [ confirmLoading, setConfirmLoading ] = useState(false);
    const [ description, setDescription ] = useState('');
    const [ tagFormData, setTagFormData ] = useState({});
    const [selectTags,setSelectTags] = useState([])

    const getTagByKeyword = (value=keyword) => {
        getTagByKeywordAndCreator({
            keyword: value,
            creator: creator||'',
            resourceType:type,
        }, data => {
            setMatchTags(data?.data||[]);

            let tagExsit = false, _selectTag = null;
            const _options = [];
            (data?.data||[]).forEach(item => {
                _options.push({
                value: item.tagId,
                label: (
                    <div
                        style={{
                            display: 'flex',
                            justifyContent: 'space-between',
                        }}
                    >
                        {item.name||''}
                        <Avatar 
                            shape="square" 
                            size="small"
                            title={item.type==='public'?'公共标签':'个人标签'}
                        >
                            {item.type==='public'?'公':'个'}
                        </Avatar>
                    </div>
                )
                });

                if (value==='' || item.name===value) {
                    tagExsit = true;
                }

                if (item.name === value) {
                    _selectTag = item;
                }

            })

            if (!tagExsit) {
                _options.push({
                    value: -1,
                    label: (
                        <a >{`创建 ${value||''}`}</a>
                    )
                })
            }

            setSelectTag(_selectTag);
            setOptions(_options);
        })
    }

    const onOk = () => {
        if (selectTags.length===0) {
            message.warning('请先填写标签');
            return;
        }

        if (selectTags.length>0) {
            setConfirmLoading(true);
            newbatchAddTagResource({
                tagIds: selectTags.join(','),
                resourceIds: id,
                type,
                creator: creator||''
            }, () => {
                reset();
                onCancel && onCancel(true);
                callback?.()
                setSelectTags([])
            }, () => {
                setConfirmLoading(false);
            })
        } else {
            getTagForm();
        }
    }

    const cancel = () => {
        reset();
        onCancel && onCancel();
    }

    const onBack = () => {
        setStep(0);
    }

    const onCreate = () => {
        form.validateFields().then((data)=>{
            setConfirmLoading(true);
            let saveData = JSON.parse(JSON.stringify(tagFormData))
            for (let item of saveData.targetParameters){
                item.value = String(data[item.name])
            }
            
            saveTag(false,saveData,(data)=>{
                batchAddTagResource({
                    tagId: data?.data?.id,
                    resourceIds: id,
                    type,
                    creator: creator||''
                }, () => {
                    reset()
                    onCancel && onCancel(true);
                }, () => {
                    setConfirmLoading(false);
                })
            },(err)=>{

                setConfirmLoading(false);
                console.log("err",err)
            })
        })  
    }

    const onFocus = () => {
        getTagByKeyword();
    }

    const onKeywordChange = (value) => {
        //匹配行被选中时 跳过
        if (value!==undefined && value!==null && typeof(value)!=='string') return;

        setSelectTag(null);
        setKeyword(value||'');
        getTagByKeyword(value||'');
    }

    //获取新增标签表单
    const getTagForm = async ()=>{
        setConfirmLoading(true);
        getSupportTagForm({
            isDefault: false,
            type: 'private',
            creator: creator||''
        }, data => {
            const _tagForm = data?.data||{};
            setTagFormData(_tagForm)
            form.resetFields()
            setConfirmLoading(false);
            setStep(1);
        }, () => {
            setConfirmLoading(false);
        })
    }

    const onSelect = async (value, option) => {
        if (value!==-1) {
            let _selectTag = null;

            matchTags.forEach(item => {
                if (item.tagId === value) {
                    _selectTag = item;
                }
            })

            setSelectTag(_selectTag);
            setKeyword(_selectTag.name||'');
        } else {
            setSelectTag(null);
            getTagForm()
        }
    }

    const onDescriptionChange = (e) => {
        setDescription(e.target.value);
    }

    const reset = () => {
        setConfirmLoading(false);
        setStep(0);
        setSelectTag(null);
        setKeyword('');
    }


    let footer = [];

    if (step === 0) {
        footer = [ 
            <Button
                key="0" 
                onClick={cancel}
            >
            取消
            </Button>,
            <Button
                key="1" 
                type="primary"
                loading={confirmLoading}
                onClick={onOk}
                // disabled={keyword===''}
            >
            确定
            </Button>
        ];
    } else if (step === 1) {
        footer = [ 
            <Button
                key="0" 
                onClick={onBack}
            >
            返回
            </Button>,
            <Button
                key="1" 
                type="primary"
                loading={confirmLoading}
                onClick={onCreate}
            >
            创建
            </Button>
        ];
    }

    const formItemLayout = {
        labelCol: {
            xs: { span: 24 },
            sm: { span: 4 },
        },
        wrapperCol: {
            xs: { span: 24 },
            sm: { span: 20 },
        },
    };

    const newTreeData = (data) =>{
        let box = []
        for (let item of data){
            let node = {title:item.name,value:item.idString}

            if(item.children&&item.children[0]){
                node.children = newTreeData(item.children)
            }
            box.push(node)

        }
        return box
    }

    return (
        <Modal 
            className='add-tag-modal'
            forceRender
            visible={visible}
            title={(step===0)?'选择标签':`创建${keyword}`}
            width={520}
            onCancel={cancel}
            footer={footer}
        >
            {/* {
            step === 0 && <AutoComplete
                style={{ width: '100%' }}
                allowClear 
                value={keyword}
                onChange={onKeywordChange}
                onFocus={onFocus}
                options={options}
                onSelect={onSelect}
            />
            } */}
            {
                step===0&&<TreeSelectItem session={{user:{userName:creator}}} resourceType={type} selectTags={selectTags} setSelectTags={setSelectTags} />
            }
            {
            step === 1 && <Form 
                {...formItemLayout}
                form={form}
            >
                {tagFormData&&tagFormData.targetParameters&&tagFormData.targetParameters[0]?
                    tagFormData.targetParameters.map((item,key)=>{
                        if(item.name==='catalogId'){
                            return(
                                <Form.Item 
                                    label={item.cnName} 
                                    name={item.name}
                                    rules={[{ required: item.required, message: `请选择${item.cnName}!` }]}
                                    key={`tagFormData${key}`}
                                >
                                    <TreeSelect
                                        style={{ width: '100%' }}
                                        dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                                        treeData={newTreeData(item.tagCatalogNode.children)}
                                        treeDefaultExpandAll
                                    />
                                </Form.Item>
                            )
                        }else if(item.name==='usable'){
                            return(
                                <Form.Item 
                                    label={item.cnName} 
                                    name={item.name}
                                    rules={[{ required: item.required, message: `请选择${item.cnName}!` }]}
                                    initialValue="1"
                                    style={{display:'none'}}
                                    key={`tagFormData${key}`}

                                >
                                    <Input  disabled />
                                </Form.Item>
                            )
                        }else if(item.name==='name'){
                            return(
                                <Form.Item 
                                    label={item.cnName} 
                                    name={item.name}
                                    rules={[{ required: item.required, message: `请输入${item.cnName}!` }]}
                                    initialValue={keyword}
                                    key={`tagFormData${key}`}
                                >
                                    <Input disabled />
                                </Form.Item>
                            )
                        }else {
                            return(
                            <Form.Item 
                                label={item.cnName} 
                                name={item.name}
                                rules={[{ required: item.required, message: `请输入${item.cnName}!` }]}
                                key={`tagFormData${key}`}

                            >
                                <Input />
                            </Form.Item>
                        )
                        }

                    })
                :''}
            </Form>
            }
        </Modal>
    )
}

export default AddTagModal;