
/*
 * @Author: your name
 * @Date: 2021-09-14 10:22:09
 * @LastEditTime: 2022-04-29 14:23:05
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: /MedicalWisdomCheckSys/src/pages/GradeHospitalAccreditation/articleManagement/index.tsx
 */



import React, { useRef, useEffect, useState } from 'react'
import MccsPageContainer from '@/components/MccsPageContainer/index'
// import MccsProCard from '@/components/MccsProCard/index';
import { useModel } from 'umi';
import MccsFileTree from '@/components/MccsFileTree/index';
import MccsTable from '@/components/MccsTable/index';

import MccsClickableTabs from '@/components/MccsClickableTabs/index';
import MccsUpload from '@/components/MccsUpload/index';
import { MccsModal } from '@/components/MccsModal';


import { getDepartmentList } from './server';


import { getScoreLevelData } from '@/pages/PlatformMana/generalSetting/serve';


import { Form, Table, Space, Button, Switch, Select } from 'antd'
import {
    ProFormText,
    ProFormSelect,
    ProFormDependency,
} from '@ant-design/pro-form';

import './index.less';
import ArticleDetail from './components/articleDetailModule';
import MccsDrawerForm from '@/components/MccsDrawerForm/index';

const { Option } = Select;

type ArticleManagementProps = {
    //组件配置信息
    columnsFromProps?: {}[],
    headerConcig?: { [key: string]: any }, //配置参考ProPageContainer
    isModeTwo?: boolean

}

type SelectedRowsType = {
    [propsName: string]: any
}


export enum ActType {
    'NOACT',  //不操作
    'ADD',
    'EDIT',
    'DEL'
};

