import { useEffect, useState } from 'react';
import {  Breadcrumb, Form, Radio, Input, Button, Tabs } from 'antd';
import { DownOutlined, PlusOutlined } from '@ant-design/icons';
import Quill from 'quill';
import SelectedTag from '@common/SelectedTag.js';
import MyDeptStruct from '@common/MyDeptStruct.js';
import UserList from './UserList';
import './index.less';
import "quill/dist/quill.snow.css";
import backIcon from "@images/back.png";
import apiObj from '@api/index';
import {message} from "antd/lib/index";
const { post, api } = apiObj;
const { TabPane } = Tabs;
function AddNewMsg(props) {
    const {goBack} = props;
    const [form] = Form.useForm();
    const initialValues={receiveType:0,type:1,sendUsers:[],sendDepts:[],sendHospitals:[]};
    const [showCustom,setShowCustom] = useState(false);     //是否显示自定义内容
    const [checkedUser, setCheckedUser] = useState([]);   //指定用户选中项
    const [checkedUserIds, setCheckedUserIds] = useState([]);   //指定用户选中项id
    const [checkedDepts, setCheckedDepts] = useState([]);   //指定科室选中项
    const [checkedDeptIds, setCheckedDeptIds] = useState([]);   //指定科室选中的科室项id
    const [checkedHosIds, setCheckedHosIds] = useState([]);   //指定科室选中的医院项id
    const [checkedTreeItems, setCheckedTreeItems] = useState([]);   //指定科室选中的树结构
    const [receiverError,setReceiverError]=useState(false);   //接收者校验状态


    useEffect(() => {
        initQuillEditor();

    }, []);
    //初始化quill富文本编辑器
    function initQuillEditor(){
        var toolbarOptions = [
            ['bold', 'italic', 'underline', 'strike'], // toggled buttons
            ['blockquote', 'code-block'],

            [{ 'header': 1 }, { 'header': 2 }], // custom button values
            [{ 'list': 'ordered'}, { 'list': 'bullet' }],
            [{ 'script': 'sub'}, { 'script': 'super' }], // superscript/subscript
            [{ 'indent': '-1'}, { 'indent': '+1' }], // outdent/indent
            [{ 'direction': 'rtl' }], // text direction

            [{ 'size': ['small', false, 'large', 'huge'] }], // custom dropdown
            [{ 'header': [1, 2, 3, 4, 5, 6, false] }],

            [{ 'color': [] }, { 'background': [] }], // dropdown with defaults from theme
            [{ 'font': [] }],
            [{ 'align': [] }],

            ['clean'], // remove formatting button
            ['chord'],
            ['play']
        ];
        const editor = document.getElementById('editor');
        let quill = new Quill(editor,{
            modules:{
                toolbar: {
                    container: toolbarOptions,
                }
            },
            theme:'snow'
        });
        //注册事件
        quill.on('selection-change',(range)=>{
            if(range===null){       //为空代表失焦
                console.log(quill.root.innerText)
                const content = quill.root.innerHTML;
                form.setFieldsValue({content:content});
                //console.log(quill.getContents(),quill.root.innerHTML);
            }
        })
    }

    //发送消息
    function validateForm(){
        console.log(form.getFieldsValue())
        form.validateFields().then((values)=>{
            if(!receiverError){
                sendMsg(values)
            }
        }).catch((error)=>{
            console.log('验证失败',error)
        })
    }
    //发送消息
    function sendMsg(values){
        post(api.noticeAdd,values).then((res)=>{
            const data = res.data;
            if(data.code===200){
                message.success(data.message || '操作成功');
            }else{
                message.warning(data.message || '操作失败');
            }
        })
    }
    //类型切换
    function onTypeChange(){

    }
    //接收者类型切换
    function onReceiveTypeChange(e){
        const val = e.target.value;
        setShowCustom(val===1);
        //是否自定义选中者为空
        const isCusEmpty = val===1&&(checkedUser.length+checkedDepts.length)===0;
        setReceiverError(isCusEmpty);
    }
    //切换tab
    function handleTabChange(){

    }
    //选中用户
    function handleTableCheck(userIdArr,userArr){
        setCheckedUser(userArr);
        setCheckedUserIds(userIdArr);
        form.setFieldsValue({sendUsers:userIdArr});
        validateReceiver(userIdArr.length+checkedDeptIds.length+checkedHosIds.length);
    }
    //验证接收者是否为空
    function validateReceiver(len){
        if(len===0){
            setReceiverError(true)
        }else{
            setReceiverError(false)
        }

    }
    //选中科室
    function handleCheckDept(checks,e){
        setCheckedTreeItems(checks);
        //排序，短的在前长的在后，为去重做准备
        const posArr = [...e.checkedNodesPositions].sort((a,b)=>{
            return a.pos.length-b.pos.length;
        });
        //console.log('排序后：',posArr);
        const checkedDepts = structureDeptTag(posArr);
        let deptIdsArr=[...checkedDepts.deptIds];
        let deptArr=[...checkedDepts.deptObj];
        let hosIdsArr=[...checkedDepts.hosIds];
        let hosArr=[...checkedDepts.hosObj];
        setCheckedDepts(hosArr.concat(deptArr));        //显示的排序可能需要再考虑一下
        setCheckedDeptIds(deptIdsArr);
        setCheckedHosIds(hosIdsArr);
        validateReceiver(checkedUserIds.length+deptIdsArr.length+hosIdsArr.length);
        form.setFieldsValue({sendDepts:deptIdsArr,sendHospitals:hosIdsArr});
    }
    //格式化选中科室数据
    function structureDeptTag(pos){   //全选传医院id，非全选传科室id
        let tempPos=[],hosIds=[],hosArr=[],len=0,deptIds=[],deptArr=[],temp=[],tempKey='';
        let it=null,checks=[];
        for(let i=0;i<pos.length;i++){
            it=pos[i];
            tempKey=it.node.key;
            if(it.pos==='0-0'){     //全选了平台，终止遍历
                temp = tempKey.split("-");
                hosArr.push({id:temp[0],name:temp[1],key:tempKey});
                hosIds.push(temp[0]);
                setCheckedTreeItems([tempKey]);
                return {hosIds:hosIds,hosObj:hosArr,deptIds:deptIds,deptObj:deptArr};
            }
            //如果当前节点的pos包含了tempPos里的某个数据，说明该节点的父节点已被选中并记录，自身则不需要记录
            if(!(tempPos.includes(it.pos.substr(0,5))||tempPos.includes(it.pos.substr(0,7)))){
                tempPos.push(it.pos);       //记录需要展示的节点pos,作为去重的依据
                temp = tempKey.split("-");
                len=temp.length;
                //记录选中的节点id,从已选中标签中删除时控制树形结构选中状态用
                checks.push(tempKey);
                setCheckedTreeItems(checks);
                //医院id存入sendHospitals，科室id存入sendDepts
                if(len===2){
                    hosArr.push({id:temp[0],name:temp[1],key:tempKey});
                    hosIds.push(temp[0]);
                }else{
                    deptArr.push({id:temp[2],name:temp[1]+"-"+temp[3],key:tempKey});
                    deptIds.push(temp[2]);
                }

            }
        }
        return {hosIds:hosIds,hosObj:hosArr,deptIds:deptIds,deptObj:deptArr};
    }
    //删除已选用户/科室
    function handleTagDel(idx,type){ //type=1指定用户，type=2指定科室
        if(idx===undefined){    //无入参，清空所有
            //情况树状结构选中状态
            setCheckedTreeItems([]);
            //清空用户
            setCheckedUser([]);
            setCheckedUserIds([]);
            //清空科室
            setCheckedDepts([]);
            setCheckedDeptIds([]);
            setCheckedHosIds([]);
            form.setFieldsValue({sendUsers:[],sendDepts:[],sendHospitals:[]});
            //校验状态更新
            setReceiverError(true);
            return;
        }
        //const idx=checkedUserIds.findIndex((it)=>it===id);
        if(type===1){
            let checkedIdsArr=[...checkedUserIds];
            let checkedUserArr=[...checkedUser];
            checkedIdsArr.splice(idx,1);
            checkedUserArr.splice(idx,1);
            setCheckedUser(checkedUserArr);
            setCheckedUserIds(checkedIdsArr);
            form.setFieldsValue({sendUsers:checkedIdsArr});
            //校验状态更新--在判断外面不好判断，直接放里面
            setReceiverError(checkedIdsArr.length+checkedDepts.length===0);
        }else if(type===2){
            //删除树结构中对应的选中状态
            const ikey = checkedDepts[idx].key;
            const tempItems = [...checkedTreeItems];
            const index = tempItems.findIndex((it)=>it===ikey);
            tempItems.splice(index,1);
            setCheckedTreeItems(tempItems);
            //console.log(ikey,index,checkedDepts,checkedTreeItems,tempItems)
            //删除对应的显示数据及传参数据
            let checkedDeptsArr=[...checkedDepts];
            let checkedHosIdsArr=[...checkedHosIds];
            let checkedDeptIdsArr=[...checkedDeptIds];
            checkedDeptsArr.splice(idx,1);
            checkedHosIdsArr.splice(idx,1);
            checkedDeptIdsArr.splice(idx-checkedHosIdsArr.length,1);
            setCheckedDepts(checkedDeptsArr);            //选中的科室和医院合并过的
            setCheckedHosIds(checkedHosIdsArr);
            setCheckedDeptIds(checkedDeptIdsArr);
            form.setFieldsValue({sendUsers:checkedUserIds,sendDepts:checkedDeptIdsArr,sendHospitals:checkedHosIdsArr});
            //校验状态更新--在判断外面不好判断，直接放里面
            setReceiverError(checkedUserIds.length+checkedDeptsArr.length===0);
        }
        //校验状态更新
        //setReceiverError(checkedUserIds.length+);
    }
    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-msg-container'>
            <Form form={form}
                  scrollToFirstError={true}
                  initialValues={initialValues}
                  labelCol={{ span: 2 }}
                  layout="horizontal">
                <Form.Item name='type' label='类型' required>
                    <Radio.Group onChange={onTypeChange}>
                        <Radio value={1}>公告</Radio>
                        <Radio value={2}>其他</Radio>
                    </Radio.Group>
                </Form.Item>
                <Form.Item name='title'
                           label='标题'
                           required
                           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='输入50字以内标题' autoComplete='off'/>
                </Form.Item>
                <Form.Item name='content'
                           label='内容'
                           required
                           rules={[() => ({
                           validator(_, value) {
                               if(!value){
                                   return Promise.reject(new Error('内容不能为空!'));
                               }else{
                                   return Promise.resolve();
                               }
                           },
                        }),]}>
                    <div className="ql-snow">
                        <div id='editor'></div>
                    </div>
                </Form.Item>
                <Form.Item name='content' hidden>
                    <Input autoComplete='off'/>
                </Form.Item>
                <Form.Item name='receiveType'
                           label='接收者'
                           required>
                    <Radio.Group onChange={onReceiveTypeChange}>
                        <Radio value={0}>所有人</Radio>
                        <Radio value={1}>自定义</Radio>
                    </Radio.Group>
                </Form.Item>
                {receiverError?<p className='receive-error'>接收者不能为空!</p>:''}
                <Form.Item name='sendUsers' hidden>
                    <Input autoComplete='off'/>
                </Form.Item>
                <Form.Item name='sendDepts' hidden>
                    <Input autoComplete='off'/>
                </Form.Item>
                <Form.Item name='sendHospitals' hidden>
                    <Input autoComplete='off'/>
                </Form.Item>
            </Form>
            <div className="receive-container" style={{display:showCustom?'block':'none'}}>
                <SelectedTag userData={checkedUser} deptData={checkedDepts} delTag={handleTagDel}></SelectedTag>
                <div className="user-type-box">
                    <Tabs defaultActiveKey="1" onChange={handleTabChange}>
                        <TabPane tab="指定用户" key="1">
                            <UserList setChecked={handleTableCheck} checkedIds={checkedUserIds}></UserList>
                        </TabPane>
                        <TabPane tab="指定科室" key="2">
                            <MyDeptStruct checkEv={handleCheckDept} checkeds={checkedTreeItems}></MyDeptStruct>
                        </TabPane>
                    </Tabs>
                </div>
            </div>
            <div className="button-box">
                <Button onClick={goBack}>取消</Button>
                <Button onClick={validateForm} type='primary'>发送</Button>
            </div>
        </div>
            </>)
}

export default AddNewMsg;