import React from 'react';
import { Select, Table, Tooltip, message, Icon, Dropdown, Input } from 'antd';
import { $http } from 'containers/config/https';
import './style/StockBatchItemSelect.less'
class ExpandTable extends React.Component {
    constructor(props) {
        super(props);
        this.columns = [
            {
                title: '序号',
                dataIndex: 'index',
                key: 'index',
                align: 'center',
                width: 30,
                render: function (text, record, index) {
                    return index + 1;
                }
            }, {
                title: '批号',
                dataIndex: 'BatchNo',
                key: 'BatchNo',
                width: 120,
                align: 'center'
            }, {
                title: '效期',
                dataIndex: 'ExpDate',
                key: 'ExpDate',
                width: 100,
                align: 'center'
            }, {
                title: '生产日期',
                dataIndex: 'ProduceDate',
                key: 'ProduceDate',
                width: 100,
                align: 'center'
            }, {
                title: '进价',
                dataIndex: 'PurRp',
                key: 'PurRp',
                width: 60,
                align: 'center'
            }, {
                title: '售价',
                dataIndex: 'PurSp',
                key: 'PurSp',
                width: 60,
                align: 'center'
            }, {
                title: '进价(基本)',
                dataIndex: 'BaseRp',
                key: 'BaseRp',
                width: 60,
                align: 'center'
            }, {
                title: '售价(基本)',
                dataIndex: 'BaseSp',
                key: 'BaseSp',
                width: 60,
                align: 'center'
            },
            {
                title: '生产厂家',
                dataIndex: 'Manf',
                key: 'Manf',
                width: 150,
                align: 'center'
            },
            {
                title: '供应商',
                dataIndex: 'Vendor',
                key: 'Vendor',
                width: 150,
                align: 'center'
            },
        ];
    }
    rowClick = (recrod, index, e) => {
        this.props.selectCallBack(recrod, index, e);
    }
    componentDidMount() {
        //addEventListener("click",(e)=>{e.stopPropagation();},false);
    }
    render() {
        return (
            <div style={{ height: '300px', width: '100%' }} onClick={e => { e.nativeEvent.stopImmediatePropagation(); }}>
                <Table
                    dataSource={this.props.dataSource}
                    rowKey={(record) => record.ID}
                    rowClassName={this.props.priceRule == 2 ? 'item-nocheck' : ''}
                    columns={this.columns}
                    loading={this.props.subLoading}
                    bordered
                    size={'small'}
                    pagination={{ pageSize: 5 }}
                    //scroll={{ x: '200%', y: '500px' }}
                    //onChange={(pagination, filters, sorter) => { }}
                    onRow={(record, index) => ({ onClick: (e) => { this.rowClick(record, index, e) } })}
                />
            </div>
        );
    }
}
function CustomExpandIcon(props) {
    let text, className, icon;
    if (!props.expanded) {
        //text = '&#8679; collapse';//ant-table-row-expand-icon ant-table-row-expanded
        icon = <Icon type="down-circle" theme="twoTone" onClick={e => { e.stopPropagation(); e.nativeEvent.stopImmediatePropagation(); props.onExpand(props.record, e); }} />
        //className = 'ant-table-row-expand-icon ant-table-row-expanded';
    } else {
        icon = <Icon type="up-circle" theme="twoTone" onClick={e => { e.stopPropagation(); e.nativeEvent.stopImmediatePropagation(); props.onExpand(props.record, e); }} />
        //text = '&#8681; expand';//ant-table-row-expand-icon ant-table-row-collapsed
        //className = 'ant-table-row-expand-icon ant-table-row-collapsed';
    }
    return (
        // <a
        //     className={className}  //"expand-row-icon"
        //     onClick={e => {e.stopPropagation();e.nativeEvent.stopImmediatePropagation();props.onExpand(props.record, e);}}
        //     dangerouslySetInnerHTML={{ __html: text }}
        //     style={{ color: 'blue', cursor: 'pointer' }}
        // />
        // <span
        //     className={className}
        //     onClick={e => { e.stopPropagation(); e.nativeEvent.stopImmediatePropagation(); props.onExpand(props.record, e); }}
        // />
        <span style={{ width: '100%', height: '100%' }}>
            {icon}
        </span>
    );
}
class SeletTable extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            expandKeys: [],
            expandTableSource: [],
            subLoading: false
        }
        this.record = null;
        this.columns = [
            {
                title: '序号',
                dataIndex: 'index',
                key: 'index',
                align: 'center',
                width: 30,
                //fixed: true,
                render: function (text, record, index) {
                    return index + 1;
                }
            }, {
                title: '代码',
                dataIndex: 'stockCode',
                key: 'stockCode',
                width: 150,
                align: 'center'
            }, {
                title: '描述',
                dataIndex: 'stockDesc',
                key: 'stockDesc',
                width: 400,
                align: 'center'
            }, {
                title: '规格',
                dataIndex: 'stockSpec',
                key: 'stockSpec',
                width: 60,
                align: 'center'
            }, {
                title: '基本单位',
                dataIndex: 'baseUnitDesc',
                key: 'baseUnitDesc',
                width: 70,
                align: 'center'
            }, {
                title: '入库单位',
                dataIndex: 'purUnitDesc',
                key: 'purUnitDesc',
                width: 70,
                align: 'center',
            }, {
                title: '库存子类',
                dataIndex: 'stkSubCatDesc',
                key: 'stkSubCatDesc',
                align: 'center'
            }
        ];
    }
    rowClick = (stock, index, e) => {
        if (this.props.priceRule == 1) {
            this.expand(stock);
        } else {
            this.props.selectCallBack(stock, "", index, e);
        }
    }
    rowdbClick = (stock, index, e) => {

    }
    batchSelectCall = (batch, index, e) => {
        this.props.selectCallBack(this.record, batch, index, e);
    }
    onExpand = (expand, record) => {
        if (expand) {
            this.record = record;
            this.getBatchDetail(record);
            this.setState({ expandKeys: [record.stockID] });
        } else {
            this.reocrd = null;
            this.setState({ expandKeys: [] });
        }
    }
    ///点击行展开
    expand = (record) => {
        if (this.state.expandKeys.length == 0) {
            this.record = record;
            this.getBatchDetail(record);
            this.setState({ expandKeys: [record.stockID] });
        } else {
            if (this.state.expandKeys[0] == record.stockID) {
                this.reocrd = null;
                this.setState({ expandKeys: [] });
            } else {
                this.record = record;
                this.getBatchDetail(record);
                this.setState({ expandKeys: [record.stockID] });
            }
        }
    }
    getBatchDetail = (record) => {
        const { stockID } = record;
        this.setState({ subLoading: true });
        $http.post("", this, {
            code: '02060148',
            data: { params: [{ stockID: stockID }] },
            success: function (res) {
                if (res.errorCode == 0) {
                    this.setState({ expandTableSource: res.result.rows, subLoading: false });
                } else {

                }
            },
            error: function () {
            }
        });
    }
    expandBatch = (record, index, indent, expanded) => {
        return (<ExpandTable subLoading={this.state.subLoading} priceRule={this.props.priceRule} selectCallBack={this.batchSelectCall} dataSource={this.state.expandTableSource} />);
    }
    componentDidMount() {
        //addEventListener("click",(e)=>{e.stopPropagation();},false);
    }
    render() {
        return (
            <div className={'StockBatchItemSelect'} onClick={e => { e.nativeEvent.stopImmediatePropagation(); }}>
                <Table
                    dataSource={this.props.dataSource}
                    rowKey={(record) => record.stockID}
                    rowClassName={this.props.priceRule == 1 ? 'item-nocheck' : ''}
                    columns={this.columns}
                    bordered
                    loading={this.props.mainLoading}
                    scroll={{ y: '400px' }}
                    onChange={(pagination, filters, sorter) => { }}
                    pagination={false}  //{ pageSize: 5 }
                    onRow={(record, index) => ({ onClick: (e) => { this.rowClick(record, index, e) } })}
                    expandedRowRender={this.expandBatch}
                    expandIcon={CustomExpandIcon}
                    expandedRowKeys={this.state.expandKeys}
                    onExpand={this.onExpand}
                />
            </div>
        );
    }
}
class StockItemSelect extends React.Component {
    constructor(props) {
        super(props);
        const value = props.value || {};
        const visible = props.visible || false;
        this.state = {
            selectDataSource: [],
            visible: visible,
            stockID: value.stockID || '',
            stockDesc: value.stockDesc || '',
            stkBatID: value.stkBatID || '',
            stkBatNo: value.stkBatNo || '',
            input: value.input || '',
            mainLoading: false,
            pagination: [{
                currentPage: 1,
                pageSize: 10
            }]
        }
        this.timeout = null;
        this.currentValue = null;
    }
    static getDerivedStateFromProps(nextProps, prevState) {
        let ret = null;
        if ('value' in nextProps) {
            ret = { ...(nextProps.value || { stockID: '', stockDesc: '', stkBatID: '', stkBatNo: '' }) };
        }
        if ('visible' in nextProps) {
            ret = { ...ret, ...{ visible: nextProps.visible } }
        }
        if ('input' in nextProps) {
            ret = { ...ret, ...{ input: nextProps.input } }
        }
        return ret;
    }
    fetch = (value, callback) => {
        if (this.timeout) {
            clearTimeout(this.timeout);
            this.timeout = null;
        }
        if (value == '') {
            return;
        }
        let currentValue = value;
        const fake = () => {
            this.setState({ mainLoading: true });
            $http.post("", this, {
                code: '02060013',
                data: { params: [{ alias: value }] },
                success: function (res) {
                    //console.log(this);
                    if (currentValue == value) {
                        if (res.result) {
                            callback(res.result);
                            this.setState({ mainLoading: false });
                        }
                    }
                },
                error: function () {
                }
            });
        }
        this.timeout = setTimeout(fake, 500);
    }
    handleSearch = (value) => {
        this.fetch(value, data => this.setState({ selectDataSource: data }));
        let input={ input:value};
        if (!this.state.visible){
            input.visible=true;
        }
        this.setState(input);
        this.triggerChange(input);
        if (!value){
            this.selectElement.input.focus();
        }
    }
    handleSelectChange = (value) => {

    }
    selectFocus() {
        this.selectElement.rcSelect.inputRef.focus();
    }
    selectCallBack = (stock, batch, index, e) => {
        if (this.props.priceRule && this.props.priceRule == 1 && batch == "") {  //批次价时必须选择对应批次
            message.warn("批次价时必须选择对应批次");
            return;
        } else if (this.props.priceRule && this.props.priceRule != 1 && batch != "") {
            message.warn("统一价时不能选择批次");
            return;
        }
        const batID = batch.ID ? batch.ID : '';
        const batNo = batch.BatchNo ? batch.BatchNo : '';
        const value = { stockID: stock.stockID, stockDesc: stock.stockDesc, stkBatID: batID, stkBatNo: batNo, visible: false };
        if (this.props.itemChangeCallback) {
            this.props.itemChangeCallback(stock, batch, index, e);  ///选中table中对应记录的回调
        }
        this.setState(value);
        this.triggerChange(value);
    }
    triggerChange = (changedValue) => {
        const onChange = this.props.onChange;
        if (onChange) {
            const obj = Object.assign({}, this.state, changedValue);
            let value = {};
            for (let key in obj) {
                if (['stockID', 'stockDesc', 'stkBatID', 'stkBatNo','input'].indexOf(key) > -1) {
                    value[key] = obj[key];
                }
            }
            onChange(value);
        }
    }
    componentDidMount() {
        document.addEventListener("click", (e) => { this.state.visible ? this.setState({ visible: false }) : ''; return; }, false);
    }
    shouldComponentUpdate(nextProps, nextState) {
        if (nextState) {
            for (let key in nextState) {
                if (nextState[key] != this.state[key]) {
                    return true;
                }
            }
        }
        return false;
    }
    componentDidUpdate() {
        if (this.state.visible) {
            //this.selectFocus();
        }
    }
    render() {
        const props = this.props;
        return (
            <div onClick={e => e.nativeEvent.stopImmediatePropagation()}>
                <Dropdown
                    visible={this.state.visible}
                    overlayStyle={{ width: '1000px' }}
                    //trigger={'click'}
                    placement={'bottomLeft'}
                    overlay={() => (
                        <SeletTable mainLoading={this.state.mainLoading} priceRule={this.props.priceRule} selectCallBack={this.selectCallBack} dataSource={this.state.selectDataSource} />
                    )}
                >
                    <Input
                        onClick={e=>e.nativeEvent.stopImmediatePropagation()}
                        allowClear
                        ref={el => { this.selectElement = el; }} 
                        //value={this.state.stkBatID ? this.state.stockDesc + '(' + this.state.stkBatNo + ')' : this.state.stockDesc} 
                        placeholder={!this.state.visible?'':this.state.stkBatID ? this.state.stockDesc + '(' + this.state.stkBatNo + ')' : this.state.stockDesc}
                        value={this.state.visible ? this.state.input?this.state.input:'' : this.state.stkBatID ? this.state.stockDesc + '(' + this.state.stkBatNo + ')' : this.state.stockDesc} 
                        onFocus={(e) => { this.handleSearch(''); }} 
                        onBlur={(e) => { }} 
                        onChange={(e) => { this.handleSearch(e.target.value); }} 
                    />
                </Dropdown>
            </div>
        //     <Select
        //     {...props}
        //     showSearch
        //     ref={el => { this.selectElement = el; if (this.props.itemRef) { this.props.itemRef(el); } }}
        //     defaultActiveFirstOption={false}
        //     showArrow={false}
        //     filterOption={false}
        //     onSearch={this.handleSearch}
        //     onFocus={() => { this.setState({ visible: true }) }}
        //     notFoundContent={null}
        //     dropdownRender={(menuNode, props) => {
        //         return (
        //             <SeletTable mainLoading={this.state.mainLoading} priceRule={this.props.priceRule} selectCallBack={this.selectCallBack} dataSource={this.state.selectDataSource} />
        //         );
        //     }}
        //     dropdownMatchSelectWidth={false}
        //     dropdownStyle={{ width: '1000px' }}
        //     //getPopupContainer={(el) => document.getElementById("StockBatchItemSelect")}
        //     open={this.state.visible}
        //     value={this.state.stockID}
        // >
        //     <Select.Option key={this.state.stockID} value={this.state.stockID}> {this.state.stkBatID ? this.state.stockDesc + '(' + this.state.stkBatNo + ')' : this.state.stockDesc}</Select.Option>
        // </Select>
            
        );
    }
}
export default StockItemSelect;