import * as React from 'react';
import { Table, Button, Modal, message } from 'kts-xui';
import { Descriptions, Pagination, Dropdown, Tooltip, Menu, Space, Table as TableTxt, Row } from 'kts-components-antd-x4';
import agent from '../../../Server';
import moment from 'moment';
import { AdvancedSearch, KtsForm } from 'kts-components';
import ConnectPanel from './ConnectDrawer';
import { InfoCircleOutlined } from '@ant-design/icons';
import { findLabel, operateEnum, effectiveStatusEnum } from '../../../CommonComponents/FiledsEnum';
/** Props接口 */
interface IProps {
    onClose?: () => void;
    taskUuid: string;
    recordUuid: number;
    data: any;
    originalDocList: string[];
    status: number
}
export default class UIComponents extends React.Component<IProps, any> {
    columns = [
        {
            title: '序号',
            dataIndex: 'id',
            width: 70,
            render: (text, record, index) => {
                return index + 1
            }
        },
        {
            title: '业务有效性',
            dataIndex: 'effectiveStatus',
            width: 140,
            render: (text, record) => {
                if (text === 1) {
                    return <span style={{ color: '#0074ff' }}>{findLabel(text, effectiveStatusEnum)}</span>
                } else if (text === 2) {
                    return <Tooltip title={record.refuseMsg}><span style={{ color: 'red' }}>{findLabel(text, effectiveStatusEnum)}</span></Tooltip>
                } else {
                    return '-'
                }
            }
        },
        {
            title: '货物(劳务)名称',
            dataIndex: 'goodsName',
            width: 140,
            ellipsis: true,
        },
        {
            title: '货物规格型号',
            dataIndex: 'specificationModel',
            width: 200,
            ellipsis: true,
            render: (text) => {
                return <span style={{ whiteSpace: 'pre-wrap' }}>{text}</span>
            }
        },
        {
            title: '单位',
            dataIndex: 'unit',
            width: 80,
        },
        {
            title: '数量',
            dataIndex: 'quantity',
            width: 80,
            ellipsis: true,
        },
        {
            title: '关联单据',
            width: 120,
            dataIndex: 'goodsDocRelationList',
            ellipsis: true,
            render: (text) => {
                if (text.length > 0) {
                    let originalDocuments = text.reduce((acc, obj) => {
                        acc.push(obj.originalDocument);
                        return acc;
                    }, [])
                    let str = originalDocuments.join('/');
                    return str
                }
            }
        },
        {
            title: '操作',
            dataIndex: 'operate',
            width: 130,
            render: (text, record) => {
                return (<Space>
                    {this.props.status < 3 && <a onClick={() => { this.onConnect(record); }}>关联</a>}
                    {this.props.status < 3 && record.goodsDocRelationList.length !== 0 && <a onClick={() => { this.onConnect(record); }}>解除关联</a>}
                </Space>)
            }
        }

    ];
    constructor(props) {
        super(props);
        this.state = {
            recordUuid: this.props.recordUuid,
            taskUuid: this.props.taskUuid,
            data: this.props.data,
            list: [],
            selectedRowKeys: [],
            pageMeta: null,
            connectModal: false,
            record: null,
            originalDocList: this.props.originalDocList || [],
            batch: false,
            connnectIds: [],
            updateType: 1
        }
    }
    onConnect = record => {
        let ids = [];
        if (record.goodsDocRelationList) {
            ids = record.goodsDocRelationList.reduce((acc, obj) => {
                acc.push(obj.docUuid);
                return acc;
            }, []);
        }
        this.setState({
            record,
            connectModal: true,
            connnectIds: ids,
            updateType: 2
        })
    }
    /**
     * 关闭关联弹框后需要设置状态为false，batch(是否是批量状态)，allpage是否是所有页面数据
     */
    onConnectClose = () => {
        this.onRefresh();
        this.setState({
            connectModal: false,
            batch: false,
            updateType: 1,
            record: null
        })
    }
    componentDidMount() {
        const params = {
            pageNum: 1,
            pageSize: 10
        };
        this.getData(params);
    }
    onSearch = (data = {}) => {
        this.setState({
            params: data
        });
        const params = {
            ...data,
            ...this.state.pageMeta,
            pageNum: 1,
            pageSize: 10
        };
        this.getData(params);
    }
    getData = async params => {
        params = {
            ...params,
            invoiceUuid: this.state.recordUuid,
            taskUuid: this.state.taskUuid
        }
        const res: any = await agent.post('/collector/task/assetGoodsPage', params, this);
        if (res.er) {
            return;
        } else if (res.res) {
            this.setState({
                list: res.res.items,
                pageMeta: res.res.pageMeta,
            })
        }

    }
    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);
    }
    /**
     * 
     * @param data 抽屉勾选的数据
     * @returns 
     */
    onConnectSave = async data => {
        const { selectedRowKeys, record, taskUuid, updateType, recordUuid } = this.state;
        const params = {
            includeManyGoodsUuid: (record && record.goodsUuid) || selectedRowKeys,
            includeManyDocUuid: data,
            invoiceUuid: recordUuid,
            taskUuid: taskUuid,
            updateType
        }
        const res: any = await agent.post('/collector/task/linkGoodsWithDoc', params, this);
        if (res.er) {
            return;
        } else if (res.res) {
            message.success('操作成功');
        }
        this.onConnectClose();
    }
    topExpand = () => {
        return (
            <AdvancedSearch
                width={400}
                height={44}
                compact={true}
                defaultKey="goodsName"
                placeholder="请输入商品名称"
                searchFormSubmit={this.onSearch}
            >
                <KtsForm
                    labelCol={6}
                    wrapperCol={18}
                    labelAlign="left"
                    compact={true}
                    schema={{
                        type: 'object',
                        properties: {
                            goodsName: {
                                type: 'string',
                                title: '商品名称',
                            },
                            specificationModel: {
                                type: 'string',
                                title: '规格型号',
                            },
                            originalDocument: {
                                type: 'string',
                                title: '关联单据',
                            },
                            'includeManyEffectiveStatus': {
                                type: 'string',
                                title: '业务有效性',
                                enum: effectiveStatusEnum,
                                'x-props': {
                                    mode: "multiple"
                                }
                            },
                        },
                    }}
                >
                </KtsForm>
            </AdvancedSearch>
        );
    }
    handleMenuClick = (e) => {
        if (e.key === 'all') {
            this.setState({
                updateType: 1,
                connectModal: true,
                batch: true
            })
        } else if (e.key === 'selected') {
            if (this.state.selectedRowKeys.length <= 0) {
                message.error('请先勾选商品，再执行批量关联单据。')
                return
            }
            this.setState({
                connectModal: true,
                updateType: 2,
                batch: true
            })
        } else if (e.key === 'clearall') {
            Modal.confirm({
                title: '确认清空关联单据吗？',
                icon: null,
                okText: <span style={{ paddingRight: 2 }}>清空</span>,
                content: (
                    <div>
                        <p>清空后，商品所有关联单据将会清空。</p>
                    </div>
                ),
                onOk: () => {
                    this.onConnectSave([]);
                }
            })
        } else if (e.key === 'clearselected') {
            if (this.state.selectedRowKeys.length <= 0) {
                message.error('请先勾选商品，再执行批量清空单据。')
                return
            }
            Modal.confirm({
                title: '确认清空关联单据吗？',
                icon: null,
                okText: <span style={{ paddingRight: 2 }}>清空</span>,
                content: (
                    <div>
                        <p>清空后，商品所有关联单据将会清空。</p>
                    </div>
                ),
                onOk: () => {
                    this.onConnectSave([]);
                }
            })
        }
    }
    render() {
        const { data, pageMeta, list, connnectIds, connectModal, originalDocList, selectedRowKeys, batch, recordUuid, record, taskUuid } = this.state;
        const { status } = this.props;
        const rowSelection = {

            onChange: (selectedRowKeys) => {
                this.setState({
                    selectedRowKeys
                })
            },
            selectedRowKeys
        };
        const menu = (<Menu onClick={this.handleMenuClick}>
            <Menu.Item key='all'>
                所有商品行
            </Menu.Item>
            <Menu.Item key='selected'>
                已勾选商品行
            </Menu.Item>
        </Menu>);
        const clearmenu =
            (<Menu onClick={this.handleMenuClick}>
                <Menu.Item key='clearall'>
                    所有商品行
                </Menu.Item>
                {/* <Menu.Item key='clearselected'>
                    已勾选商品行
                </Menu.Item> */}
            </Menu>);
        return (
            <Modal
                title='发票明细'
                onCancel={this.props.onClose}
                visible={true}
                width={900}
                footer={null}
                bodyStyle={{ maxHeight: 500, overflow: 'auto' }}
            >
                <Descriptions>
                    <Descriptions.Item label="销售方名称" span={2}>{data.salerName}</Descriptions.Item>
                    <Descriptions.Item label="购买方名称">{data.buyerName}</Descriptions.Item>
                    <Descriptions.Item label="开票日期">{data.invoiceDate && moment(data.invoiceDate).format('YYYY-MM-DD')}</Descriptions.Item>
                    <Descriptions.Item label="发票代码">{data.invoiceCode}</Descriptions.Item>
                    <Descriptions.Item label="发票号码">{data.invoiceNo}</Descriptions.Item>
                </Descriptions>
                <div style={{ display: 'flex', padding: '0 0 10px' }}>
                    <div style={{ flex: 1 }}>
                        {this.topExpand()}
                    </div>
                    <Space>
                        <Dropdown disabled={status < 3 ? false : true} overlay={clearmenu} key='3'>
                            <Button type="primary">批量清空关联</Button>
                        </Dropdown>
                        <Dropdown disabled={status < 3 ? false : true} overlay={menu} key='3'>
                            <Button type="primary"><Row align="middle">批量关联 <Tooltip title='批量关联将会覆盖之前的关联关系'><InfoCircleOutlined style={{ color: 'white', marginLeft: 5 }} /></Tooltip></Row></Button>
                        </Dropdown>
                        {/* <Button disabled={selectedRowKeys.length > 0 ? false : true} key='1' type="primary" onClick={this.onConnect}>批量关联单据</Button> */}
                    </Space>
                </div>
                {list &&
                    <Table
                        rowSelection={rowSelection}
                        dataSource={list}
                        columns={this.columns}
                        scroll={{ x: 700 }}
                        pagination={false}
                        rowKey="goodsUuid"
                    />
                }
                {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} />}
                {connectModal && <ConnectPanel threeInone={{ invoiceUuid: recordUuid, goodsUuid: record && record.goodsUuid, taskUuid }} type={batch} onSave={this.onConnectSave} onClose={this.onConnectClose} value={connnectIds} list={originalDocList} />}
            </Modal>);
    }

}