import React, { useCallback, useEffect, useState } from 'react';
import { Form, Input, Drawer, Button, AutoTableContainer, Pagination, Table, message, DatePicker } from 'kts-xui';
import { Space, Divider, Modal, } from 'kts-components-antd-x4';
import './index.less';
import agent from '../../Server';
import moment from 'moment';
const Search = Input.Search;
const { RangePicker } = DatePicker;
interface IProps {
    onClose: () => void;
    onSuccess?: () => void;
    type: number;
}
const GoodsSource = (props: IProps) => {
    const [data, setData] = useState([]);
    const [form] = Form.useForm();
    const [pageMeta, setPageMeta] = useState<{ pageNum: number, pageSize: number, pages: number, total: number }>({
        pageNum: 1,
        pageSize: 10,
        pages: 0,
        total: 0,
    });
    const type = props.type;
    const [selectedRowKeys, setRowKeys] = useState<any[]>([]);
    const [selectedRows, setRows] = useState<any[]>([]);
    const [params, setParams] = useState({ pageNum: 1, pageSize: 10, name: '' });
    const columns = [
        {
            title: '商品名称',
            dataIndex: 'name',
            width:200,
            ellipsis: true,
        },
        {
            title: '规格型号',
            dataIndex: 'specification',
            width: 240,
            ellipsis: true,
            render: (text) => {
                return <span style={{ whiteSpace: 'pre-wrap' }}>{text}</span>
            }
        },

    ];
    const onPageChange = (pageNum: any, pageSize: any) => {
        setParams({
            ...params,
            pageNum,
            pageSize
        });
    }
    const add = () => {
        form.submit();
    }
    useEffect(() => {
        (async () => {
            const res: any = await agent.post('/product/platform/productPage', params, this);
            if (res.res) {
                setData(res.res.items);
                setPageMeta(res.res.pageMeta)
            }
        })()
    }, [params]);
    const onFinish = async (values: any) => {
        const authDate = {
            authStartTime: moment(values['authTime'][0]).format('YYYY-MM-DD'),
            authEndTime: moment(values['authTime'][1]).format('YYYY-MM-DD'),

        }
        const data = selectedRows.map(item => {
            return {
                ...authDate,
                productName: item['name'],
                specification: item['specification'],
                type
            }
        })
        const res: any = await agent.post('/verifierparty/config/default/scope/batch/save', data, this);
        if (res.err) {
            return false;
        }
        if (res.res) {
            if (res.res.failList.length > 1) {
                const tips = res.res.failList.map((item, index) => {
                    return <div key={index}>{item.productName}/{item.specification}</div>
                })
                Modal.confirm({
                    title: '以下商品重复导入',
                    content: tips,
                })
            } else if (res.res.failList.length === 1) {
                message.warn('重复导入');
            } else {
                message.success('操作成功');
                props.onSuccess!();
            }
            return res;
        }

    }
    const rowSelection = {
        onChange: (selectedRowKeys: any[], selectedRows: any[]) => {
            setRows(selectedRows);
        },
        getCheckboxProps: (record: any) => ({
            disabled: !record.specification,
        }),
    }
    const onSearchName = (value: string) => {
        setParams({
            ...params,
            name: value
        })
    }
    return (
        <Drawer
            title="从商品管理导入"
            visible={true}
            onClose={props.onClose}
            width={700}
            footer={
                <Space>
                    <Button onClick={add} type='primary' disabled={selectedRows.length === 0 ? true : false} >添加</Button>
                    <Button onClick={props.onClose}>取消</Button>
                </Space>
            }
        >
            <AutoTableContainer style={{ flex: 1, }} >
                <Form
                    layout='vertical'
                    form={form}
                    onFinish={onFinish}
                >
                    <Form.Item
                        label="授权有效时间"
                        name="authTime"
                        rules={[{ required: true, message: '请输入必填项' }]}
                    >
                        <RangePicker />
                    </Form.Item>
                    <Form.Item
                        label="请输入商品名称查询"
                        name="productName"
                    >
                        <Search
                            placeholder="请输入商品名称查询"
                            onSearch={onSearchName}
                        />
                    </Form.Item>
                </Form>
                <Divider />
                <Table
                    dataSource={data}
                    columns={columns}
                    pagination={false}
                    rowSelection={rowSelection}
                    rowKey='id'
                />
            </AutoTableContainer>
            <Pagination onChange={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} />

        </Drawer>
    )
}

export default GoodsSource