/*
 * @Author: your name
 * @Date: 2021-09-23 08:49:14
 * @LastEditTime: 2022-01-05 14:54:32
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: /MedicalWisdomCheckSys/src/pages/DataManagement/publicData/index.tsx
 */


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

import './index.less'

import { Form, Table, Space, Button, Popconfirm} from 'antd'
import 'moment/locale/zh-cn';
import locale from 'antd/es/date-picker/locale/zh_CN';


import {
    ProFormText,
    ProFormSelect,
    ProFormDateRangePicker,
} from '@ant-design/pro-form';

type PublicDataType = {

}

type SelectedRowsType = Record<string, any>

const PublicData: React.FC<PublicDataType> = (props) => {

    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: 'date',
            hideInTable: true,
            renderFormItem: (item: any, { type }: any, form: any) => {

                if (type === 'form') {
                    return null;
                }
                return (
                    <ProFormDateRangePicker fieldProps={{ format: 'yyyy-MM-DD',locale }} placeholder={['开始时间', '结束时间']} />
                )
            },
        },
        {
            title: 'ID',
            key: 'id',
            dataIndex: 'id',
            hideInSearch: true,
            width: '10%'
        },
        {
            title: '文件名称',
            key: 'fileName',
            dataIndex: 'fileName',
            hideInSearch: true,
            width: '30%',
            ellipsis:true,
        },
        {
            title: '添加时间',
            key: 'createDateTime',
            dataIndex: 'createDateTime',
            hideInSearch: true,
            width: '20%'
        },
        {
            title: '关联条款',
            key: 'articles',
            hideInSearch: true,
            ellipsis:true,
            width:'20%',
            dataIndex: 'articles',
            render: (_: any, record: any) => {
                //    console.log({record});
                const { articlesList = [] } = record;
                return (articlesList.map((t: any) => t.numStr)).join(',');
            }
        },
        {
            title: '操作',
            width: '180px',
            valueType: 'option',
            render: (_: any, record: any) => {
                // console.log({record});
                const { ruleStatus, fileUrl } = record;
                const arr = [
                    <a key="1" href={fileUrl} >预览</a>,
                    <Popconfirm
                        title="是否确定删除?"
                        onConfirm={()=>delFileHandle(record)}
                        onCancel={()=>{}}
                        okText="确定"
                        key="2"
                        cancelText="取消"
                    >
                        <a  >删除</a>
                    </Popconfirm>
                ]
                // 1 展示 0掩藏
                return ruleStatus == 0 ? [...arr] : [<a key="3"
                    onClick={() => {
                        setSelectedFiles([record]);
                        connectHandle(record)
                    }}>关联条款</a>, ...arr]
            },
        },
    ];

    const drawerTableColumns = [
        {
            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>
                )
            },
        },
        {
            title: 'ID',
            key: 'id',
            dataIndex: 'id',
            hideInTable: true,
            hideInSearch: true,
        },
        {
            title: '四码',
            key: 'numStr',
            dataIndex: 'numStr',
            hideInSearch: true,
            width: '30%'
        },
        {
            title: '四码细则名',
            key: 'name',
            dataIndex: 'name',
            hideInSearch: true,
            width: '70%',
            ellipsis: true
        },
    ]

    const tableRef = useRef<MccsTable.MccsTableRef>();

    const [actionType, setActionType] = useState('add');

    const [MccsModalVisible, setMccsModalVisible] = useState(false);

    const [treeDataModelInit, setTreeDataModelInit] = useState<{ name: string, cateType: number }>();

    const [drawerVisible, setDrawerVisible] = useState(false);

    const [selectedRowIds, setSelectedRowIds] = useState<number[]>([]); // 条文id

    const [selectedFiles, setSelectedFiles] = useState<any[]>([]);  // 文件id

    const [uploadModalVisible, setUploadModalVisible] = useState(false);

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


    const { publicData } = useModel('allModels', model => {
        return { publicData: model.publicData };
    });

    // 搜索回调
    const searchHandle = (val: any) => {
        publicData.getTreeData(val);
    }

    const onSelectHandle = (data: SelectedTreeDataType) => {
        publicData.setCurrentActivedTree(data);
        // 重新获取数据
        tableRef?.current?.getTableRef().current?.reload();
    }

    const MccsModalVisibleChangeHandle = (bool: boolean) => {
        !bool && setTreeDataModelInit(undefined)
        setMccsModalVisible(bool);
    }

    const connectHandle = (records?: any) => {
        // 关联条款 records传参解决useState异步拿不到数据
        let defaultSelectedAccreditation: number[] = []; // 默认选中的条文

        if (!records) {
            selectedFiles.map((item: any) => {
                const { articlesList = [] } = item;
                const arr = articlesList.map((t: any) => t.ruleId);
                defaultSelectedAccreditation = defaultSelectedAccreditation.concat(arr);
            });
        } else {
            const { articlesList = [] } = records;
            defaultSelectedAccreditation = articlesList.map((t: any) => t.ruleId);
        }

        setSelectedRowIds(Array.from(new Set(defaultSelectedAccreditation.concat(selectedRowIds))));
        setDrawerVisible(true);
    }

    const delFileHandle = (records: any) => {
        // 删除树结构对应的公共资料
        publicData.delTableFlieListFunc(records.id);
    }


    // 操作回调
    const actionHandle = ({ type, data }: { type: string, data: MccsFileTree.childTree }) => {

        data ? publicData.setCurrentActived(data) : publicData.setCurrentActived(undefined);  // 点击获取当前树数据

        if (type == 'del') {
            // 删除
            setActionType('del');
            if (data) {
                const { id } = data;
                publicData.delTreeHandle([Number(id)]);
            }

        }
        if (type == 'edit' && data) {
            setActionType('edit');
            setTreeDataModelInit({ name: data.title, cateType: data.cateType });
            setMccsModalVisible(true);
        }
        if (type == 'add') {
            setActionType('add');
            setMccsModalVisible(true);
        }
    }

    const MccsModalFinnishHandle = (values: { name: string, cateType: number }) => {
        //   console.log({values});
        let parentId = 0;  // 默认最顶级为0
        if (publicData.currentActived) {
            parentId = Number(publicData.currentActived.id)
        }
        if (actionType == 'add') {
            publicData.addTreeHandle({ ...values, parentId });
        }
        if (actionType == 'edit') {
            if (publicData.currentActived) {
                const { id } = publicData.currentActived;
                publicData.editTreeHandle({ name: values.name, id: Number(id) });
            }
        }

        setMccsModalVisible(false);

    }


    const onDrawerVisibleChangeHandle = (bool: boolean) => {
        if (!bool) {
            setSelectedRowIds([]); // 关闭drawer清空
            tableRef?.current?.getTableRef().current?.clearSelected(); // 关闭Drawer清空选中项
            setSelectedRowIds([]);
            setSelectedFiles([]);
        }
        setDrawerVisible(bool);
    }

    const onSelectedFilesHandle = (selectedRowKeys: number[], selectedRows: any[]) => {
        setSelectedFiles(selectedRows);
    }

    const drawerFormOnFinnish = async () => {
        await publicData.batchConnectAccreditation({
            articlesList: selectedRowIds,
            ids: selectedFiles.map((t: any) => t.id)
        });
        setDrawerVisible(false);
        tableRef?.current?.getTableRef().current?.clearSelected(); // 关闭Drawer清空选中项
        setSelectedRowIds([]);
        setSelectedFiles([]);
    }


    const uploadFileHandle = async (file: any) => {
        await publicData.uploadFilehandle(file);
        setUploadModalVisible(false);
    }

    const batchDownload = (selectedRowKeys: string[] | number[]) => {
        //   console.log({selectedRowKeys});
        const toNumberArr = selectedRowKeys.map((t: string | number) => Number(t));
        publicData.batchDownloadResourcePost(toNumberArr);
    }



    useEffect(() => {
        // 刷新表格数据
        tableRef?.current?.getTableRef().current?.reload();
    }, [publicData.reloadTable])


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


    useEffect(() => {
        // 默认获取数据
        publicData.getTreeData();
    }, []);


    return (
        <MccsPageContainer>
            <MccsDrawerForm
                title='关联条款'
                width={1000}
                visible={drawerVisible}
                onVisibleChange={onDrawerVisibleChangeHandle}
                onFinish={drawerFormOnFinnish}
            >
                <Form.Item>

                    <MccsTable
                        columns={drawerTableColumns}
                        request={async (params: any)=>{
                              const ids = (selectedFiles.map((t: any)=>t.id)).join(',');
                              return  await publicData.getDrawerTableList(params,ids)
                        }} 
                        search={{
                            labelWidth: 0,
                            span: 10
                        }}
                        rowSelection={{
                            // 自定义选择项参考: https://ant.design/components/table-cn/#components-table-demo-row-selection-custom
                            // 注释该行则默认不显示下拉选项
                            selections: [Table.SELECTION_ALL, Table.SELECTION_INVERT],
                            selectedRowKeys: [...selectedRowIds],
                            onChange: (selectedRowKeys: number[]) => {
                                // console.log({selectedRowKeys,selectedRowIds});
                                // const _prev = selectedRowIds;
                                // const combinIds = selectedRowKeys.concat(_prev);
                                // // setSelectedRowIds(Array.from(new Set(combinIds)));
                            },
                            onSelect:(record: any, selected: any, selectedRows: any, nativeEvent: any)=>{
                                // console.log({record,selected,selectedRows,nativeEvent});
                                const {id} = record;
                                const _prev = selectedRowIds;
                                if(selected){
                                    setSelectedRowIds(_prev.concat([id]));
                                }else{
                                    _prev.splice(_prev.findIndex(item => item === id), 1);
                                    setSelectedRowIds([..._prev]);
                                }
                            }
                        }}
                        rowKey="id"
                        tableAlertOptionRender={({ selectedRowKeys, selectedRows, onCleanSelected }: { selectedRowKeys: number[] | string[], selectedRows: SelectedRowsType[], onCleanSelected: () => void }) => {

                            return (
                                <Space size={16}>
                                    <Button type='primary' onClick={onCleanSelected}>取消选择</Button>
                                </Space>
                            );
                        }}
                     />
                </Form.Item>
            </MccsDrawerForm>
            {
                MccsModalVisible && (
                    <MccsModal
                        title={actionType == 'add' ? '新增' : (actionType == 'edit' ? '编辑' : '')}
                        visible={MccsModalVisible}
                        layout='inline'
                        initialValues={actionType == 'edit' && treeDataModelInit}
                        onVisibleChange={MccsModalVisibleChangeHandle}
                        onFinish={MccsModalFinnishHandle}
                    >
                        <Space size={20} direction='vertical'>
                            <ProFormText
                                name='name'
                                width="md"
                                label="名称"
                                placeholder="请输入名称"
                            />
                            <ProFormSelect
                                options={[
                                    {
                                        value: 1,
                                        label: '等级评审',
                                    },
                                    {
                                        value: 0,
                                        label: '其他',
                                    },
                                ]}
                                width="md"
                                name="cateType"
                                label="类型"
                            />
                        </Space>
                    </MccsModal>
                )
            }

            <MccsProCard gutter={16} ghost direction='row'>
                <MccsProCard colSpan={6} style={{ height: '78vh' }} bodyStyle={{ padding: '16px' }}>
                    <MccsFileTree
                        treeData={publicData.treeData}
                        defaultSelected={defaultOpened}
                        onSelectHandle={onSelectHandle}
                        actionHandle={actionHandle}
                        searchHandle={searchHandle}
                        editable={true}
                    />
                </MccsProCard>
                <MccsProCard colSpan={18} style={{ height: '78vh' }} bodyStyle={{ padding: '16px' }}>
                    <MccsTable
                        ref={tableRef}
                        columns={columns}
                        request={publicData.getTreeTableListHandle}
                        search={{
                            span: 8,
                            optionRender: (searchConfig: any, formProps: any, dom: any) => [
                                // <Button key='upload' onClick={uploadFileHandle}>上传文件</Button>,
                                <MccsModal
                                    title='上传文件'
                                    key='upload'
                                    visible={uploadModalVisible}
                                    onVisibleChange={(bool: boolean) => setUploadModalVisible(bool)}
                                    trigger={
                                        <Button onClick={() => setUploadModalVisible(true)}>上传文件</Button>
                                    }
                                    onFinish={(values: { file: any }) => { uploadFileHandle(values.file.fileList) }}
                                >
                                    <Form.Item name='file'>
                                        <MccsUpload maxCount={10} />
                                    </Form.Item>
                                </MccsModal>,
                                ...dom
                            ]
                        }}
                        rowSelection={{
                            // 自定义选择项参考: https://ant.design/components/table-cn/#components-table-demo-row-selection-custom
                            // 注释该行则默认不显示下拉选项
                            selections: [Table.SELECTION_ALL, Table.SELECTION_INVERT],
                            onChange: (selectedRowKeys: any[], selectedRows: any[]) => { onSelectedFilesHandle(selectedRowKeys, selectedRows) }
                        }}

                        rowKey="id"
                        tableAlertOptionRender={({ selectedRowKeys, selectedRows, onCleanSelected }: { selectedRowKeys: number[] | string[], selectedRows: SelectedRowsType[], onCleanSelected: () => void }) => {
                            return (
                                <Space size={16}>
                                    <Button onClick={() => { connectHandle() }}>{`修改关联`}</Button>
                                    <Button onClick={() => batchDownload(selectedRowKeys)}>{`下载`}</Button>
                                    <Button type='ghost' onClick={onCleanSelected}>取消选择</Button>
                                </Space>
                            );
                        }}
                    />
                </MccsProCard>
            </MccsProCard>
        </MccsPageContainer>
    )
}

export default PublicData
