import * as React from 'react';
import { PageHeaderFoot, Button, AutoTableContainer, Table, Pagination } from 'kts-xui';
import { AdvancedSearch, KtsForm } from 'kts-components';
import MercyModal from './UI.MercyModal';
import moment from 'moment';
import { columnEnum } from '../CommonComponents/ColumnEnum';
import { withRouter, RouteChildrenProps } from 'react-router-dom';
import agent from '../Server';
import { DigitalAssetVerification } from '../..';
import HistoryModal from './UI.HistoryModal';
import { findLabel, proveStatusEnum, invoiceTypeEnum, effectiveStatusEnum, submitStatusEnum, appealStatusEnum, taskTypeEnum } from '../CommonComponents/FiledsEnum';
import { Select, Space, Tag, Tooltip } from 'kts-components-antd-x4';
import VerifyList from '../CommonComponents/VerifiedList'

/** Props接口 */
interface IProps {

}

class UIComponents extends React.Component<IProps & RouteChildrenProps, any> {
    columns = [
        {
            title: '商品id',
            dataIndex: 'goodsUuid',
            width: 250,
        },
        {
            title: '核验方',
            dataIndex: 'verifierName',
            width: 200,
            ellipsis: true,
        }, {
            title: '销售方',
            width: 170,
            dataIndex: 'salerName',
            ellipsis: true,
        }, {
            title: '采购方',
            width: 170,
            dataIndex: 'buyerName',
            ellipsis: true,
        },
        {
            dataIndex:'buyerTaxNo',
            type: 'string',
            width: 170,
            title: '采购方纳税人识别号',
            ellipsis: true,
        },
        {
            title: '业务有效性',
            width: 120,
            align: 'center',
            dataIndex: columnEnum['有效性状态'],
            render: (text, record) => {
                if (text === 2) {
                    return <Tooltip title={record.refuseMsg}><span style={{ color: 'red' }}>{findLabel(text, effectiveStatusEnum)}</span></Tooltip>
                } else {
                    return <span style={{ color: '#0074ff' }}>{findLabel(text, effectiveStatusEnum)}</span>
                }
            }
        },
        {
            title: '证明结果',
            width: 100,
            align: 'center',
            dataIndex: columnEnum['证明标识'],
            render: (text, record) => {
                if (text === 2 || text === 4) {
                    return <Tooltip title={record.proveMsg}><span style={{ color: 'red' }}>{findLabel(text, proveStatusEnum)}</span></Tooltip>
                } else if (text === 1) {
                    return <span style={{ color: '#0074ff' }}>{findLabel(text, proveStatusEnum)}</span>
                } else {
                    return findLabel(text, proveStatusEnum)
                }
            }
        }, {
            title: '提交状态',
            width: 100,
            align: 'center',
            dataIndex: columnEnum['提交状态'],
            render: (text, record) => {
                if (text === 4 || text === 5) {
                    return <Tooltip title={record.refuseMsg}><Tag style={{ color: 'red' }}>{findLabel(text, submitStatusEnum)}</Tag></Tooltip>
                } else {
                    return <Tag>{findLabel(text, submitStatusEnum)}</Tag>
                }
            }
        }, {
            title: '商品名称',
            dataIndex: 'goodsName',
            width: 160,
            ellipsis: true,
        }, {
            title: '规格型号',
            width: 160,
            ellipsis: true,
            dataIndex: 'specificationModel',
            render: (text) => {
                return <span style={{ whiteSpace: 'pre-wrap' }}>{text}</span>
            }
        }, {
            title: '数量',
            width: 70,
            ellipsis: true,
            dataIndex: 'quantity',
        }, {
            title: '单位',
            width: 70,
            ellipsis: true,
            dataIndex: 'unit',
        }, {
            title: '发票类型',
            width: 120,
            dataIndex: 'invoiceType',
            render: (text, record) => {
                if (text) {
                    return <Tag>{findLabel(text, invoiceTypeEnum)}</Tag>

                }
            }
        }, {
            title: '发票代码',
            width: 140,
            dataIndex: 'invoiceCode',
        }, {
            title: '发票号码',
            width: 190,
            dataIndex: 'invoiceNo',
        }, {
            title: '开票日期',
            width: 120,
            dataIndex: 'invoiceDate',
            render: text => {
                return text && moment(text).format('YYYY-MM-DD')
            }
        }, {
            title: '申诉状态',
            width: 100,
            dataIndex: 'appealStatus',
            render: (text, record) => {
                if (text === 1) {
                    return <span style={{ color: 'red' }}>{findLabel(text, appealStatusEnum)}</span>
                } else if (text === 3) {
                    return <span style={{ color: '#0074ff' }}>{findLabel(text, appealStatusEnum)}</span>
                } else {
                    return findLabel(text, appealStatusEnum)
                }
            }
        }, {
            title: '采集时间',
            width: 160,
            ellipsis: true,
            dataIndex: 'createTime',
            render: text => {
                return text && moment(text).format('YYYY-MM-DD HH:mm')
            }
        }, {
            title: '采集人',
            width: 100,
            ellipsis: true,
            dataIndex: 'collectMan',
        }, {
            title: '提交时间',
            width: 160,
            ellipsis: true,
            dataIndex: 'submitTime',
            render: text => {
                return text && moment(text).format('YYYY-MM-DD HH:mm')
            }
        }, 
        {
            title: '提交用途',
            width: 150,
            ellipsis: true,
            dataIndex:'submitPurpose',
        },{
            title: '提交人',
            width: 100,
            ellipsis: true,
            dataIndex: 'submitter',
        },
        
        {
            title: '任务单号',
            dataIndex: columnEnum['任务单号'],
            width: 160,
            ellipsis: true,
        },
        {
            title: '关联单据',
            width: 120,
            dataIndex: 'goodsDocRelationList',
            ellipsis: true,
            render: (text, record) => {
                if (record.goodsDocRelationList?.length > 0) {
                    let originalDocuments = record.goodsDocRelationList.reduce((acc, obj) => {
                        acc.push(obj.originalDocument);
                        return acc;
                    }, [])
                    let str = originalDocuments.join('/');
                    return str
                }
            }
        },
        {
            title: '操作',
            dataIndex: 'id',
            width: 180,
            fixed: 'right',
            render: (text, record) => {
                //无效商品 证明结果正常

                return <Space>
                    {record.canAppeal === 1 && <a onClick={() => { this.onMercy([record]); }}>申诉</a>}
                    {record.appealStatus !== null && <a onClick={() => { this.onMercyList(record) }}>申诉记录</a>}
                    {record.submitStatus === 3 && <a onClick={() => { this.onVerifyList(record.goodsUuid) }}>处理记录</a>}
                </Space>

            }
        },
    ];
    constructor(props) {
        super(props);
        this.state = {
            pageMeta: null,
            list: [

            ],
            params: {},
            selectedRowKeys: [],
            selectedRows: [],
            denyList: [],
            mercyId: null,
            validMode: '',
            goodsUuid: '',
        };
    }
    onVerifyList = id => {
        this.setState({
            goodsUuid: id,
        })
    }
    closeVerify = () => {
        this.setState({
            goodsUuid: '',
        })
    }
    changeValid = value => {
        this.setState({
            validMode: value
        }, () => {
            const { params } = this.state
            this.onSearch({
                ...params,
                validMode: value
            })
        });

    }
    topExpand = () => {
        const { validMode } = this.state
        return (
            <AdvancedSearch
                width={450}
                height={44}
                compact={true}
                defaultKey="goodsName"
                placeholder="请输入商品名称"
                searchFormSubmit={this.onSearch}
                extra={
                    <Select value={validMode} style={{ marginRight: 10, width: 100 }} onChange={this.changeValid}>
                        <Select.Option value={''}>全部</Select.Option>
                        <Select.Option value={1}>有效商品</Select.Option>
                        <Select.Option value={2}>无效商品</Select.Option>
                    </Select>
                }
            >
                <KtsForm
                    labelCol={9}
                    wrapperCol={15}
                    labelAlign="left"
                    compact={true}
                    schema={{
                        type: 'object',
                        properties: {
                            [columnEnum['任务单号']]: {
                                type: 'string',
                                title: '任务单号',
                            },
                            'goodsUuid': {
                                type: 'string',
                                title: '商品id',
                            },
                            'goodsName': {
                                type: 'string',
                                title: '商品名称',
                            },
                            'specificationModel': {
                                type: 'string',
                                title: '规格型号',
                            },
                            'verifierName': {
                                type: 'string',
                                title: '核验方',
                            },
                            [columnEnum['销售方']]: {
                                type: 'string',
                                title: '销售方',
                            },
                            'buyerName': {
                                type: 'string',
                                title: '采购方',
                            },
                            'buyerTaxNo': {
                                type: 'string',
                                title: '采购方纳税人识别号',
                            },
                            kaipiao: {
                                type: 'daterange',
                                title: '开票日期',
                                'x-props': {
                                    extendsFields: ['minInvoiceDate', 'maxInvoiceDate'],
                                }
                            },
                            submitTime: {
                                type: 'daterange',
                                title: '提交日期',
                                'x-props': {
                                    extendsFields: ['minSubmitTime', 'maxSubmitTime'],
                                }
                            },
                            submitPurpose:{
                                type: 'string',
                                title: '提交用途',
                            },
                            collectDate: {
                                type: 'daterange',
                                title: '采集日期',
                                'x-props': {
                                    extendsFields: ['minCreateTime', 'maxCreateTime'],
                                }
                            },
                            [columnEnum['采集人']]: {
                                type: 'string',
                                title: '采集人'
                            },
                            [columnEnum['提交人']]: {
                                type: 'string',
                                title: '提交人'
                            },
                            'invoiceCode': {
                                type: 'string',
                                title: '发票代码',
                            },
                            'invoiceNo': {
                                type: 'string',
                                title: '发票号码',
                            },
                            originalDocument: {
                                type: 'string',
                                title: '关联单据',
                            },
                            [columnEnum['提交状态']]: {
                                type: 'string',
                                title: '提交状态',
                                enum: submitStatusEnum,
                                'x-props': {
                                    mode: "multiple",
                                    filterOption: (input, option) =>
                                        option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                                }
                            }
                        },
                    }}
                >
                </KtsForm>
            </AdvancedSearch>

        );
    }
    /**
     * 申诉
     * @param record 
     */
    onMercy = (record: any[]) => {
        this.setState({
            denyList: record,
        })
    }
    onMercyList = (record) => {
        this.setState({
            mercyId: record
        })
    }
    onCloseMercyList = () => {
        this.setState({
            mercyId: null
        })
    }
    componentDidMount() {
        const params = {
            pageNum: 1,
            pageSize: 10
        };
        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,
            effectiveStatus: this.state.validMode,
        };
        this.getData(params);
    }
    onSearch = (data = {}) => {
        this.setState({
            params: data,

        });
        const params = {
            ...data,
            ...this.state.pageMeta,
            effectiveStatus: this.state.validMode,

            pageNum: 1
        };
        this.getData(params);
    }
    getData = async (params?) => {
        params = {
            ...params,
            minCreateTime: params['minCreateTime'] && moment(params['minCreateTime']).format('YYYY-MM-DD 00:00:00'),
            maxCreateTime: params['maxCreateTime'] && moment(params['maxCreateTime']).format('YYYY-MM-DD 23:59:59'),
            minSubmitTime: params['minSubmitTime'] && moment(params['minSubmitTime']).format('YYYY-MM-DD 00:00:00'),
            maxSubmitTime: params['maxSubmitTime'] && moment(params['maxSubmitTime']).format('YYYY-MM-DD 23:59:59'),
            minInvoiceDate: params['minInvoiceDate'] && moment(params['minInvoiceDate']).format('YYYY-MM-DD 00:00:00'),
            maxInvoiceDate: params['maxInvoiceDate'] && moment(params['maxInvoiceDate']).format('YYYY-MM-DD 23:59:59'),
        }
        const res: any = await agent.post('/asset/submit/submitGoodsPage', params, this);
        if (res.err) {
            return;
        } else {
            if (res.res) {
                this.setState({
                    pageMeta: res.res.pageMeta,
                    list: res.res.items
                });
            }
        }
    }
    onDeny = () => {
        this.setState({
            denyList: [...this.state.selectedRows]
        })
    }
    /**
     * 导出 带筛选条件导出
     */
    onExport = async () => {
        const { params } = this.state;
        const data = {
            ...params,
            effectiveStatus: this.state.validMode,
            minCreateTime: params['minCreateTime'] && moment(params['minCreateTime']).format('YYYY-MM-DD 00:00:00'),
            maxCreateTime: params['maxCreateTime'] && moment(params['maxCreateTime']).format('YYYY-MM-DD 23:59:59'),
            minSubmitTime: params['minSubmitTime'] && moment(params['minSubmitTime']).format('YYYY-MM-DD 00:00:00'),
            maxSubmitTime: params['maxSubmitTime'] && moment(params['maxSubmitTime']).format('YYYY-MM-DD 23:59:59'),
            minInvoiceDate: params['minInvoiceDate'] && moment(params['minInvoiceDate']).format('YYYY-MM-DD 00:00:00'),
            maxInvoiceDate: params['maxInvoiceDate'] && moment(params['maxInvoiceDate']).format('YYYY-MM-DD 23:59:59'),
        };
        const res: any = await DigitalAssetVerification.server.post(`${DigitalAssetVerification.prefix_path}/asset/submit/exportSubmitGoods`, data).reqFs(DigitalAssetVerification.server.reqFs.filter(v => v !== DigitalAssetVerification.serviceTools.addContentType)).resFs([]).responseType('blob').end(null);;
        if (res.err) {
            return;
        } else {
            const blob = res.res.body;
            let url = URL.createObjectURL(blob);
            let link = document.createElement('a');
            link.style.display = 'none';
            link.href = url;
            link.setAttribute('download', `资产采集商品明细-${moment(new Date()).format('YYYYMMDDHHmmss')}.xls`);
            link.click();
            // link = null;
        }
    }
    closeModal = () => {
        this.setState({
            denyList: []
        })
    }
    successModal = () => {
        this.onRefresh();
        this.closeModal();
        this.setState({
            selectedRowKeys: [],
            selectedRows: [],
        })
    }
    render() {
        const dataSource = this.state.list;
        const { pageMeta, selectedRows, mercyId, goodsUuid, selectedRowKeys } = this.state;
        const rowSelection = {
            selectedRowKeys,
            onChange: (selectedRowKeys, selectedRows) => {
                this.setState({
                    selectedRowKeys,
                    selectedRows
                });
            },
            getCheckboxProps: (record) => ({
                disabled: record.canAppeal !== 1
            }),
        }
        return (
            <div style={{ height: 'calc(100vh - 97px)', display: 'flex', flexDirection: 'column', overflow: 'auto' }}>
                <div style={{ flex: 'none', position: 'relative', zIndex: 3 }}>
                    <PageHeaderFoot
                        expandLeft={this.topExpand()}
                        expandRight={[
                            <Button key='0' type="primary" onClick={this.onExport}>导出</Button>,
                            <Button disabled={selectedRows.length === 0 ? true : false} key='1' type="primary" onClick={this.onDeny}>批量申诉</Button>,
                        ]}
                    >

                    </PageHeaderFoot>
                </div>
                <AutoTableContainer style={{ flex: 1, padding: '0 20px', background: '#F4F4F4' }} >
                    <Table
                        className='fixheight'
                        bordered
                        dataSource={dataSource}
                        columns={this.columns as any}
                        rowSelection={rowSelection}
                        scroll={{ x: '2100', y: 'max-content' }}
                        pagination={false}
                        rowKey='goodsUuid'
                    />
                </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} />}
                {
                    this.state.denyList.length > 0 && <MercyModal list={this.state.denyList} onClose={this.closeModal} onSuccess={this.successModal} />
                }
                { mercyId && <HistoryModal data={mercyId} onClose={this.onCloseMercyList} />}
                {goodsUuid && <VerifyList url='/asset/submit/handleRecordPage' goodsUuid={{ 'goodsUuid': goodsUuid }} onClose={this.closeVerify} />}
            </div>
        );
    }
}
export default withRouter(UIComponents as any)