/*
 * @Author: your name
 * @Date: 2021-09-14 10:22:09
 * @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,
        getDepartmentRequest,
        departmentManagers,
        getDepartment,//获取责任单位
        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({});//清空默认值
        //重新获取数据
        tableRef?.current?.getTableRef().current?.reload();
    }

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

    const onModalVisibleChange = (visible: boolean) => {
        //表单弹窗
        //  console.log('uploadFormInitValue',restModelData.uploadFormInitValue);
        !visible && restModelData.setUploadFormInitValue(undefined);
        restModelData.setModalVisible(visible);

    }

    const uploadLedgerChangeHandle = (tabData: any) => {
        //台账上传类型选择回调

    }

    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 (restModelData.leafData) {
            const { responsibilityDepartmentId, responsibilityDepartmentName, responsibilityUserId, targetEvaluation, responsibilityUserName, accountType } = restModelData.leafData.reviewArticle;
            if (responsibilityDepartmentName && responsibilityDepartmentId) {

                articleManagement.setArticleSettingFormInit({
                    responsibilityDepartment: { label: responsibilityDepartmentName, value: responsibilityDepartmentId },
                    responsibilityUser: { label: responsibilityUserName, value: responsibilityUserId },
                    targetScores: { label: targetEvaluation, value: targetEvaluation },
                    articleType: { label: accountType, value: accountType },
                });
            }

            restModelData.getGradeOptions();  //获取可选档次
            restModelData.getAccoutTypeOptions(); //可选类型

        }

    }, [restModelData.leafData]);


    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
                }}
            >
                {
                    restModelData.modalVisible && (
                        //台账上传弹窗
                        <MccsModal title='台账上传' visible={restModelData.modalVisible}
                            onFinish={(values: any) => restModelData.uploadFile(values)}
                            initialValues={!restModelData.uploadFormInitValue ? {} : restModelData.uploadFormInitValue}
                            onVisibleChange={onModalVisibleChange}
                            params={restModelData.uploadFormInitValue}
                            request={(params: any) => {
                                return Promise.resolve(params)
                            }}
                        >
                            <div className='formItemTitle'>选择类型</div>
                            <Form.Item name='tab' rules={[
                                {
                                    required: true,
                                    message: '请选择类型！',
                                },
                            ]}>
                                <MccsClickableTabs
                                    //重新上传不允许更改类型
                                    disabled={(restModelData.uploadFormInitValue && JSON.stringify(restModelData.uploadFormInitValue) != '{}') ? true : false}
                                    type='multi'
                                    onChange={uploadLedgerChangeHandle}
                                    data={restModelData.uploadLedgerTypeList}
                                />
                            </Form.Item>
                            <ProFormDependency name={['tab']}>
                                {
                                    ({ tab }) => {
                                        //制度特殊处理
                                        return tab && tab.value.label == '制度' && (
                                            <ProFormSelect
                                                name="publicCateId"
                                                label="制度下类型"
                                                width='md'
                                                request={async () => await restModelData.getSelectableRuleChilds(tab.value.value)}
                                                placeholder="请选择"
                                                rules={[{ required: true, message: '请选择!' }]}
                                            />
                                        )
                                    }
                                }
                            </ProFormDependency>
                            <Form.Item name='files' rules={[
                                {
                                    required: true,
                                    message: '请上传文件！',
                                },
                            ]}>
                                <MccsUpload maxCount={10} />
                            </Form.Item>
                        </MccsModal>
                    )
                }

                <div style={{ display: 'flex', flexDirection: 'row', justifyContent: 'flex-start', width: '100%' }}>
                    <div style={{ height: '85vh', 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' }}>
                            <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