//条文管理
const ArticleManagement: React.FC<ArticleManagementProps> = (props) => {
    const { columnsFromProps = [], headerConcig, isModeTwo } = props;
    const { articleManagement } = useModel('allModels');

    const {
        isLeaf,
        treeData,
        getTableData,
        currentActivedTree,
        setCurrentActivedTree,
        scoreList,
        currentSelectedActObj,
        setdetailDrawerVisible,
        detailDrawerVisible,
        ...restModelData
    } = articleManagement;
    const tableRef = useRef<MccsTable.MccsTableRef>();


    const [defaultOpened, setDefaultOpened] = useState<string>();

    const [departments, setdepartments] = useState<{ label: string; value: string }[]>([]);
    

    const columns = [


        {
            key: 'keyword',
            hideInTable: true,
            renderFormItem: (item: any, { type }: any, form: any) => {

                if (type === 'form') {
                    return null;
                }
                return (
                    <Form.Item name='keyword'>
                        <ProFormText placeholder='条文/条款' />
                    </Form.Item>
                )
            },
        },
        {
            key: 'department',
            hideInTable: true,
            renderFormItem: (item: any, { type }: any, form: any) => {

                if (type === 'form') {
                    return null;
                }


                return (
                    <Form.Item name='department'>
                        <Select
                            showSearch
                            placeholder="请选择单位"
                        >
                            {
                                departments.map((item, index) => {
                                    return (
                                        <Option value={item.value} key={index}>{item.label}</Option>
                                    )
                                })
                            }
                        </Select>
                    </Form.Item>
                )
            },
        },
        {
            key: 'name',
            hideInTable: true,
            renderFormItem: (item: any, { type }: any, form: any) => {


                if (type === 'form') {
                    return null;
                }
                return (
                    <Form.Item name='name'>
                        <ProFormText placeholder='负责人' />
                    </Form.Item>
                )
            },
        },
        {
            key: 'selfEvaluation',
            hideInTable: true,
            renderFormItem: (item: any, { type }: any, form: any) => {

                if (type === 'form') {
                    return null;
                }
                return (
                    <ProFormSelect
                        name="selfEvaluation"
                        request={async () => {
                            const data = await getScoreLevelData();
                            if (!data) return [];
                            return data.map(item => ({ label: item.levelNumber, value: item.levelNumber }))
                        }}
                        placeholder="选择自评"
                        rules={[{ required: false }]}
                    />
                )
            },
        },
        {
            key: 'targetEvaluation',
            hideInTable: true,
            renderFormItem: (item: any, { type }: any, form: any) => {

                if (type === 'form') {
                    return null;
                }
                return (
                    <ProFormSelect
                        name="targetEvaluation"
                        request={async () => {
                            const data = await getScoreLevelData();
                            if (!data) return [];
                            return data.map(item => ({ label: item.levelNumber, value: item.levelNumber }))
                        }}
                        placeholder="选择目标"
                        rules={[{ required: false }]}
                    />
                )
            },
        },
        {
            title: '条款',
            key: 'numStr',
            dataIndex: 'numStr',
            hideInSearch: true,

        },
        {
            title: '条文',
            dataIndex: 'name',
            hideInSearch: true,
            width: '35%',
            ellipsis: true
        },
        {
            title: '负责单位',
            dataIndex: 'responsibilityDepartmentName',
            hideInSearch: true,
        },
        {
            title: '负责人',
            dataIndex: 'responsibilityUserName',
            hideInSearch: true,
        },
        {
            title: '自评',
            hideInSearch: true,
            dataIndex: 'selfEvaluation',
        },
        // {
        //     title: '现场查核',
        //     hideInSearch: true,
        //     dataIndex: 'siteEvaluation',
        // },
        {
            title: '目标',
            dataIndex: 'targetEvaluation',
            hideInSearch: true,
        },
        {
            title: '系统评分',
            dataIndex: 'systemEvaluation',
            hideInSearch: true,
        },
        {
            title: '操作',
            width: 100,
            valueType: 'option',
            render: (_: any, record: any) => {

                return [<a key="1" onClick={() => openDetailInDrawer(record)}>详情</a>]
            },
        },
    ]

    //左侧树搜索回调
    const searchHandle = (val: any) => {
        restModelData.getArticleTreeData(val);
    }

    const onSelectHandle = (data: MccsFileTree.childTree) => {
        //左侧树节点点击回调
        setCurrentActivedTree(data);
        restModelData.setCurrentSelectedActObj(data);
        articleManagement.setArticleSettingFormInit(undefined);//清空默认值
        //重新获取数据
        tableRef?.current?.getTableRef().current?.reload();
    }

    const batchSelfAssessment = (rowkeys: number[] | string[]) => {
        //批量设置
        restModelData.setDrawerFormType('BATCHSETTING');
        restModelData.setSelectedRowKeys(rowkeys);
        restModelData.setDrawerVisible(true);
    }


    const openDetailInDrawer = (record: any) => {
        // restModelData.setRecords(record)
        setdetailDrawerVisible(true);
        restModelData.setCurrentSelectedActObj(record);
        getTableData({ id: record.id});
    }

    const taizhangImplementationCommit = () => {
        //台账执行情况编辑结果提交
        restModelData.commitTaizhangImplementationHandle();
    }


    const getDepartments = async () => {

        const resp = await getDepartmentList();
        if (resp) {
            const { list = [] } = resp;
            setdepartments(list.map(t => ({ label: t.name, value: t.name })));
        }
    }


    useEffect(() => {

        if (restModelData.reloadRightContent) {
            //重新获取数据
            tableRef?.current?.getTableRef().current?.reload();
            tableRef?.current?.getTableRef().current?.clearSelected();
        }

    }, [restModelData]);


  


    useEffect(() => {
        if (isModeTwo) {
            //设置当前模块模式,台账上传共用时
            restModelData.setModuleMode(isModeTwo);
        } else {
            //设置当前模块模式
            restModelData.setModuleMode(false);
        }
    }, [props]);

    useEffect(() => {
        if (treeData.length > 0) {
            //默认展开书结构第一个结点
            //树结构组件会默认执行一遍onSelectHandle,将选中结点信息传出来
            const { id } = treeData[0];
            setDefaultOpened(`${id}`);
        }
    }, [treeData]);

    useEffect(() => {
        //页面加载完
        //获取左侧输结构
        restModelData.getArticleTreeData();
        //获取当前评分
        restModelData.getCurrentHospScore();

        getDepartments();

    }, [])



    return (
        <div className='ArticleManagement'>

            <MccsDrawerForm
                width={1000}
                visible={detailDrawerVisible}
                onVisibleChange={(bool: boolean) => setdetailDrawerVisible(bool)}
                submitter={false}
            >
                <ArticleDetail  />
            </MccsDrawerForm>


            <MccsPageContainer
                config={headerConcig ? headerConcig : {
                    content: !isModeTwo && <div style={{ textAlign: 'right', fontSize: 12, color: '#525866' }}>{restModelData.currentHospSelfScoreAndOthers}</div>,
                    footer: restModelData.editMode ? [
                        <Button key="3" onClick={() => restModelData.setEditMode(false)}>取消</Button>,
                        <Button key="2" type="primary" onClick={() => taizhangImplementationCommit()}>
                            保存
                        </Button>,
                    ] : null
                }}
            >

                <div style={{ display: 'flex', flexDirection: 'row', justifyContent: 'flex-start', width: '100%' }}>
                    <div style={{ height: 'calc(100vh - 88px)', width: restModelData.editMode ? 0 : '25%', transition: 'width 0.2s ease-in', padding: '16px', backgroundColor: '#fff', marginRight: '16px', boxSizing: 'border-box' }} >
                        {
                            defaultOpened && (
                                <MccsFileTree
                                    treeData={treeData}
                                    defaultSelected={defaultOpened}
                                    onSelectHandle={onSelectHandle}
                                    searchHandle={searchHandle}
                                    renderFilter={() => {
                                        //只在台账上传时展示
                                        return isModeTwo ? (
                                            <div className='onlyMyselfFilter'>
                                                <span>只看我的</span>
                                                <Switch size='small' onChange={(checked) => restModelData.setIsShowMineOnly(checked)} />
                                            </div>
                                        ) : null
                                    }}
                                    editable={false}
                                />
                            )
                        }
                    </div>
                    <div style={{ padding: 0, width: restModelData.editMode ? '100%' : '75%', transition: 'width 0.2s ease-in' }}>
                        <div className='card' style={{ display: currentActivedTree?.isLeaf ? 'none' : 'block',height:'calc(100vh - 88px)'}}>
                            <MccsTable
                                ref={tableRef}
                                columns={columnsFromProps.length > 0 ? columnsFromProps : columns}
                                request={getTableData}
                                search={{
                                    span: 6
                                }}
                                rowSelection={isModeTwo ? false : {
                                    // 自定义选择项参考: https://ant.design/components/table-cn/#components-table-demo-row-selection-custom
                                    // 注释该行则默认不显示下拉选项
                                    selections: [Table.SELECTION_ALL, Table.SELECTION_INVERT],
                                }}
                                rowKey="id"
                                tableAlertOptionRender={({ selectedRowKeys, selectedRows, onCleanSelected }: { selectedRowKeys: number[] | string[], selectedRows: SelectedRowsType[], onCleanSelected: () => void }) => {
                                    return (
                                        <Space size={16}>
                                            <Button type='primary' onClick={() => batchSelfAssessment(selectedRowKeys)}>批量设置</Button>
                                            <Button type='ghost' onClick={onCleanSelected}>取消选择</Button>
                                        </Space>
                                    );
                                }}
                            // searchNode={searchNode()}
                            />
                        </div>
                        <div style={{ display: currentActivedTree?.isLeaf ? 'block' : 'none' }}>
                            <ArticleDetail isModeTwo={isModeTwo} />
                        </div>
                    </div>
                </div>
            </MccsPageContainer>
        </div>
    )
}

export default ArticleManagement