import React from 'react';
import { observer } from 'mobx-react';
import { WeaDialog, WeaNewScroll, WeaLocaleProvider, WeaRightMenu } from 'ecCom';
import { WeaScope, WeaInput, WeaInputNumber, WeaSearchGroup, WeaTab, WeaError, WeaHelpfulTip } from 'ecCom';
const getLabel = WeaLocaleProvider.getLabel;
import { Button, Table, Modal, message } from 'antd';
import { observable, toJS, } from "mobx";
import { WeaForm } from 'comsMobx';
import $ from 'jquery';

@observer
export default class QuickSearchDetail extends React.Component {
    constructor(props) {
        super(props);
    }


    onSelectChange = (keys, rows) => {
        let keyarr = [];
        rows.map(row => {
            keyarr.push(row.key);
        });
        const { quickSearch } = this.props;
        quickSearch.qcDetailRowKeys = keyarr;
    }

    save = () => {
        const { quickSearch } = this.props;
        quickSearch.saveQuickSearchDetailInfo();
    }

    closeDialog = () => {
        const { quickSearch } = this.props;
        quickSearch.quickSearchDetailVisable = false;
    }

    onChange = (data) => {
        const { quickSearch } = this.props;
        quickSearch.setQuickSearchDetailData(data);
    }

    getSearchButton = () => {
        const { quickSearch } = this.props;
        const buttons = new Array();
        buttons.push(<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@spalvu@addRow`} type="primary" shape="circle" title={getLabel(611, '添加')} size="small" disabled={0} onClick={() => {
            this.addRow();
        }}><i className="anticon anticon-plus"></i></Button>);
        buttons.push(<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@zz4kgt@delRow`} title={getLabel(126371, '删除')} shape="circle" size="small" onClick={() => {
            this.delRow();
        }} ><i className="anticon anticon-minus"></i></Button>);
    
