import * as React from 'react';
import { PageHeaderFoot, Button, AutoTableContainer, Table, Pagination, Tag, Radio, message } from 'kts-xui';
import { AdvancedSearch, KtsForm } from 'kts-components';
// import AddModal from './UI.DenyModal';
import moment from 'moment';
import { columnEnum } from '../CommonComponents/ColumnEnum';
import { fileTypeEnumEnum, fileStatusEnum, proveStatusEnum, submitStatusEnum } from '../CommonComponents/FiledsEnum';
import { withRouter, RouteChildrenProps } from 'react-router-dom';
import { produceStatusEnum, fileTypeEnum } from './StatusEnum';
import { Icon } from 'antd';
import agent from '../Server';
import { Space, Tooltip } from 'kts-components-antd-x4';
import VerifyList from '../CommonComponents/VerifyList';
import { DigitalAssetVerification } from '../..';
/** Props接口 */
interface IProps {
    changeView: (value) => void
}

class UIComponents extends React.Component<IProps & RouteChildrenProps, any> {
    transformStandard = (record: any) => {
        if (record) {
            let infoArray = [] as any[];
            const { fileStatus, createFailureReason } = record;
            let color = 'green';
            let type = 'check-circle';
            if (fileStatus === null) {
                return '';
            } 
            // 只要有一个失败，就显示红色
            if (fileStatus === 'SUCCESS') {
                color = 'green';
                type = 'check-circle';
                return '已生成';
            } else if (fileStatus === 'PROCESSING') {// 只要有一个未校验 就显示灰色
                return '生成中';
            }
            // 警告状态
            if (fileStatus === 'FAILURE') {
                color = 'red';
                type = 'warning';
                infoArray.push(
                    <div key={1}> 
                        {createFailureReason && <div>警告原因:{createFailureReason}</div>}
                    </div>);
            }
            if (infoArray.length === 0) {
                return <Icon type={type} style={{ color: color }} />;
            } else {
                return <Tooltip title={infoArray}>{produceStatusEnum[fileStatus]}<Icon type={type} style={{ color: color }} /></Tooltip>;
            }
        }
        return '';
    };
    getFile = async record => {
        if (record.fileStatus === 2) { return; }
        const params = { fileName: record.fileName };
        const res: any = await agent.get('/global/export/getDownloadUrl', { fileName: record.fileName }, this);
        // const res = await serviceAgent.get(Urls.getDownloadUrl, params).end(this);

        if (!res.err) {
            let a = document.createElement('a');
            a.setAttribute('href', res.res);
            a.setAttribute('target', '_blank');
            a.click();
        }
    }
    columns = [
        {
            title: '文件名',
            dataIndex: 'fileName',
            width: 450,
            ellipsis: true,
            render: (text) => {
                return (
                    <Tooltip placement="topLeft" title={text}>
                        <div
                            className='ellipsisText'
                            style={{ maxWidth: '409px'}}
                        >
                            {text}
                        </div>
                    </Tooltip>
                );
            }
        },
        {
            title: '状态',
            dataIndex: 'fileStatus',
            key: 'fileStatus',
            width: 100,
            render: (text, record: any) => {
                return (
                    <span>
                        {this.transformStandard(record)}
                    </span>
                );
            }
        },
        {
            title: '来源',
            dataIndex: 'fileType',
            key: 'fileType',
            width: 150,
            render: (text, record: any) => {
                return (
                    <span>
                        {fileTypeEnum[text]}
                    </span>
                );
            }
            
        },
        {
            title: '创建时间',
            dataIndex: 'createTime',
            key: 'createTime',
            width: 200,
            render: text => moment(text).format('YYYY-MM-DD HH:mm:ss')
        },
        {
            title: '更新时间',
            dataIndex: 'updateTime',
            key: 'updateTime',
            width: 200,
            render: text => moment(text).format('YYYY-MM-DD HH:mm:ss')
        },
        {
            title: '操作',
            dataIndex: 'opera',
            key: 'opera',
            width: 150,
            fixed: 'right',
            render: (text, record) => {
                return (
                    <span>
                        {record.fileName && record.fileStatus === 'SUCCESS' && 
                            <span className="hand" style={record.fileStatus === 'SUCCESS' ? { color: '#1890ff' } : {}}  onClick={() => { this.getFile(record); }}>
                                <Icon type="download" />数据下载</span>}
                    </span>
                );
            }
        }
    ];
    constructor(props) {
        super(props);
        this.state = {
            pageMeta: null,
            list: [
            ],
            params: this.props.history?.location?.state || {},
            showModal: false,
            selectedRowKeys: [],
            denyList: [], 
        };
    }
    onSubmit = async recordUuid => {
        const res: any = await agent.post('/asset/submit/reSubmit', { recordUuid }, this);
        if (res.err) {
            return;
        } else {
            this.onRefresh();
        }
    }   
    topExpand = () => {
        const { params } = this.state;
        return (
            <AdvancedSearch
                width={400}
                height={44}
                compact={true}
                defaultKey="fileName"
                placeholder="请输入文件名"
                initialValues={params}
                searchFormSubmit={this.onSearch} 
            >
                <KtsForm
                    labelCol={9}
                    wrapperCol={15}
                    labelAlign="left"
                    compact={true}
                    schema={{
                        type: 'object',
                        properties: {
                            'fileName': {
                                type: 'string',
                                title: '文件名',
                            }, 
                            fileStatus: {
                                type: 'string',
                                title: '状态',
                                enum: fileStatusEnum,
                            },
                            fileType: {
                                type: 'string',
                                title: '来源',
                                enum: fileTypeEnumEnum
                            }, 
                            kaipiao: {
                                type: 'daterange',
                                title: '创建时间',
                                'x-props': {
                                    extendsFields: ['createTimeStart', 'createTimeEnd'],
                                }
                            }, 
                           

                        },
                    }}
                >
                </KtsForm>
            </AdvancedSearch>
        );
    }
    /**
     * 拒绝
     * @param keys 
     */
    onDenyHandler = (keys: string[]) => {
        this.setState({
            denyList: keys,
            showModal: true
        })
    }
    componentDidMount() {
        const params = {
            pageNum: 1,
            pageSize: 10,
            ...this.state.params,
        };
        this.getData(params); 
    }
    onPageChange = (pageNum, pageSize) => {
        this.setState({
            pageMeta: {
                ...this.state.pageMeta,
                pageNum,
                pageSize
            }
        }, () => {
            this.onRefresh();
        });
    }
    onRefresh = () => {
        const params = {
            ...this.state.params,
            ...this.state.pageMeta,
        };
        this.getData(params);
    }
    onSearch = (data = {}) => {
        this.setState({
            params: data,
        });
        const params = {
            ...data,
            ...this.state.pageMeta,
            pageNum: 1
        };
        this.getData(params);
    }
    getData = async (params?) => { 
        params = {
            ...params,
            createTimeStart: params.kaipiao && params.kaipiao[0] && moment(params.kaipiao[0]).format('YYYY-MM-DD 00:00:00'),
            createTimeEnd: params.kaipiao && params.kaipiao[1] && moment(params.kaipiao[1]).format('YYYY-MM-DD 23:59:59')
        }
        const res: any = await agent.post('/global/export/page', params, this);
        if (res.err) {
            return;
        } else {
            if (res.res) {
                this.setState({
                    pageMeta: res.res.pageMeta,
                    list: res.res.items
                });
            }
        }
    }     
    render() {
        const dataSource = this.state.list;
        const { pageMeta } = this.state; 
        return (
            <div style={{ height: 'calc(100vh - 97px)', display: 'flex', flexDirection: 'column' }}>
                <div style={{ flex: 'none', position: 'relative', zIndex: 1 }}>
                    <PageHeaderFoot
                        expandLeft={this.topExpand()} 
                        onRefresh={this.onRefresh}
                    >
                    </PageHeaderFoot>
                </div>
                <AutoTableContainer style={{ flex: 1, padding: '0 20px', background: '#F4F4F4' }} >
                    <Table
                        className='fixheight'
                        dataSource={dataSource}
                        columns={this.columns as any}
                        bordered={true} 
                        scroll={{ x: '1600', y: 'max-content' }}
                        pagination={false}
                        rowKey='recordUuid'
                    />
                </AutoTableContainer>
                {pageMeta && <Pagination onChange={this.onPageChange} showTotal={(total, range) => `第 ${range[0]}-${range[1]} 条,  共有 ${total} 条`} style={{ padding: '16px 0', flex: 'none', background: 'white', textAlign: 'center' }} total={pageMeta.total} pageSize={pageMeta.pageSize} current={pageMeta.pageNum} showSizeChanger={true} />}
            </div>
        );
    }
}
export default withRouter(UIComponents as any);