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

const {post,api,xPost} = apiObj;

const { TabPane } = Tabs;
const { Option } = Select;
function AddRole(props){
    const [form] = Form.useForm();
    const { back } = props;
    const [isChange, setIsChange] = useState(false);
    const [visible, setVisible] = useState(false);
    const { detail } = useContext(RoleContext);
    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">
                <ContentForm back={goback} form={form}></ContentForm>
            </div>
            <Modal
                title="提示"
                okText='确定'
                cancelText='取消'
                width={400}
                visible={visible}
                onOk={handleOk}
                onCancel={handleCancel}
            >
                <p>您还有内容未保存，确定要退出？</p>
            </Modal>
        </>
    )
}

function ContentForm(props){
    const [treeDatas, setTreeDatas] = useState([]);
    const [tabDatas, setTabDatas] = useState([]);
    const [activeTab, setActiveTab] = useState('');
    const { save,detail }  = useContext(RoleContext);
    const [sysCheckeds, setSysCheckeds] = useState();
    const { back, form } = props;
    const initialValues=detail||{
        status:'1'
    };
    
    const vilidateRules = {
        required: '${label}不能为空!',
        types: {
            email: '${label} is not a valid email!',
            number: '${label} is not a valid number!',
        },
    };

    //获取菜单数据，type：组织0角色1
    function getTreeData(){
        xPost(api.getUserMenuResourceTree,{type:1}).then((res)=>{
            if(res.data.code===200){
                const data = res.data.data;
                const treeDatas = structureTreeData(data);
                setTreeDatas(treeDatas);
                //默认选中第一个tab
                setTabDatas([treeDatas[0]]);
                setActiveTab(treeDatas[0].key);
                setSysCheckeds(treeDatas[0]?[treeDatas[0].key]:[]);

                
            }

        })
    }
    //数据转换为树形结构所需字段
    function structureTreeData(data){
        const arr = [];
        let obj={};
        data.relation ==1 || 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)
            }
        });
        return arr;
    }
    //数据转换为树形结构所需字段
    function structureTreeData2(data) {
        const arr = [];
        let obj = {};
        data.map((it, i) => {
            if (it.relation == 1){
                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)
                }
            }
            
        });
        return arr;
    }
    useEffect(()=>{
        if(detail){
        //编辑时权限树从详情中获取，tab数据也是
            const treeDatas2 = structureTreeData2(detail.loginUserMenuResourceTree);
            const treeDatas = structureTreeData(detail.loginUserMenuResourceTree);
            setTreeDatas(treeDatas);
            setSysCheckeds(detail.sids);
            setTabDatas(treeDatas2);
            console.log(detail);
            console.log(form.getFieldsValue());
        }else{
            getTreeData();
        }

    },[]);
    function handleSave(){
        form.validateFields(['name']).then((res)=>{
            save(form.getFieldsValue())
        });

    }
    //树形结构选中事件
    function checkTreeEvent(i,idsArr,sourceIds){
        const formData=form.getFieldsValue();
        let arr=formData.softwares;
        arr[i]={
            id:activeTab,
            softwareMenuIds:idsArr,
            softwareResourceIds:sourceIds
        };
        form.setFieldsValue({
            softwares:arr
        });
    }
    function onTabChange(activeTab){ 
        setActiveTab(activeTab.split('-')[0])
    }
    //开放系统勾选事件
    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="角色名称"
                name='name'
                required
                rules={[({ getFieldValue }) => ({
                    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="角色描述"
                name='remark'>
                <Input placeholder='请输入角色描述' autoComplete='off'/>
            </Form.Item>
            <Form.Item
                label="排序"
                name='orderNo'>
                <InputNumber placeholder='大于0的整数' min={0}/>
            </Form.Item>
            <Form.Item
                label="开放系统"
                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="菜单权限"
                required>
                <Tabs onChange={onTabChange} type="card">
                    {
                        tabDatas.map((it,i)=>{
                            return (
                                <TabPane tab={it.title} key={it.key + "-" + i} forceRender={detail ? true : false}>
                                    <Form.Item
                                        key={i}
                                        name={['softwares', i, 'softwareMenuIds']}
                                        valuePropName='checked'
                                        getValueFromEvent={(checked)=>{
                                            return [];
                                        }} 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>
                                </TabPane>
                            )
                        })
                    }
                </Tabs>
            </Form.Item>
            <Form.Item
                label="当前状态">
                <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">
                <Button onClick={back}>取消</Button>
            <Button onClick={handleSave} type='primary'>保存</Button>
        </div>
        
        </>
    )
}

export default AddRole;