/*
 * @Author: your name
 * @Date: 2022-04-28 16:02:55
 * @LastEditTime: 2022-05-06 10:45:40
 * @LastEditors: Please set LastEditors
 * @Description: 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 * @FilePath: /MedicalWisdomCheckSys/src/pages/GradeHospitalAccreditation/articleManagement/components/articleDetailModule/drawer/fragment/ledger.tsx
 */


import { Upload, message, Empty, Table } from 'antd';

import MccsDrawerForm from '@/components/MccsDrawerForm/index';
import { useModel } from 'umi';

import blueFieIcon from '../../../../../../../../public/blueFileIcon.png';
import { useEffect, useState } from 'react';
import { delLedgerRecords, getLedgerRecords, ledgerRecordList, uploadFilePost } from '@/pages/GradeHospitalAccreditation/articleManagement/server';
import MccsTable from '@/components/MccsTable/index';


const { Dragger } = Upload;

const Ledger = () => {

    const columns = [
        {
          title: '时间',
          dataIndex: 'createTime',
          render:(text:any, record:any)=>{
              return `${new Date(record.createTime).getFullYear()}-${new Date(record.createTime).getMonth() + 1}-${new Date(record.createTime).getDate()} ${new Date(record.createTime).getHours()}:${new Date(record.createTime).getMinutes()}:${new Date(record.createTime).getSeconds()}`
          }
        },
        {
          title: '名称',
          dataIndex: 'fileName',
        },
        {
            title: '上传人',
            dataIndex: 'createUserName',
        },
        {
          title: '操作',
          render: (text:any, record:any) => (
            <a href={record.fileUrl} target='_blank'>预览</a>
          ),
        },
      ];

    const props = {
        name: 'file',
        multiple: true,
        customRequest:(option:any)=>{
            option.onSuccess('')
        },
        onChange(info: any) {
            const { status } = info.file
            if (status === 'done') {
                set_uploadList([...info.fileList]);
            } else if (status === 'error') {
                message.error(`${info.file.name} file upload failed.`);
            }
        },
        onDrop(e: any) {
            console.log('Dropped files', e.dataTransfer.files);
        },
    };


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

    const {
        isLeaf,
        treeData,
        getTableData,
        currentActivedTree,
        setCurrentActivedTree,
        scoreList,
        getDepartmentRequest,
        currentActDataDireactory,
        ...restModelData
    } = articleManagement;

    const [ledgerRecordList, set_ledgerRecordList] = useState<ledgerRecordList[]>([]);  //台账记录
    const [uploadList, set_uploadList] = useState<any>([]);

    const onVisibleChangeHandle = (visible: boolean) => {
        //drawer展示控制
        restModelData.setDrawerVisible(visible);
    }

    const uploadLedgerHandle = async () => {

        const uploadFormData = new FormData();

        for (const item of uploadList) {
            uploadFormData.append('file', item.originFileObj as Blob)
        }

        uploadFormData.append('id', `${currentActDataDireactory?.id}`);

        const resp = await uploadFilePost(uploadFormData);

        if (resp) {
            getRecordList();
        }
    }

    const getRecordList = async () => {
        if (currentActDataDireactory) {
            const resp = await getLedgerRecords({ id: currentActDataDireactory.id });
            if (resp) {
                const { list } = resp;
                set_ledgerRecordList(list);

                return {
                    data: list,
                    success: true,
                  };
            }
            return []
        }
    }

    const delLedgerRecord = async (data: ledgerRecordList) => {
        const resp = await delLedgerRecords(data.id);
        if (resp) {
            getRecordList();
        }
    }

    useEffect(() => {
        getRecordList();
    }, []);

    return (
        <MccsDrawerForm
            title={restModelData.drawerFormType == 'VIEWLEDGER'?currentActDataDireactory?.directory:'台账上传'}
            width={restModelData.drawerFormType == 'VIEWLEDGER'?800:500}
            visible={restModelData.drawerVisible}
            onVisibleChange={onVisibleChangeHandle}
            submitter={false}
        >
            {restModelData.drawerFormType == 'VIEWLEDGER' && (
                  <MccsTable 
                     search={false}
                     columns={columns}  
                     request={getRecordList} 
                     tableStyle={{padding:0}}
                  />
            )}
            {
                restModelData.drawerFormType == 'Ledger' && (
                    <>
                        <div className='uploadArea'>
                            <Dragger {...props}>
                                <p className="ant-upload-drag-icon">
                                    <img src={blueFieIcon} width={40} />
                                </p>
                                <p className="ant-upload-text" style={{ marginTop: 8, marginBottom: 8 }}>点击或将文件拖拽到这里上传</p>
                                <p className="ant-upload-hint" style={{ fontSize: 12, color: '#666F80' }}>
                                    支持拓展名：.doc .pdf .jpg .docx
                                </p>
                            </Dragger>
                        </div>

                        {uploadList.length > 0 && <button onClick={uploadLedgerHandle} style={{ marginTop: 30 }}>提交上传文件</button>}

                        <div style={{ fontSize: 16, height: 16, color: '#7A8599', marginTop: 50, marginBottom: 24 }}>台账记录</div>
                        <div>
                            {
                                ledgerRecordList.map((item, index) => {
                                    return (
                                        <div className='ledgerRecord' key={index} style={{ display: 'flex', flexDirection: 'column', marginBottom: 16 }}>
                                            <div style={{ color: '#292C33', fontWeight: 'bold', fontSize: 14 }}>{item.fileName}</div>
                                            <div style={{ display: 'flex', flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center' }}>
                                                <span style={{ color: '#525866', fontSize: 12 }}>
                                                    {`${new Date(item.createTime).getFullYear()}-${new Date(item.createTime).getMonth() + 1}-${new Date(item.createTime).getDate()} ${new Date(item.createTime).getHours()}:${new Date(item.createTime).getMinutes()}:${new Date(item.createTime).getSeconds()}`}
                                                </span>
                                                <div>
                                                    <a style={{ fontSize: 12, color: '#3377FF' }} onClick={() => delLedgerRecord(item)}>删除</a>
                                                    {/* <Divider type='vertical' /> */}
                                                    {/* <a style={{fontSize:12,color:'#3377FF'}} >重新上传</a> */}
                                                </div>
                                            </div>
                                        </div>
                                    )
                                })
                            }
                        </div>
                        {
                            ledgerRecordList.length == 0 && (<Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />)
                        }
                    </>
                )
            }

        </MccsDrawerForm>

    )

}

export default Ledger;