/*
 * @Author: your name
 * @Date: 2022-03-08 10:41:15
 * @LastEditTime: 2022-06-06 10:46:32
 * @LastEditors: code4eat awesomedema@gmail.com
 * @Description: 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 * @FilePath: /MedicalWisdomCheckSys/src/pages/GradeHospitalAccreditation/articleManagement/components/articleDetailModule/index.tsx
 */


import MccsEditableTable from '@/components/MccsEditableTable';
import MccsLightTable from '@/components/MccsLightTable';
import { getScoreColor } from '@/constant';
import TextArea from 'antd/lib/input/TextArea';
import React, { useRef, useEffect, useState } from 'react'
import { useModel } from 'umi';
import { ActType } from '../..';
import { getCurrentLevelTable, getTaizhangDirectoryTable } from '../../server';

import { Input, Switch, Select } from 'antd'

import './style.less';
import SetDrawer from './drawer';

const { Option } = Select;

const myEvent = new Event('resize');



const ArticleDetail = ({ isModeTwo = false }) => {

    const { articleManagement,ledgerUpload } = useModel('allModels');

    const {
        isLeaf,
        currentActivedTree,
        scoreList,
        currentSelectedActObj,
        ...restModelData
    } = articleManagement;

    const {} = ledgerUpload

    const [scrollAreaH, setScrollAreaH] = useState(100);
    const leafContentRef = useRef<HTMLDivElement>(null);
    const scrollContentRef = useRef<HTMLDivElement>(null);
    const [ifCollapse, setifCollapse] = useState(false);

    const MccsLightTableColumns = [
        {
            key: 'gradeLevel',
            title: '档次',
            width: 10
        },
        {
            key: 'directory',
            title: '名称',
            width: 60
        },
        {
            key: 'accountType',
            title: '类型',
        },
        {
            key: 'accountStatus',
            title: '需要台账',
            render: (record: any) => {
                return record.accountStatus == 0 ? '否' : '是'
            }
        },
        {
            key: 'accountStatus',
            title: '操作',
            valueType:'option',
            render: (record: any) => {
                return record.accountStatus == 1 &&(<a onClick={()=>viewLedgerFileHandle(record)}>查看</a>)
            }
        },
    ]

    const mccsEditableTableColumns = [
        {
            title: '名称',
            dataIndex: 'directory',
            width: '50%',
            align: 'center',
            formItemProps: () => {
                return {
                    rules: [{ required: true, message: '此项为必填项' }],
                };
            },
        },
        {
            title: '档次',
            dataIndex: 'grade',
            width: '15%',
            align: 'center',
            formItemProps: () => {
                return {
                    rules: [{ required: true, message: '此项为必填项' }],
                };
            },
            renderFormItem: (_: any, config: any, form: any) => {

                const { isEditable } = config;

                return isEditable ? (
                    <Select
                        mode='multiple'
                        placeholder='请选择'
                    >
                        {
                            restModelData.gradeOptions.map((item, index) => (
                                <Option value={item.value} key={index}>{item.label}</Option>
                            ))
                        }
                    </Select>

                ) : <Input />;
            },
            render: (_: any, row: any) => {
                return typeof _ == 'object' ? _.join(',') : _;
            },
        },
        {
            title: '类型',
            dataIndex: 'accountType',
            align: 'center',
            width: '15%',
            formItemProps: () => {
                return {
                    rules: [{ required: true, message: '此项为必填项' }],
                };
            },
            renderFormItem: (_: any, { isEditable }: { isEditable: boolean }, form: any) => {

                return isEditable ? (
                    <Select
                        placeholder='请选择'
                    >
                        {
                            restModelData.accountTypeOptions.map((item, index) => (
                                <Option value={item.value} key={index}>{item.label}</Option>
                            ))
                        }
                    </Select>
                ) : <Input />;
            },


        },
    ]


    const onTextAreaChange = (e: React.ChangeEvent<HTMLTextAreaElement>, level: string) => {
        //更改执行情况说明数据
        //首先找出要更新的项，再进行整体替换

        if (restModelData.selectedSelfEvolution) {

            const editTargetLevel = restModelData.selectedSelfEvolution.label;  //目标等级
            //找出目标等级下正在更新的level
            const editImplementationDataItemIndex = restModelData.implementationData[editTargetLevel].findIndex(item => item.level == level);
            //拷贝旧的目标等级数据
            let _cpOldImplemetationItem = restModelData.implementationData[editTargetLevel];
            //将新的编辑内容赋值给正在编辑的目标下的level
            _cpOldImplemetationItem[editImplementationDataItemIndex].note = e.target.value;

            if (editImplementationDataItemIndex != -1) {
                restModelData.setImplementationData({
                    ...restModelData.implementationData,
                    //插入更新
                    [editTargetLevel]: _cpOldImplemetationItem
                }
                )
            }
        }

    }

    const taizhangDataDerectoryEditHandle = (data: any, actType: ActType) => {
        //台账资料目录编辑回调
        const version = restModelData.leafData?.reviewArticle.version;
        let prevData = restModelData.taizhangDataDirectoryCommitList;
        const numStr = restModelData.leafData?.reviewArticle.numStr;


        if (actType == ActType.DEL && (typeof data.id == 'string')) {
            //如果是删除操作且删除的不是数据库已有数据时,剔除之前暂时保留数据
            prevData = prevData.filter(item => item.directory != data.directory);
            restModelData.setTaizhangDataDirectoryCommitList([...prevData]);
            return;
        }

        const replaceData = (item: any, index: number) => {
            prevData[index] = {
                ...item, dataStatus: actType, version: version ? version : '',
                grade: data.grade.join(','), numStr: numStr, accountStatus: data.accountStatus ? '1' : '0'
            };
            restModelData.setTaizhangDataDirectoryCommitList([...prevData]);

        }

        const findeIndex = prevData.findIndex(item => item.id == data.id);

        if (findeIndex != -1) {
            //之前已有操作记录的,替换为最新状态
            replaceData(data, findeIndex);
            return;
        }

        restModelData.setTaizhangDataDirectoryCommitList(
            [...prevData, {
                ...data, dataStatus: actType, version: version ? version : '',
                grade: data.grade.join(','), numStr: numStr, accountStatus: data.accountStatus ? '1' : '0'
            }]
        )
    }



    const followWindowResize = (num?: number, leafContentHeight?: number) => {
        const _num = num ? num : 0;

        if (leafContentRef.current) {
            const leafContentH = leafContentHeight ? leafContentHeight : (leafContentRef.current.clientHeight);  //className为leafContent的div
            const headerH = 48 + 16;
            const scoreH = isModeTwo ? (60) : 0;
            const h = window.innerHeight - (leafContentH + headerH + scoreH);
        
            setScrollAreaH(h - _num - 24);
        }
    }

    const telescopicBtnHandle = (e: React.MouseEvent) => {
        //展开/收起
        e.preventDefault();

        setifCollapse(!ifCollapse);
        if (!ifCollapse) {
            followWindowResize(0, 55);
        } else {
            followWindowResize(0);
        }

        // window.dispatchEvent(myEvent);

        if (scrollContentRef.current) {
            scrollContentRef.current.scrollTop = 0
        }

    }


    const setDrawerFormInit = () => {
        if (restModelData.leafData) {
            const { responsibilityDepartmentId, responsibilityDepartmentName, responsibilityUserId, targetEvaluation, responsibilityUserName, accountType, pfmReviewArticleDepartList } = restModelData.leafData.reviewArticle;
            if (responsibilityDepartmentName && responsibilityDepartmentId) {

                restModelData.setArticleSettingFormInit({
                    Co_DepartmentAndManager: pfmReviewArticleDepartList.map(t => ({
                        responsibilityDepartment: { label: t.responsibilityDepartmentName, value: t.responsibilityDepartmentId },
                        responsibilityUser: { label: t.responsibilityUserName, value: t.responsibilityUserId }
                    })),
                    responsibilityDepartment: { label: responsibilityDepartmentName, value: responsibilityDepartmentId },
                    responsibilityUser: { label: responsibilityUserName, value: responsibilityUserId },
                    targetScores: { label: targetEvaluation, value: targetEvaluation },
                    articleType: { label: accountType, value: accountType },
                });
            }

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

        }
    }


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

    }

    const setEditPageStatus = () => {
        //更改页面的编辑状态
        restModelData.setEditMode(!restModelData.editMode);
    }

    const uploadLedgerHandle = (item:API.TaizhangDirectoryTableItem)=>{
        //台账上传点击触发台账管理界面上传抽屉
        restModelData.set_currentActDataDireactory(item);
        restModelData.setDrawerFormType('Ledger');
        restModelData.setDrawerVisible(true);
    }

    const viewLedgerFileHandle = (item:API.TaizhangDirectoryTableItem)=>{
        console.log('ee');
        restModelData.set_currentActDataDireactory(item);
        restModelData.setDrawerFormType('VIEWLEDGER');
        restModelData.setDrawerVisible(true);
    }


    useEffect(() => {
        if (restModelData.editMode) {
            followWindowResize(40);
        } else {
            followWindowResize(0);
        }
    }, [restModelData.editMode]);

    useEffect(() => {
        // followWindowResize();
        if (isLeaf) {
            setTimeout(() => {
                //首次加载叶子节点内容触发一次
                window.dispatchEvent(myEvent);
                document.body.style.overflowY = 'hidden';  //叶子节点下锁住页面滚动
            }, 500);
            //获取单位列表
        }

        if (!isLeaf) {
            document.body.style.overflowY = 'auto';  //非叶子节点放开
        }
    }, [isLeaf]);


    useEffect(() => {
        window.addEventListener("resize", () => followWindowResize());
        return () => {
            window.removeEventListener("resize", () => followWindowResize());
        }
    }, []);


    return (
        <div className='articleDetailContainer' >

            <SetDrawer />

            {
                isLeaf && (
                    <div className={ifCollapse ? 'leafContent collapse' : 'leafContent'} ref={leafContentRef}>
                        <div className='leafContentTitle'>{`${currentSelectedActObj.code} ${currentSelectedActObj.name||currentSelectedActObj.title}`}</div>
                        <div style={{marginBottom:'24px'}}>
                        <div className='peopleGroup'>
                            <span>条文组别：</span>
                            <span>{restModelData.leafData?.reviewArticle?.accountType}</span>
                            <span>负责单位：</span>
                            <span>{restModelData.leafData?.reviewArticle?.responsibilityDepartmentName}</span>
                            <span>负责人：</span>
                            <span>{restModelData.leafData?.reviewArticle?.responsibilityUserName}</span>
                        </div>
                        {
                            (restModelData.leafData?.reviewArticle.pfmReviewArticleDepartList
                                && restModelData.leafData?.reviewArticle.pfmReviewArticleDepartList.length > 0) && (
                                <div className='coOperateList'>
                                    <div>合作单位及负责人：</div>
                                    <div>
                                        {
                                            restModelData.leafData?.reviewArticle.pfmReviewArticleDepartList.map((item, index) => {
                                                return (
                                                    <span key={index} style={{border:'1px solid #DADEE6',marginRight:2}}>{`${item.responsibilityDepartmentName}｜${item.responsibilityUserName}`}</span>
                                                )
                                            })
                                        }
                                    </div>
                                </div>
                            )
                        }
                        </div>
                        
                        <div className='scoreRow'>
                            <div className='scoreInfo'>
                                {
                                    scoreList.map((item, index) => {
                                        return (
                                            <div key={index} className='scoreBlock'>
                                                {item.label}
                                                {item.value && item.value != '-' ? (<span style={{ color: getScoreColor(item.value) }}>{item.value}</span>) : ' -'}
                                            </div>
                                        )
                                    })
                                }
                            </div>
                            {
                                //条文页面
                                !restModelData.moduleMode && <div className='ruleSettingBtn' onClick={articleSetBtnHandle}>条文设置</div>
                            }
                            {
                                //台账上传页面且非编辑状态下
                                (restModelData.moduleMode && !restModelData.editMode && restModelData.hasEditAuthority) && <div className='editPageBtn' onClick={() => setEditPageStatus()}>{restModelData.editMode ? '取消编辑' : '开启编辑'}</div>
                            }
                        </div>
                        <div className='scoreGradeDetail'>

                            {
                                restModelData.leafData?.pfmViewRuleDetailDataVoList.map((item, index) => (
                                    <div className='scoreGradeDetailList' key={index}>
                                        <div className='head'>{item.evaluation}</div>
                                        <div className='detail'>
                                            {
                                                item.viewRuleAndLevelVos && item.viewRuleAndLevelVos.map((v, k) => (
                                                    <div className='textLine' key={k}>{`${v.grade} ${v.detail}`}</div>
                                                ))
                                            }
                                        </div>
                                    </div>
                                ))
                            }
                        </div>

                        <div className={ifCollapse ? 'telescopicBtn collapse' : 'telescopicBtn'} onClick={e => telescopicBtnHandle(e)}></div>
                    </div>
                )
            }

            {
                isLeaf && isModeTwo && (
                    <div className='selfEvaluationWrap'>
                        <div style={{ display: 'flex', flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', width: '100%', }}>
                            <div className='selfEvaluation'>
                                自评等级
                                {!restModelData.editMode && (
                                    <span style={{ color: getScoreColor(restModelData.leafData ? restModelData.leafData.reviewArticle.selfEvaluation : '') }}>{restModelData.leafData?.reviewArticle.selfEvaluation ? restModelData.leafData?.reviewArticle.selfEvaluation : '-'}</span>
                                )}
                            </div>
                            {
                                restModelData.editMode && (
                                    <div className='wrap' style={{ width: '60%', display: 'flex', flexDirection: 'row', justifyContent: 'flex-end' }}>
                                        {
                                            (restModelData.targetScores).map((item, index) => (
                                                <div className={restModelData.selectedSelfEvolution?.label == item.label ? 'tab on' : 'tab'} key={index} onClick={() => restModelData.onSelfEvolutionTabChange(item)}>{item.label}</div>
                                            ))
                                        }
                                    </div>
                                )
                            }
                        </div>
                    </div>
                )
            }

            {
                isLeaf && restModelData.leafData && (
                    //台账上传页面时，背景色统一白色，cardWrap提供容器实现上下滑动
                    <div className={isModeTwo ? 'cardWrap isModeTwo' : 'cardWrap'} style={{ marginTop: '16px', height: `${scrollAreaH - 16}px` }} ref={scrollContentRef}>
                        <div>
                            {
                                //渲染执行情况说明
                                /**
                                 * 满足条件：
                                 * 1.存在自评等级从接口获取或手动点击选择
                                 * 2.implementationData里有当前等级的数据
                                 */
                                (restModelData.selectedSelfEvolution && restModelData.implementationData[restModelData.selectedSelfEvolution.label])
                                && restModelData.implementationData[restModelData.selectedSelfEvolution.label].map((item, index) => {

                                    return (
                                        <div className='card' key={index} style={{ marginBottom: isModeTwo ? 0 : '16px', paddingBottom: isModeTwo ? 0 : '16px' }}>
                                            <div className='cardTitle' style={{ marginBottom: isModeTwo ? '8px' : '16px' }}>{`执行情况说明（等级${item.level}）`}</div>

                                            <TextArea showCount maxLength={2000}
                                                autoSize={{
                                                    minRows: 5,
                                                    maxRows: 20
                                                }}
                                                disabled={!restModelData.editMode} value={item.note}
                                                onChange={e => onTextAreaChange(e, item.level)}
                                                style={{ marginBottom: 20 }} />

                                            {
                                                !isModeTwo && (
                                                    <MccsLightTable
                                                        columns={MccsLightTableColumns}
                                                        request={(current, pageSize) => getCurrentLevelTable({
                                                            level: item.level,
                                                            numStr: currentSelectedActObj ? (currentSelectedActObj.numStr ? currentSelectedActObj.numStr : currentSelectedActObj.code) : 'null',
                                                            version: restModelData.leafData ? (restModelData.leafData.reviewArticle.version) : 'null',
                                                            current,
                                                            pageSize
                                                        })}
                                                    />
                                                )
                                            }
                                        </div>
                                    )
                                })
                            }
                        </div>
                        <div>
                            {
                                //台帐下展示
                                (isModeTwo && restModelData.leafData) && (
                                    <MccsEditableTable
                                        bordered={true}
                                        controlled={false}
                                        bodyStyle={{padding:'16px'}}
                                        edit={restModelData.editMode}
                                        reload={!restModelData.editMode}
                                        pagination={true}
                                        addHandle={
                                            (data: any) => taizhangDataDerectoryEditHandle(data, ActType.ADD)
                                        }
                                        editHandle={
                                            (data: any) => taizhangDataDerectoryEditHandle(data, ActType.EDIT)
                                        }
                                        delHandle={
                                            (data: any) => taizhangDataDerectoryEditHandle(data, ActType.DEL)
                                        }
                                        request={async (current, pageSize) => {

                                            if (restModelData.leafData) {

                                                const { numStr, version } = restModelData.leafData.reviewArticle;
                                                const resp = await getTaizhangDirectoryTable({ numStr, version, current, pageSize });
                                                const { list = [] } = resp;
                                                return {
                                                    data: list.map(item => ({ ...item, grade: item.grade ? item.grade.split(',') : [], accountStatus: item.accountStatus == '0' ? false : true })), //多选下拉需传数组值
                                                    total: resp.totalCount,
                                                    current: resp.current,
                                                    success: true
                                                };
                                            }
                                            return {
                                                data: [],
                                                total: 0,
                                                success: false
                                            }
                                        }}
                                        columns={restModelData.editMode?[...mccsEditableTableColumns,{
                                            title: '台账上传',
                                            align: 'center',
                                            dataIndex: 'accountStatus',
                                            width: '10%',
                                            valueType: 'switch',
                                            render: (_: any, row: any) => {
                                                return (
                                                    <Switch size='small' disabled checked={row.accountStatus} />
                                                )
                                            },
                                        },]:[
                                            ...mccsEditableTableColumns,
                                            {
                                                title: '操作',
                                                width: '10%',
                                                align: 'center',
                                                render: (text: string, record: any, _: any, action: any) => (record.accountStatus?<a onClick={()=>uploadLedgerHandle(record)}>上传</a>:'')
                                            }
                                        ]}
                                    />
                                )
                            }
                        </div>
                    </div>
                )
            }

        </div>
    )
}

export default ArticleDetail;