/*
 * @Author: your name
 * @Date: 2021-09-14 10:22:09
 * @LastEditTime: 2021-10-28 16:05:37
 * @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 MccsScoreBanner from '@/components/MccsScoreBanner/index';
import MccsRecordList from '@/components/MccsRecordList/index';
import MccsDrawerForm from '@/components/MccsDrawerForm/index';
import MccsClickableTabs from '@/components/MccsClickableTabs/index';
import MccsUpload from '@/components/MccsUpload/index';
import { MccsModal } from '@/components/MccsModal';
import type { ProFormInstance, } from '@ant-design/pro-form';



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


import './index.less';



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

}

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

const { TabPane } = Tabs;

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>
            )
        },
    },
    {
        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,
    },
]

//条文管理
const ArticleManagement: React.FC<ArticleManagementProps> = (props) => {
    const { columnsFromProps = [], headerConcig, isModeTwo } = props;
    const { articleManagement } = useModel('allModels');
    const drawerFormRef = useRef<ProFormInstance>();
    const {
        isLeaf,
        treeData,
        getTableData,
        currentActivedTree,
        setCurrentActivedTree,
        scoreList,
        getDepartmentRequest,
        departmentManagers,
        getDepartment,//获取责任单位
        ...restModelData
    } = articleManagement;
    const tableRef = useRef<MccsTable.MccsTableRef>();

    const [articleSettingFormInit, setArticleSettingFormInit] = useState<{}>({});  //条文设置表单回显默认值
    const [defaultOpened, setDefaultOpened] = useState<string>();

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

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

    const articleSetBtnHandle = () => {
        //条文设置
        // console.log({ articleSettingFormInit });
        restModelData.setDrawerFormType('ARTICLE_SET');
        restModelData.setDrawerVisible(true);

    }

    const onVisibleChangeHandle = (visible: boolean) => {
        //drawer展示控制
        !visible && setArticleSettingFormInit({});//清空默认值
        restModelData.setDrawerVisible(visible);
    }

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

    }

    const upLoadFileHandle = (formInitData?: any) => {
        //因为modalForm开启了request+params获取表单默认值，
        //所以必须先设置默认值才能开启弹窗
        if (formInitData) {
            const { fileUrl, recordTypeName, accountType, fileName } = formInitData;
            // console.log({formInitData});
            restModelData.setUploadFormInitValue({
                tab: { label: accountType, value: { label: recordTypeName, value: recordTypeName } },
                files: [{
                    uid: new Date().getTime(),
                    name: fileName,
                    status: 'done',
                    url: fileUrl
                }]
            });
        } else {
            restModelData.setUploadFormInitValue({})
        }
        restModelData.getUploadLedgerType().then(data => {
            //设置上传台账类型
            restModelData.setUploadLedgerTypeList(data);

        })
        restModelData.setModalVisible(true);
    }

    const actionNodeFunc = (data: any) => {
        //渲染记录列表操作按钮
        // console.log({ data });
        const { fileUrl } = data;
        const reupload = () => {

            upLoadFileHandle(data);
        }

        return isModeTwo ? (
            //台账上传
            <a onClick={reupload}>重新上传</a>
        ) : (
            //条文管理
            <a href={fileUrl}>下载文件</a>
        )
    }


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


    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;
            if (responsibilityDepartmentName && responsibilityDepartmentId) {
                setArticleSettingFormInit({
                    responsibilityDepartment: { label: responsibilityDepartmentName, value: responsibilityDepartmentId },
                    responsibilityUser: { label: responsibilityUserName, value: responsibilityUserId },
                    targetScores: { label: targetEvaluation, value: targetEvaluation },
                    articleType: { label: accountType, value: accountType },
                });
            }
        }

    }, [restModelData.leafData]);


    useEffect(() => {
        if (isModeTwo) {
            //设置当前模块模式
            restModelData.setModuleMode(isModeTwo);
        } else {
            //设置当前模块模式
            restModelData.setModuleMode(false);
        }
    }, [props]);

    useEffect(() => {
        if (treeData.length > 0) {
          //默认展开书结构第一个结点
          const { id } = treeData[0];
          setDefaultOpened(`${id}`);
        }
      }, [treeData]);

    useEffect(() => {
        restModelData.getArticleTreeData();
        restModelData.getCurrentHospScore();
    }, [])

    return (
        <MccsPageContainer
            config={headerConcig ? headerConcig : {
                content: !isModeTwo && <div style={{ textAlign: 'right', fontSize: 12, color: '#525866' }}>{restModelData.currentHospSelfScoreAndOthers}</div>
            }}
        >
            {
                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={1} />
                        </Form.Item>
                    </MccsModal>
                )
            }

            {
                //条文设置/表格批量设置drawer弹窗
                restModelData.drawerVisible && (
                    <MccsDrawerForm
                        title={restModelData.drawerFormType == 'ARTICLE_SET' ? '条文设置' : '批量设置'}
                        width={500}
                        formRef={drawerFormRef}
                        visible={restModelData.drawerVisible}
                        initialValues={restModelData.drawerFormType == 'ARTICLE_SET' ? { ...articleSettingFormInit } : {}}
                        onFinish={(values: any) => restModelData.drawerFormType == 'ARTICLE_SET' ? restModelData.setArticle(values) : restModelData.batchSetting(values)}
                        onVisibleChange={onVisibleChangeHandle}
                    >
                        <div className='formItemTitle'>负责人及单位</div>
                        <Row gutter={16}>
                            <Col className="gutter-row" span={10}>
                                <ProFormSelect
                                    name="responsibilityDepartment"
                                    width='sm'
                                    showSearch
                                    request={getDepartmentRequest}
                                    placeholder="选择单位"
                                    fieldProps={{
                                        labelInValue: true,
                                        onChange: (value, option) => {
                                            //责任单位修改时清空责任人
                                            drawerFormRef.current?.setFieldsValue({ ...articleSettingFormInit, responsibilityUser: { label: '', value: '' } });
                                            getDepartment(value, option)
                                        }
                                    }}
                                    rules={[{ required: true, message: '请选择单位！' }]}
                                />
                            </Col>

                            <Col className="gutter-row" span={8}>
                                <ProFormDependency name={['responsibilityDepartment']}>
                                    {({ responsibilityDepartment }) => {
                                        return (
                                            <ProFormSelect
                                                name="responsibilityUser"
                                                width='sm'
                                                disabled={!responsibilityDepartment || JSON.stringify(responsibilityDepartment) == '{}'}
                                                options={departmentManagers}
                                                placeholder="选择负责人"
                                                fieldProps={{
                                                    labelInValue: true,
                                                    // onChange:(value,option)=>getManagers(value,option)
                                                }}
                                                rules={[{ required: true, message: '请选择负责人！' }]}
                                            />
                                        )
                                    }}
                                </ProFormDependency>
                            </Col>
                        </Row>
                        <div className='formItemTitle'>目标分数</div>
                        <Row >
                            <Col span={24}>
                                <Form.Item name='targetScores' rules={[
                                    {
                                        required: true,
                                        message: '请选择目标分数!',
                                    },
                                ]}>
                                    <MccsClickableTabs
                                        data={restModelData.targetScores}
                                    />
                                </Form.Item>
                            </Col>
                        </Row>
                        {
                            true && (
                                <>
                                    <div className='formItemTitle'>条文组别</div>
                                    <Row>
                                        <Col span={24}>
                                            <Form.Item name='articleType' rules={[
                                                {
                                                    required: true,
                                                    message: '请选择条文组别!',
                                                },
                                            ]}>
                                                <MccsClickableTabs
                                                    data={restModelData.ruleTypes}
                                                />
                                            </Form.Item>
                                        </Col>
                                    </Row>
                                </>
                            )
                        }

                    </MccsDrawerForm>

                )
            }

            <MccsProCard gutter={16} ghost direction='row'>
                <MccsProCard colSpan={6} style={{ height: '78vh' }} bodyStyle={{ padding: '16px' }}>
                    {
                        defaultOpened&&(
                            <MccsFileTree
                            treeData={treeData}
                            defaultSelected={defaultOpened}
                            onSelectHandle={onSelectHandle}
                            // actionHandle={actionHandle}
                            // searchHandle={searchHandle}
                            editable={false}
                            />
                        )
                    }
                </MccsProCard>
                <MccsProCard colSpan={18} style={{ minHeight: '78vh' }} bodyStyle={{ padding: '16px' }}>
                    {
                        !isLeaf && (
                            <MccsTable
                                ref={tableRef}
                                columns={columnsFromProps.length > 0 ? columnsFromProps : columns}
                                request={getTableData}
                                search={{
                                    span: 6
                                }}
                                rowSelection={{
                                    // 自定义选择项参考: 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()}
                            />
                        )
                    }

                    {
                        isLeaf && (
                            <div className='leafContent'>
                                <div className='leafContentTitle'>{currentActivedTree ? currentActivedTree.title : ''}</div>
                                <div className='peopleGroup'>
                                    <span>条文组别：</span>
                                    <span>{restModelData.leafData?.accountType}</span>
                                    <span>负责单位：</span>
                                    <span>{restModelData.leafData?.responsibilityDepartmentName}</span>
                                    <span>负责人：</span>
                                    <span>{restModelData.leafData?.responsibilityUserName}</span>
                                </div>
                                <MccsScoreBanner list={scoreList} />
                                {
                                    isModeTwo && (
                                        <div style={{ marginTop: 5 }}>
                                            <Tabs  activeKey={`${restModelData.tabKey}`} centered size='large' onChange={(key) => restModelData.setTabKey(key)}>
                                                <TabPane tab="台账记录" key="1">
                                                    <div className='articleSetBtn'>
                                                        <span onClick={() => upLoadFileHandle()}>上传文件</span>
                                                    </div>
                                                    <MccsRecordList
                                                        title='台账记录'
                                                        list={restModelData.records}
                                                        actionFunc={(data) => restModelData.delHistoryRecordHandle(data)}
                                                        actionNode={(data) => actionNodeFunc(data)}
                                                    />
                                                </TabPane>
                                                <TabPane tab="自评结果" key="2">
                                                <div className='selfEvolutionTitle'>开始自评</div>
                                                    <div className='selfEvolutionArea'>
                                                       
                                                        <MccsClickableTabs
                                                            classNames='tabWrap'
                                                            onChange={(value: { label: string, value: any }) => restModelData.onSelfEvolutionTabChange(value)}
                                                            data={restModelData.targetScores}
                                                            value={restModelData.selectedSelfEvolution}
                                                        />
                                                        <Button onClick={() => restModelData.commitSelfEvolution()}>提交自评</Button>
                                                    </div>
                                                    <MccsRecordList
                                                        title='自评记录'
                                                        list={restModelData.selfEvaluationRecords}
                                                    />
                                                </TabPane>
                                            </Tabs>
                                        </div>
                                    )
                                }
                                {
                                    !isModeTwo && (
                                        <>
                                            <div className='articleSetBtn'><span onClick={articleSetBtnHandle}>条文设置</span></div>
                                            <MccsRecordList
                                                title='台账记录'
                                                list={restModelData.records}
                                                actionFunc={(data) => { console.log({ data }) }}
                                                //restModelData.delHistoryRecordHandle(data)
                                                actionNode={(data) => actionNodeFunc(data)}
                                            />
                                        </>
                                    )
                                }
                            </div>
                        )
                    }

                </MccsProCard>
            </MccsProCard>
        </MccsPageContainer>
    )
}

export default ArticleManagement