        return buttons;
    }

    addRow = () => {
        const { quickSearch } = this.props;
        let { quickSearchDetailData } = quickSearch;
        let datas = quickSearchDetailData;
        let time = new Date().getTime();
        let obj = {
            key: "new_" + time,
            customname: '',
            orderid: 0,
            minnum: '',
            maxnum: '',
            type: quickSearch.qcData.qcType,
            fieldid: quickSearch.qcData.fieldid,
            customid: quickSearch.customid
        }
        datas = toJS(datas);
        datas.push(obj);
        quickSearch.setQuickSearchDetailData(datas);
    }

    delRow = () => {
        const { quickSearch } = this.props;
        let { qcDetailRowKeys } = quickSearch;
        if (qcDetailRowKeys.length <= 0) {
            message.error(getLabel(22346, '请选择要删除的信息', 'label'));
            return;
        }
        const that = this;
        Modal.confirm({
            title: getLabel(83601, '您确认要删除选中的记录吗？'),
            onOk() {
                let datas = quickSearch.quickSearchDetailData;
                datas = toJS(datas);
                datas = that.delFromArray(datas, qcDetailRowKeys);
                quickSearch.qcDetailRowKeys = [];
                quickSearch.setQuickSearchDetailData(datas);
            },
            onCancel() { },
        });
    }

    delFromArray = (array, selectRowIds) => {
        for (let i = 0; i < selectRowIds.length; i++) {
            let key = selectRowIds[i];
            for (let j = 0; j < array.length; j++) {
                if (array[j]["key"] == key) {
                    array.splice(j, 1);
                    break;
                }
            }
        }
        return array;
    }

    render() {
        const { quickSearch: store } = this.props, {
            qcDetailRowKeys
        } = store;
        const rowSelection = {
            qcDetailRowKeys,
            onChange: this.onSelectChange,
        }
        const Height = $(".wea-dialog-body")[0] && $(".wea-dialog-body")[0].style.height;
        const buttons = [
            <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@va8uvk@save`} onClick={() => this.save()} type="primary">{getLabel(86, "保存")}</Button>,
            <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@edy7ux@closeDialog`} onClick={() => {
 this.closeDialog() 
}}>{getLabel(309, "关闭")}</Button>
        ]
        return (
            <WeaDialog ecId={`${this && this.props && this.props.ecId || ''}_WeaDialog@d0kgwh`} style={{ width: 800, height: 550 }}
                visible={store.quickSearchDetailVisable} 
                title={getLabel('387685', "自定义条件设置")}
                iconBgcolor="#217346"
                icon='icon-coms-hrm'
                onCancel={this.closeDialog}
                buttons={buttons}
            >
                 <WeaNewScroll ecId={`${this && this.props && this.props.ecId || ''}_WeaNewScroll@x6apdm`} ref="sc" height={Height?Height:530}>
                        <WeaSearchGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaSearchGroup@d5750t`} needTigger={false} showGroup={true} >
                            <WeaTab ecId={`${this && this.props && this.props.ecId || ''}_WeaTab@85m7gk`}
                                keyParam="key"  //主键
                                buttons={this.getSearchButton()}
                            />
                            <QuickSearchTableEdit ecId={`${this && this.props && this.props.ecId || ''}_QuickSearchTableEdit@immgug`}
                                datas={toJS(store.quickSearchDetailData)}
                                precision={store.precision}
                                onChange={this.onChange}
                                rowSelection={rowSelection}
                                ListProps={this.props}
                            />
                        </WeaSearchGroup>
                    </WeaNewScroll>

            </WeaDialog>
        )
    }


}

@observer
class QuickSearchTableEdit extends  React.Component{
    
    getColumns = () => {
        let columnArray = [
            {
                title: getLabel(547517, "名称"), dataIndex: "customname", key: "customname", width: "40%",
                com: [{ label: '', type: 'INPUT', key: 'customname', viewAttr: 3, otherParams: { isBase64: true, inputType: "multilang" } }]
            },
            {
                title: <div>
                    {getLabel(547379, "内容自定义条件")}&nbsp;
                    <WeaHelpfulTip ecId={`${this && this.props && this.props.ecId || ''}_WeaHelpfulTip@6znscx@condition`}
                        width =  {196} //如果要自定义宽度，在这里设置
                        title={getLabel('547630','数值关系: 下限值 <= 数值 < 上限值') }
                    />
                </div>, dataIndex: "condition", key: "condition", width: "40%",
                com: [{ label: '', type: 'SCOP', key: 'condition', viewAttr: 3 }]
            },
            {
                title: getLabel(547631, "顺序"), dataIndex: "orderid", key: "orderid", width: "20%",
                com: [{ label: '', type: 'INPUTNUMBER', key: 'orderid', viewAttr: 2, otherParams: { max: 999, step: 1 } }]
            }
        ];
        columnArray = columnArray.map((col) => {
            let _col = { ...col };
            _col.render = (text, record, index) => {
                return this.getColRender(_col, text, record, index);
            }
            return _col
        });
        return columnArray;
    }
    
    getColRender = (_col, text, record, index) => {
        const { datas } = this.props;
        const { quickSearch: { quickSearchRefObj } } = this.props.ListProps;
        const { com, } = _col;
        let _com = [];
        com.map((c) => {
            if (typeof c.props === 'object') {
                _com.push(<span></span>);
            } else {
                const { key, viewAttr = 2, type = 'INPUT', width, otherParams = {} } = c;
                const _type = type.toUpperCase();
                _com.push(
                    <span>
                        {
                            _type === 'INPUT' &&
                            <WeaError ecId={`${this && this.props && this.props.ecId || ''}_WeaError@z6mgxq@${index}`}
                                tipPosition={(index == 0 || index+1==datas.length) ? 'top':'bottom'}
                                error={getLabel('385869', "此项必填")}
                                style={{ width: "98%" }}
                                ref={ref => quickSearchRefObj[`error_${key}_${index}`] = ref}
                            >
                                <WeaInput ecId={`${this && this.props && this.props.ecId || ''}_WeaInput@mz6i71@${index}`}
                                    value={record[key]}
                                    viewAttr={viewAttr}
                                    onChange={(value) => this.onEdit(record, index, key, value)}
                                    {...otherParams}
                                />
                            </WeaError>
                        }
                        {
                            _type === 'SCOP' &&
                            <WeaError ecId={`${this && this.props && this.props.ecId || ''}_WeaError@bvnfbi@${index}`}
                                tipPosition={(index == 0 || index+1==datas.length) ? 'top':'bottom'}
                                error={getLabel('385869', "此项必填")}
                                ref={ref => quickSearchRefObj[`error_${key}_${index}`] = ref}
                            >
                                <div className={(record['minnum'] === '' || record['minnum'] == undefined) && (record['maxnum'] === '' || record['maxnum'] == undefined) ? "required" : ""}>
                                    <WeaScope ecId={`${this && this.props && this.props.ecId || ''}_WeaScope@zu7wra@${index}`}
                                        isMobx
                                        hideOps={true}
                                        precision={this.props.precision}
                                        value={[record['minnum'], record['maxnum']]}
                                        onChange={(value) => this.onEdit(record, index, key, value)}
                                    />
                                </div>
                            </WeaError>
                        }
                        {
                            _type === 'INPUTNUMBER' &&
                            <WeaInputNumber ecId={`${this && this.props && this.props.ecId || ''}_WeaInputNumber@chty4d@${index}`}
                                value={record[key]}
                                style={{ width, display: 'inline-block' }}
                                viewAttr={viewAttr}
                                onChange={(value1) => this.onEdit(record, index, key, value1)}
                                {...otherParams}
                            />
                        }
                    </span>
                )
            }
        });
        return (
            <div>
                {_com}
            </div>
        )
    }

    onEdit = (record, index, key, value) => {
        const { datas } = this.props;
        let _datas = [...datas];
        _datas[index][key] = value;
        if (key == 'condition') {
            _datas[index].minnum = value[0] === undefined ? "" : value[0];
            _datas[index].maxnum = value[1] === undefined ? "" : value[1];
        }
        typeof this.props.onChange === 'function' && this.props.onChange(_datas);
    }

    render() {
        const { datas, rowSelection } = this.props;
        return (
            <div className="wev-cube-table-inner-warp">
                <Table ecId={`${this && this.props && this.props.ecId || ''}_Table@nytlcm`}
                    rowSelection={rowSelection}
                    columns={this.getColumns()}
                    dataSource={datas}
                    pagination={false}
                />
            </div>
        )
    }
}
