import * as React from 'react';
import { Table, Drawer, Button, Pagination, message } from 'kts-xui';
import agent from '../Server';
import { AdvancedSearch, KtsForm } from 'kts-components';
import { Row, Space } from 'kts-components-antd-x4';
import { columnEnum } from '../CommonComponents/ColumnEnum';
import { taskStatusEnum, findLabel } from '../CommonComponents/FiledsEnum';
import moment from 'moment';
/** Props接口 */
interface IProps {
    onClose: () => void;
    value: any;
}

export default class UIComponents extends React.Component<IProps, any> {
    columns = [
        {
            title: '任务单号',
            dataIndex: columnEnum.任务单号,
            width: 160,
        },
        {
            title: '采集方',
            dataIndex: columnEnum.被核验方,
            width: 180,
            ellipsis: true,
        },
        {
            title: '任务状态',
            dataIndex: columnEnum.任务状态,
            width: 100,
            align: 'center',
            render: text => {
                return findLabel(text, taskStatusEnum)
            }
        }, {
            title: '任务截止日期',
            width: 120,
            dataIndex: 'taskEndDate',
            render: (text) => {
                return text && moment(text).format('YYYY-MM-DD');
            }
        },
        {
            title: '关联单据',
            width: 180,
            dataIndex: 'originalDocList',
            ellipsis: true,
            render: (text, record) => {
                if (record.originalDocList?.length > 0) {
                    let originalDocuments = record.originalDocList.reduce((acc, obj) => {
                        acc.push(obj.originalDocument);
                        return acc;
                    }, [])
                    let str = originalDocuments.join('/');
                    return str
                }
            }
        }, 
        {
            title: '关联任务单号',
            width: 180,
            dataIndex: 'taskRelationList',
            ellipsis: true,
            render: (text, record) => {
                if (text.length > 0) {
                    let originalDocuments = text.reduce((acc, obj) => {
                        acc.push(obj.taskNo);
                        return acc;
                    }, [])
                    let str = originalDocuments.join('/');
                    return str
                }
            }
        }, {
            title: '创建人',
            width: 100,
            ellipsis: true,
            dataIndex: columnEnum.创建人,
        },
        {
            title: '备注',
            width: 140,
            dataIndex: columnEnum.备注,
            ellipsis: true,
        },

    ]
    constructor(props) {
        super(props);
        this.state = {
            record: this.props.value,
            selectedRowKeys: [],
            list: [],
            pageNum: 1,
            pageSize: 10,
            pageMeta: null,
            params: {},
        }
    }
    componentDidMount() {
        if (this.props.value.taskRelationList.length > 0) {
            let taskUuids = this.props.value.taskRelationList.reduce((acc, obj) => {
                acc.push(obj.taskUuid);
                return acc;
            }, [])
            this.setState({
                selectedRowKeys: taskUuids
            })
        }
        const params = {
            pageNum: 1,
            pageSize: 10000
        };
        this.getData(params);
    }
    getData = async (params) => {
        params = {
            ...params,
            minEffectiveStart: params['minEffectiveStart'] && moment(params['minEffectiveStart']).format('YYYY-MM-DD 00:00:00'),
            maxEffectiveEnd: params['maxEffectiveEnd'] && moment(params['maxEffectiveEnd']).format('YYYY-MM-DD 23:59:59')
        }
        const res: any = await agent.post('/web/verifierTask/queryTaskPage', params, this);
        if (res.er) {
            return;
        } else if (res.res) {
            this.setState({
                pageMeta: res.res.pageMeta,
                list: res.res.items
            });
        }
    }
    onClose = () => {
        this.props.onClose();
    }

    onRefresh = () => {
        const params = {
            ...this.state.params,
            ...this.state.pageMeta,
        };

        this.getData(params);
    }
    onSearch = (data = {}) => {
        this.setState({
            params: data,
            // selectedRowKeys: []
        });
        const params = {
            ...data,
            ...this.state.pageMeta,
            pageNum: 1,
        };
        this.getData(params);
    }
    onSubmit = async () => {
        const { selectedRowKeys,record } = this.state;
        const data = {
            taskUuid: record.taskUuid,
            relationTaskUuidList: selectedRowKeys
        }
        const res: any = await agent.post('/collector/task/batchLinkTask',data, this);
        if (res.err) {
            return false;
        } else {
            message.success('操作成功');
            this.props.onClose();
        }
    }
    topExpand = () => {
        return (
            <AdvancedSearch
                width={480}
                height={44}
                compact={true}
                defaultKey="taskNo"
                placeholder="请输入任务单号"
                searchFormSubmit={this.onSearch}
            >
                <KtsForm
                    labelCol={9}
                    wrapperCol={15}
                    labelAlign="left"
                    compact={true}
                    schema={{
                        type: 'object',
                        properties: {
                            [columnEnum['任务单号']]: {
                                type: 'string',
                                title: '任务单号',
                            },
                            [columnEnum['任务发起方']]: {
                                type: 'string',
                                title: '任务发起方',
                            },
                            [columnEnum['被核验方']]: {
                                type: 'string',
                                title: '被核验方',
                            },
                            heyan: {
                                type: 'daterange',
                                title: '核验发票时间范围',
                                'x-props': {
                                    extendsFields: ['minEffectiveStart', 'maxEffectiveEnd'],
                                }
                            },
                            taskEndDate: {
                                type: 'date',
                                title: '任务截止日期',
                                'x-props': {
                                    style: { width: '100%' }
                                }
                            },
                            [columnEnum['创建人']]: {
                                type: 'string',
                                title: '创建人',
                            },
                            originalDocument: {
                                type: 'string',
                                title: '关联单据',
                            },
                        },
                    }}
                >
                </KtsForm>
            </AdvancedSearch>
        );
    }
    onPageChange = (pageNum, pageSize) => {
        this.setState({
            pageMeta: {
                ...this.state.pageMeta,
                pageNum,
                pageSize
            }
        }, () => {
            this.onRefresh();
        });
    }
    render() {
        const dataSource = this.state.list;
        const { pageMeta,selectedRowKeys } = this.state
        const rowSelection = {
            onChange: (selectedRowKeys: React.Key[]) => {
                this.setState({
                    selectedRowKeys: selectedRowKeys
                })
            },
            selectedRowKeys
        };
        return (
            <Drawer
                title="添加关联核验任务"
                onClose={this.onClose}
                visible={true}
                footer={
                    <Row justify='end'>
                        <Space align='end'>
                            <Button type="primary" onClick={this.onSubmit}>保存</Button>
                            <Button onClick={this.onClose}>取消</Button>
                        </Space>
                    </Row>}
                width={700}
            >
                {/* <div style={{ marginBottom: 10 }}>
                    {this.topExpand()}
                </div> */}
                <Table
                    bordered
                    dataSource={dataSource}
                    columns={this.columns as any}
                    scroll={{ x: '1400', y: 'max-content' }}
                    // pagination={false}
                    rowKey="taskUuid"
                    rowSelection={rowSelection}
                />
                {/* {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} />} */}
            </Drawer>
        );
    }
}
