import { useEffect, useState, useContext } from 'react';
import { Form, Input, Checkbox, Button, Select, Steps, Tabs, InputNumber, Space, Switch, Breadcrumb, Modal } from 'antd';
import MenuTree from './MenuTree';
import './index.less';
import OrgContext from './org-context';
import apiObj from '@api/index';
import backIcon from "@images/back.png";

const { post, api, xPost } = apiObj;

const { Step } = Steps;
const { TabPane } = Tabs;
const { Option } = Select;
function AddSubOrg(props) {
    const [form] = Form.useForm();
    const [current, setCurrent] = useState(0);
    const [isChange, setIsChange] = useState(false);
    const [visible, setVisible] = useState(false);

    const { back } = props
    const { type } = useContext(OrgContext);
    const steps = [
        {
            title: '基础信息',
            content: 'First-content',
        },
        {
            title: '设置管理员',
            content: 'Second-content',
        },
        {
            title: '分配权限',
            content: 'Last-content',
        },
    ];

    const next = () => {
        setCurrent(current + 1);
        setIsChange(true)

    };
    const pre = () => {
        setCurrent(current - 1);
    };
    function handleOk() {
        back()
    }
    function handleCancel() {
        setVisible(false)
    }
    const goback = () => {
        if (form.isFieldsTouched()) {
            setVisible(true)
        } else {
            back()
        }
    };

    return (
        <>
            <Breadcrumb separator="">
                <Breadcrumb.Item><img className='back-icon' src={backIcon} onClick={goback} alt="返回上一页" /></Breadcrumb.Item>
                <Breadcrumb.Item>组织管理</Breadcrumb.Item>
                <Breadcrumb.Separator />
                <Breadcrumb.Item>新增子组织</Breadcrumb.Item>
            </Breadcrumb>
            <div className="add-container">
                <Steps current={current}>
                    {steps.map(item => (
                        <Step key={item.title} title={item.title} />
                    ))}
                </Steps>
                <div className="steps-content">
                    <StepContent current={current}
                        pre={pre}
                        next={next}
                        form={form}
                    />
                </div>
                <Modal
                    title="提示"
                    okText='确定'
                    cancelText='取消'
                    width={400}
                    visible={visible}
                    onOk={handleOk}
                    onCancel={handleCancel}
                >
                    <p>您还有内容未保存，确定要退出？</p>
                </Modal>
            </div>
        </>
    )
}

function StepContent(props) {

    const [treeDatas, setTreeDatas] = useState([]);
    const [tabDatas, setTabDatas] = useState([]);
    const [activeTab, setActiveTab] = useState('');
    const [sysCheckeds, setSysCheckeds] = useState([]);
    const [name, setName] = useState('');
    const [hisTypeList, setHisTypeList] = useState([]);
    const [orgType, setOrgType] = useState(localStorage.getItem('type'));
    const { type, save, detail } = useContext(OrgContext);
    const { current, pre, next, form } = props;
    const initialValues = detail
    const vilidateRules = {
        required: '${label}不能为空!',
        types: {
            email: '${label} is not a valid email!',
            number: '${label} is not a valid number!',
        },
    };

    //获取菜单数据
    function getTreeData() {
        xPost(api.getUserMenuResourceTree, { type: 0 }).then((res) => {
            if (res.data.code === 200) {
                const data = res.data.data;
                const treeDatas = structureTreeData(data);
                setTreeDatas(treeDatas);
                setTabDatas([treeDatas[0]]);
                setActiveTab(treeDatas[0].key);
                setName(treeDatas[0].title)
                setSysCheckeds(treeDatas[0] ? [treeDatas[0].key] : []);
            }

        })
    }
    function getStaticInfos() {
        post(api.getManagerBoxInfo).then((res) => {
            if (res.data.code === 200) {
                const data = res.data.data;
                const list = localStorage.getItem('type') == 4 ? data[45] : data[43]
                setHisTypeList(list)
            }
        })
    }
    //数据转换为树形结构所需字段
    function structureTreeData(data) {
        const arr = [];
        const checks = []
        let obj = {};
        data.map((it, i) => {
            obj = JSON.stringify(it.children).replace(/softwareMenuId/g, "key").replace(/menuName/g, 'title');
            arr[i] = {
                title: it.softwareName,
                key: it.softwareId,
                children: JSON.parse(obj)
            }
            checks[i] = it.softwareId
        });
        //form.setFieldsValue({softwares:[{id:arr[0]?[arr[0].key]:''}]});   //默认选中第一个
        return arr;
    }
    useEffect(() => {
        if (type == 2) {
            const treeDatas = detail.getRoleDTO ? structureTreeData(detail.getRoleDTO.loginUserMenuResourceTree) : [];
            setTabDatas(treeDatas);
            setSysCheckeds(detail.sids);
            getStaticInfos()
            setActiveTab(detail.softwares[0].id);
        } else {
            getTreeData();
            getStaticInfos()
        }
    }, []);
    function handlePre() {
        pre();
    }
    function handleNext() {
        const validateKeys = {
            0: ['parentId', 'name', 'code', ['addHospitalUserVO', 'name'], ['addHospitalUserVO', 'mobilePhone'], 'type', 'orderNo'],
            1: [['addHospitalUserVO', 'username'], ['addHospitalUserVO', 'password'], 'confirmPsd'],
        };
        form.validateFields(validateKeys[current]).then((res) => {
            next(form);
        });
    }
    function handleSave() {
        if (orgType == 4) {
            form.validateFields(['name']).then((res) => {
                save(form.getFieldsValue())
            });
        } else {
            form.validateFields([['softwares', 0, 'id'], ['softwares', 0, 'softwareMenuIds'], ['softwares', 0, 'softwareResourceIds']]).then((res) => {
                save(form.getFieldsValue())
            });
        }

    }
    //树形结构选中事件
    function checkTreeEvent(i, idsArr, sourceIds) {

        const formData = form.getFieldsValue();
        const arr = formData.softwares;
        arr[i] = {
            id: activeTab,
            name: name,
            softwareMenuIds: idsArr,
            softwareResourceIds: sourceIds
        };
        form.setFieldsValue({
            softwares: arr
        });

    }
    function onTabChange(activeTab) {
        setName(activeTab.split('-')[0])
        setActiveTab(activeTab.split('-')[1])
    }
    //开放系统勾选事件
    function softwareChange(checkedValue) {
        let arr = [], item;
        setSysCheckeds(checkedValue);
        for (let i = 0; i < checkedValue.length; i++) {
            item = treeDatas.find((it) => it.key === checkedValue[i]);
            if (item) {
                arr.push(item);
            }
        }
        setTabDatas(arr);
    }
    return (
        <>
            <Form
                labelCol={{ span: 6 }}
                wrapperCol={{ span: 16 }}
                layout="horizontal"
                validateMessages={vilidateRules}
                initialValues={initialValues}
                form={form}
            >
                <Form.Item
                    label="上级组织ID"
                    hidden={true}
                    name='parentId'>
                    <Input placeholder='请输入上级组织ID' autoComplete='off' />
                </Form.Item>
                <Form.Item
                    label="上级组织"
                    name='parentName'
                    hidden={current !== 0}
                    rules={[{ required: true }]}>
                    <Input disabled />
                </Form.Item>
                <Form.Item
                    label="组织名称"
                    name='name'
                    required
                    hidden={current !== 0}
                    rules={[() => ({
                        validator(_, value) {
                            if (!value) {
                                return Promise.reject(new Error('组织名称不能为空!'));
                            } else if (value.length < 51) {
                                return Promise.resolve();
                            }
                            return Promise.reject(new Error('格式错误!'));
                        },
                    }),]}>
                    <Input placeholder='请输入组织名称' autoComplete='off' />
                </Form.Item>
                <Form.Item
                    label="组织编码"
                    hidden={current !== 0}
                    name='code'>
                    <Input placeholder='请输入组织编码' autoComplete='off' />
                </Form.Item>
                <Form.Item
                    label="联系人"
                    hidden={current !== 0}
                    name={['addHospitalUserVO', 'name']}>
                    <Input placeholder='请输入联系人' autoComplete='off' />
                </Form.Item>
                <Form.Item
                    label="手机号码"
                    hidden={current !== 0}
                    name={['addHospitalUserVO', 'mobilePhone']}>
                    <Input placeholder='请输入手机号码' autoComplete='off' />
                </Form.Item>
                <Form.Item
                    label="类型"
                    name='type'
                    hidden={current !== 0}
                    rules={[{ required: true }]}>
                    {orgType == 4 ?
                        <Input placeholder='科室' disabled />
                        :
                        <Select placeholder='请选择类型'>
                            {hisTypeList.map((item, i) => {
                                return (
                                    <Option value={item.name} key={i}>{item.val}</Option>
                                )
                            })}
                        </Select>
                    }
                </Form.Item>
                {orgType == 4 ?
                    <Form.Item
                        label="病区"
                        name='regionId'
                        hidden={current !== 0}>
                        <Select placeholder='请选择类型'>
                            {hisTypeList.map((item, i) => {
                                return (
                                    <Option value={item.name} key={i}>{item.val}</Option>
                                )
                            })}
                        </Select>
                    </Form.Item> : null
                }
                <Form.Item
                    label="排序"
                    hidden={current !== 0}
                    name='orderNo'>
                    <InputNumber placeholder='大于0的整数' min={0} />
                </Form.Item>
                <Form.Item
                    label="用户名"
                    hidden
                    name={type == 2 ? ['addHospitalUserVO', 'id'] : ''}>
                    <Input placeholder='用户名是组织中唯一标识，请勿重复' autoComplete='off' disabled={type == 2 ? true : false} />
                </Form.Item>
                <Form.Item
                    label="用户名"
                    hidden={current !== 1}
                    name={['addHospitalUserVO', 'username']}
                    rules={type != 2 ? [{ required: true }] : null}>
                    <Input placeholder='用户名是组织中唯一标识，请勿重复' autoComplete='off' disabled={type == 2 ? true : false} />
                </Form.Item>
                <Form.Item
                    label="初始密码"
                    type="password"
                    hidden={current !== 1}
                    name={['addHospitalUserVO', 'password']}
                    rules={type != 2 ? [{ required: true }, {
                        min: 8,
                        message: '密码不能少于8个字符',
                    }, {
                        max: 12,
                        message: '密码不能大于12个字符',
                    }] : null}>
                    <Input placeholder='8-12位大小写字母、数字、特殊字符' autoComplete='off' disabled={type == 2 ? true : false} />
                </Form.Item>
                <Form.Item
                    label="确认密码"
                    type="password"
                    name='confirmPsd'
                    dependencies={['addHospitalUserVO', 'password']}
                    hidden={current !== 1}
                    rules={type != 2 ? [{ required: true }, ({ getFieldValue }) => ({
                        validator(_, value) {
                            if (!value || getFieldValue(['addHospitalUserVO', 'password']) === value) {
                                return Promise.resolve();
                            }
                            return Promise.reject(new Error('两次密码输入不一致!'));
                        },
                    })] : null}>
                    <Input placeholder='8-12位大小写字母、数字、特殊字符' autoComplete='off' disabled={type == 2 ? true : false} />
                </Form.Item>
                <Form.Item
                    label="开放系统"
                    type="password"
                    hidden={current !== 2}
                    rules={[{ required: true }]}>
                    <Checkbox.Group value={sysCheckeds} onChange={softwareChange}>
                        {
                            treeDatas.map((it, i) => {
                                return (
                                    <Form.Item key={it.key} noStyle>
                                        <Checkbox key={i} value={it.key}>{it.title}</Checkbox>
                                    </Form.Item>
                                )
                            })
                        }
                    </Checkbox.Group>
                </Form.Item>
                <Form.Item
                    label="菜单权限"
                    hidden={current !== 2}
                    required>
                    <Tabs onChange={onTabChange} type="card">
                        {
                            tabDatas.map((it, i) => {
                                return (
                                    <TabPane tab={it.title} key={it.title + '-' + it.key} forceRender={type == 2 ? true : false}>
                                        <Form.Item key={i} name={['softwares', i, 'softwareMenuIds']} noStyle>
                                            <MenuTree data={it} checkeds={form.getFieldValue().softwares ? form.getFieldValue().softwares[i] : []} checkEv={(checkedKeys, sourceIds) => checkTreeEvent(i, checkedKeys, sourceIds)} />
                                        </Form.Item>
                                        <Form.Item key={i + "a"} hidden={true} name={['softwares', i, 'id']} noStyle>
                                            <Input />
                                        </Form.Item>
                                        <Form.Item key={i + "b"} hidden={true} name={['softwares', i, 'softwareResourceIds']} noStyle>
                                            <Input />
                                        </Form.Item>
                                        <Form.Item key={i + "c"} hidden={true} name={['softwares', i, 'name']} noStyle>
                                            <Input />
                                        </Form.Item>
                                    </TabPane>
                                )
                            })
                        }
                    </Tabs>
                </Form.Item>
                <Form.Item
                    label="当前状态"
                    hidden={current !== 2}>
                    <Space>
                        <Form.Item
                            name='status'
                            valuePropName='checked'
                            getValueFromEvent={(checked) => {
                                return +checked + '';
                            }}
                            noStyle>
                            <Switch />
                        </Form.Item>
                        <span>启用</span>
                    </Space>
                </Form.Item>
            </Form>
            <div className="button-box">
                {current !== 0 && orgType != 4 ? <Button onClick={handlePre}>上一步</Button> : null}
                {current !== 2 && orgType != 4 ? <Button onClick={handleNext} type='primary'>下一步</Button> : null}
                {current === 2 || orgType == 4 ? <Button onClick={handleSave} type='primary'>保存</Button> : null}
            </div>
        </>
    )
}

export default AddSubOrg;