import React from 'react';
import { Row, Col, Button, Form, Input, Select, Table, InputNumber, DatePicker, Dropdown, Popconfirm, message, Card, Icon } from 'antd';
import { $http } from '../../../containers/config/https';
import store from 'store';
import moment from 'moment';
import { StockBatchItemSelect, NewSelect } from '../Common';
import ColumnAuthoritysModel from 'pages/columnAuthority/ColumnAuthoritysModel';
import './style/AdjUnite.less';

class EditableRowForm extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            unit: [],
            prePrice: {},
            data: {},
            language : JSON.parse(window.sessionStorage.userData),
            ChineseEnglishSize:{}
        }
    }
    componentWillReceiveProps(props){
        this.setState({ChineseEnglishSize:props.ChineseEnglishSize})
    }
    addOneData = () => {
        this.props.form.validateFields((error, values) => {
            if (error) {
                return;
            }
            values = this.formatValues(values);
            //console.log(values);
            let ret = false;
            if (this.state.key && this.adjID) {
                ret = this.props.updateOneData(this.state.key, values);
            } else {
                ret = this.props.addOneData(values, this.state.key);
            }
            if (ret) {
                this.clearAllInput();
            }
        });
    }
    clearAllInput = () => {
        const { adjReason, preExeDate } = this.props.commonParams;
        let item = ['stock', 'priorSp', 'resultSp', 'unit', 'resultBaseSp', 'remark', 'warrentNO', 'WNODate', 'hosp']
        if (adjReason !== 'Y') {
            item.push('reason');
        }
        if (preExeDate !== 'Y') {
            item.push('preExeDate');
        }
        //console.log(this);
        this.props.form.resetFields(item);
        this.setState({ key: '', unitOpt: [] });
        this.adjID = '';
    }

    formatValues = (values) => {
        for (let key in values) {
            if (values[key] && values[key] instanceof moment) {
                values[key] = values[key].format("YYYY-MM-DD");
            }
        }
        return values;
    }
    itemChangeCallback = (stock, batch, index, e) => {
        let {ChineseEnglishSize} = this.state;
        this.clearAllInput();
        $http.post("", this, {
            code: '02020039',
            data: { params: [{ stockID: stock.stockID, stkBatID: batch.ID }] },
            success: function (res) {
                if (res.result) {
                    let unitOpt = [];
                    if ('unit' in res.result) {
                        res.result.unit.map((value, key) => {
                            unitOpt.push(<Select.Option key={value.id} type={value.type} fac={value.fac} value={value.id}>{value.desc}</Select.Option>);
                        })
                    }
                    this.setState({ unitOpt: unitOpt, prePrice: res.result.price });
                    this.unit = res.result.unit;
                    const PriorSp = res.result.price.price || 0;
                    const ResultBaseSp = res.result.price.baseSp;
                    const UnitDr = res.result.price.unit || {};
                    //console.log(UnitDr);
                    this.props.form.setFieldsValue({ 'priorSp': PriorSp, "resultBaseSp": ResultBaseSp, "resultSp": PriorSp, "unit": UnitDr });  //'ResultBaseSp': PriorSp,
                }
            },
            error: function () {
                this.setState({ errMsg: ChineseEnglishSize.PriceAdjustmentFormEnttryAgain ? ChineseEnglishSize.PriceAdjustmentFormEnttryAgain.descripts:"数据加载失败，请重试!" });
            }
        });
    }
    tableDataToForm = (data) => {
        let {ChineseEnglishSize} = this.state;
        if (!data || Object.keys(data).length == 0) {
            this.clearAllInput();
            return;
        }
        for (let key in data) {
            if (data[key]) {
                const { stockID, stkBatID } = data[key].stock;
                $http.post("", this, {
                    code: '02020039',
                    data: { params: [{ stockID: stockID, stkBatID: stkBatID }] },
                    success: function (res) {
                        if (res.result) {
                            let unitOpt = [];
                            if ('unit' in res.result) {
                                res.result.unit.map((value, key) => {
                                    unitOpt.push(<Select.Option key={value.id} type={value.type} fac={value.fac} value={value.id}>{value.desc}</Select.Option>);
                                })
                            }
                            this.setState({ unitOpt: unitOpt, prePrice: res.result.price, key: key });
                            this.adjID = data[key].adjID;
                            this.unit = res.result.unit;
                            this.props.form.setFieldsValue(data[key]);    //browser.js:49 Warning: You cannot set a form field before rendering a field associated with the value.
                            // const PriorSp = res.result.price.price || 0;
                            // const ResultBaseSp = res.result.price.baseSp;
                            // const UnitDr = res.result.price.Unit || { id: record.BaseUomDr };
                            // //console.log(UnitDr);
                            // this.props.form.setFieldsValue({ 'PriorSp': PriorSp, "ResultBaseSp": ResultBaseSp, "ResultSp": PriorSp, "UnitDr": UnitDr });  //'ResultBaseSp': PriorSp,
                        }
                    },
                    error: function () {
                        this.setState({ errMsg: ChineseEnglishSize.PriceAdjustmentFormEnttryAgain ? ChineseEnglishSize.PriceAdjustmentFormEnttryAgain.descripts:"数据加载失败，请重试!" });
                    }
                });
            }
        }
    }

    onUnitChange = (value, option) => {
        const { prePrice } = this.state;
        let PriorSp = prePrice.price || 0;
        const { fac, type } = option.props;
        let baseSp = '';
        if (prePrice.unit && prePrice.unit.id && prePrice.unit.id != value.id) {
            if (type == 'base') {
                PriorSp = PriorSp / fac;
                baseSp = PriorSp;
            } else {
                baseSp = PriorSp;
                PriorSp = PriorSp * fac;
            }
        } else {
            //PriorSp = prePrice.price||0;
            if (type == 'base') {
                baseSp = PriorSp;
            } else {
                baseSp = PriorSp / fac;
            }
        }
        baseSp = this.fomatBaseSp(baseSp);
        this.setState({ unitType: type });
        this.props.form.setFieldsValue({ priorSp: PriorSp, resultSp: PriorSp, resultBaseSp: baseSp });
    }
    fomatBaseSp(baseSp) {
        baseSp = baseSp ? baseSp : 0;
        const { fmtSP } = this.props.commonParams;
        const length = fmtSP.split('.')[1].length + 4;
        const num = Math.pow(10, length);
        return Math.round(baseSp * num) / num;
    }
    onReSpChange = (e) => {
        //const { prePrice } = this.state;
        const UnitDr = this.props.form.getFieldValue('unit');
        if (!UnitDr) {
            return;
        }
        let baseSp = 0, sel = {};
        this.unit.map((value, key) => {
            value.id === UnitDr.id ? sel = value : '';
        });
        if (sel.type == 'purch') {
            baseSp = e / sel.fac;
        } else {
            baseSp = e;
        }
        baseSp = this.fomatBaseSp(baseSp);
        this.props.form.setFieldsValue({ resultBaseSp: baseSp });
    }
    validatorResultSp = (rule, value, callback) => {
        let {ChineseEnglishSize} = this.state;
        let num = this.getSpPrecision();
        const priorSp = this.props.form.getFieldValue('priorSp');
        if (!value) {
            // 当value值不存在的话
            callback(ChineseEnglishSize.PriceAdjustmentFormEntpriceNotNull ? ChineseEnglishSize.PriceAdjustmentFormEntpriceNotNull.descripts:'售价不能为空');
        } else if (priorSp === value) {
            callback(ChineseEnglishSize.PriceAdjustmentFormEntadjPriceTips ? ChineseEnglishSize.PriceAdjustmentFormEntadjPriceTips.descripts:"调后售价不能等于调前售价");
        } else {
            let re = new RegExp("^-?\\d+(\\.\\d{1," + num + "})?$");
            if (!re.test(value)) {
                callback(ChineseEnglishSize.PriceAdjustmentFormEntdecimalTips ? ChineseEnglishSize.PriceAdjustmentFormEntdecimalTips.descripts:"小数位数不能超过" + num + ChineseEnglishSize.PriceAdjustmentFormEntdigits ? ChineseEnglishSize.PriceAdjustmentFormEntdigits.descripts:"位");
            }
        }
        callback();
    }
    getSpPrecision = () => {
        let ret = 2;
        if (this.props.commonParams.fmtSP) {
            ret = this.props.commonParams.fmtSP.split('.')[1].length;
            if (this.state.unitType == 'base') {
                ret = ret + 4;
            }
        }
        return ret;
    }
    render() {
        let {ChineseEnglishSize,language} = this.state;
        const { getFieldDecorator, setFieldsValue } = this.props.form;
        const { priceRule } = this.props.commonParams;
        let { reasonOpt, hospOpt } = this.props.opt;
        reasonOpt = reasonOpt ? reasonOpt : [];
        hospOpt = hospOpt ? hospOpt : [];
        const itemSpan = { labelCol: { span: 8 }, wrapperCol: { span: 16 } }
        const { userData } = sessionStorage;
        const obj = JSON.parse(userData);
        return (
            <div style={{ height: store.getState().tableHeight.y + 'px' }}>
                <Form layout={'horizontal'}>
                    <Row>
                        <Col span={24}>
                            <Form.Item label={ChineseEnglishSize.PriceAdjustmentFormEntdrugName ? ChineseEnglishSize.PriceAdjustmentFormEntdrugName.descripts:'药品名称'} labelCol={{ span: 4 }} wrapperCol={{ span: 20 }}>
                                {getFieldDecorator('stock', {
                                    rules: [{
                                        required: true,
                                        message: ChineseEnglishSize.PriceAdjustmentFormEntnotNull ? ChineseEnglishSize.PriceAdjustmentFormEntnotNull.descripts:'不能为空'
                                    }]
                                })(<StockBatchItemSelect priceRule={priceRule ? priceRule : ''} itemChangeCallback={this.itemChangeCallback} />)}
                            </Form.Item>
                        </Col>
                        {/* <Col span={12}>
                        <Form.Item label={'批号'} {...itemSpan}>
                            {getFieldDecorator('BatNo', {
                                rules: [{
                                    required: false,
                                    message: '不能为空'
                                }]
                            })(<Input />)}
                        </Form.Item>
                    </Col> */}
                        <Col span={12}>
                            <Form.Item label={ChineseEnglishSize.PriceAdjustmentFormEntpreAdjPrice ? ChineseEnglishSize.PriceAdjustmentFormEntpreAdjPrice.descripts:'调前售价'} {...itemSpan}>
                                {getFieldDecorator('priorSp', {
                                    rules: [{
                                        required: true,
                                        message: ChineseEnglishSize.PriceAdjustmentFormEntnotNull ? ChineseEnglishSize.PriceAdjustmentFormEntnotNull.descripts:'不能为空'
                                    }]
                                })(<InputNumber style={{ width: '100%' }} disabled />)}
                            </Form.Item>
                        </Col>
                        <Col span={12}>
                            <Form.Item label={ChineseEnglishSize.PriceAdjustmentFormEntadjPrice ? ChineseEnglishSize.PriceAdjustmentFormEntadjPrice.descripts:'调后售价'} {...itemSpan}>
                                {getFieldDecorator('resultSp', {
                                    rules: [{
                                        required: true,
                                        validator: this.validatorResultSp
                                    }]
                                })(<InputNumber style={{ width: '100%' }} min={0} onChange={this.onReSpChange} />)}
                            </Form.Item>
                        </Col>
                        <Col span={12}>
                            <Form.Item label={ChineseEnglishSize.PriceAdjustmentFormEntpriceAdjUnit ? ChineseEnglishSize.PriceAdjustmentFormEntpriceAdjUnit.descripts:'调价单位'} {...itemSpan}>
                                {getFieldDecorator('unit', {
                                    rules: [{
                                        required: true,
                                        message: ChineseEnglishSize.PriceAdjustmentFormEntnotNull ? ChineseEnglishSize.PriceAdjustmentFormEntnotNull.descripts:'不能为空'
                                    }]
                                })(<NewSelect onSelectChange={this.onUnitChange}>{this.state.unitOpt}</NewSelect>)}
                            </Form.Item>
                        </Col>
                        <Col span={12}>
                            <Form.Item label={ChineseEnglishSize.PriceAdjustmentFormEntpirce ? ChineseEnglishSize.PriceAdjustmentFormEntpirce.descripts:'单价(基本)'} {...itemSpan}>
                                {getFieldDecorator('resultBaseSp', {
                                    rules: [{
                                        required: true,
                                        message: ChineseEnglishSize.PriceAdjustmentFormEntnotNull ? ChineseEnglishSize.PriceAdjustmentFormEntnotNull.descripts:'不能为空'
                                    }]
                                })(<InputNumber style={{ width: '100%' }} disabled />)}
                            </Form.Item>
                        </Col>
                        <Col span={12}>
                            <Form.Item label={ChineseEnglishSize.PriceAdjustmentFormEnteffDate ? ChineseEnglishSize.PriceAdjustmentFormEnteffDate.descripts:'计划生效日期'} {...itemSpan}>
                                {getFieldDecorator('preExeDate', {
                                    rules: [{
                                        required: true,
                                        message: ChineseEnglishSize.PriceAdjustmentFormEntnotNull ? ChineseEnglishSize.PriceAdjustmentFormEntnotNull.descripts:'不能为空'
                                    }],
                                    initialValue: new moment(new Date()).add(1, 'day')
                                })(<DatePicker style={{ width: '100%' }} format="YYYY-MM-DD" disabledDate={(cur) => {
                                    return cur && cur < moment().endOf('day');
                                }} />)}
                            </Form.Item>
                        </Col>
                        <Col span={12}>
                            <Form.Item label={ChineseEnglishSize.PriceAdjustmentFormEntreason ? ChineseEnglishSize.PriceAdjustmentFormEntreason.descripts:'调价原因'} {...itemSpan}>
                                {getFieldDecorator('reason', {
                                    rules: [{
                                        required: true,
                                        message: ChineseEnglishSize.PriceAdjustmentFormEntnotNull ? ChineseEnglishSize.PriceAdjustmentFormEntnotNull.descripts:'不能为空'
                                    }]
                                })(<NewSelect>{reasonOpt}</NewSelect>)}
                            </Form.Item>
                        </Col>
                        <Col span={12}>
                            <Form.Item label={ChineseEnglishSize.PriceAdjustmentFormEntremark ? ChineseEnglishSize.PriceAdjustmentFormEntremark.descripts:'备注'} {...itemSpan}>
                                {getFieldDecorator('remark', {
                                    rules: [{
                                        required: false,
                                        message: '不能为空'
                                    }]
                                })(<Input />)}
                            </Form.Item>
                        </Col>
                        <Col span={12}>
                            <Form.Item label={ChineseEnglishSize.PriceAdjustmentFormEntapprovalNum ? ChineseEnglishSize.PriceAdjustmentFormEntapprovalNum.descripts:'批准文号'} {...itemSpan}>
                                {getFieldDecorator('warrentNO', {
                                    rules: [{
                                        required: false,
                                        message: '不能为空'
                                    }]
                                })(<Input />)}
                            </Form.Item>
                        </Col>
                        <Col span={12}>
                            <Form.Item label={ChineseEnglishSize.PriceAdjustmentFormEntapprovalDate ? ChineseEnglishSize.PriceAdjustmentFormEntapprovalDate.descripts:'批文日期'} {...itemSpan}>
                                {getFieldDecorator('WNODate', {
                                    rules: [{
                                        required: false,
                                        message: '不能为空'
                                    }]
                                })(<DatePicker style={{ width: '100%' }} format="YYYY-MM-DD" />)}
                            </Form.Item>
                        </Col>
                        <Col span={12}>
                            <Form.Item label={ChineseEnglishSize.PriceAdjustmentFormEnthospotal ? ChineseEnglishSize.PriceAdjustmentFormEnthospotal.descripts:'医院'} {...itemSpan}>
                                {getFieldDecorator('hosp', {
                                    rules: [{
                                        required: true,
                                        message: ChineseEnglishSize.PriceAdjustmentFormEntnotNull ? ChineseEnglishSize.PriceAdjustmentFormEntnotNull.descripts:'不能为空'
                                     }],
                                    initialValue: { id: +obj.hospID }
                                })(<NewSelect disabled>{hospOpt}</NewSelect>)}
                            </Form.Item>
                        </Col>
                        {language.language=='EN'?
                            <Col span={24}>
                            <Button type={'primary'} htmlType={'submit'} style={{ float: 'right', margin: '0px 20px' }} onClick={this.addOneData}>{this.state.key ? 'modify' : 'Add'}</Button>
                            <Button type={'primary'} htmlType={'reset'} style={{ float: 'right' }} onClick={this.clearAllInput}>Clear</Button>
                        </Col>:<Col span={24}>
                            <Button type={'primary'} htmlType={'submit'} style={{ float: 'right', margin: '0px 20px' }} onClick={this.addOneData}>{this.state.key ? '修改' : '添加'}</Button>
                            <Button type={'primary'} htmlType={'reset'} style={{ float: 'right' }} onClick={this.clearAllInput}>清空</Button>
                        </Col>}
                    </Row>
                </Form>
            </div>

        );
    }
}
class ConditionFields extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            language : JSON.parse(window.sessionStorage.userData),
            ChineseEnglishSize:{}
        }
    }
    componentWillReceiveProps(props){
        this.setState({ChineseEnglishSize:props.ChineseEnglishSize})
    }
    search = () => {
        let {ChineseEnglishSize} = this.state;
        this.props.form.validateFields((error, values) => {
            for (let key in values) {
                if (values[key] && values[key] instanceof (moment)==true) {
                    values[key] = values[key].format('YYYY-MM-DD');
                }
            }
            values.state = 'no';
            $http.post("", this, {
                code: '02020044',
                data: { params: [values] },
                success: function (res) {
                    if (res.errorCode == "0") {
                        this.props.clickEvents.addSearch(res.result);
                        if (res.result.length == 0) {
                            message.warning(ChineseEnglishSize.PriceAdjustmentFormEntnoData ? ChineseEnglishSize.PriceAdjustmentFormEntnoData.descripts:"未查询到数据");
                        } else {
                            message.success(res.errorMessage);
                        }
                    } else {
                        message.error(res.errorMessage);
                    }
                },
                error: function () {
                    this.setState({ errMsg: ChineseEnglishSize.PriceAdjustmentFormEnttryAgain ? ChineseEnglishSize.PriceAdjustmentFormEnttryAgain.descripts:"数据加载失败，请重试!" });
                }
            });
        });
    }
    save = () => {
        this.props.clickEvents.save();
    }
    del = () => {
        this.props.clickEvents.del();
    }
    render() {
        const { getFieldDecorator } = this.props.form;
        let {ChineseEnglishSize,language} = this.state;
        const formStype = {
            labelCol: {
                xs: { span: 9 },
                sm: { span: 10 },
                md: { span: 6 }
            },
            wrapperCol: {
                xs: { span: 15 },
                sm: { span: 14 },
                md: { span: 18 }
            },
        };
        return (
            <Row style={{ marginTop: '18px', marginLeft: '10px' }}>
                <Col span={18}>
                    <Form>
                        <Row>
                            <Col span={6}>
                                <Form.Item label={ChineseEnglishSize.PriceAdjustmentFormEntStartDate ? ChineseEnglishSize.PriceAdjustmentFormEntStartDate.descripts:'开始日期'} {...formStype}>
                                    {getFieldDecorator('startDate', {
                                        rules: [{
                                            required: false,
                                            message: '不能为空'
                                        }],
                                        initialValue: moment(new Date)
                                    })(<DatePicker />)}
                                </Form.Item>
                            </Col>
                            <Col span={6}>
                                <Form.Item label={ChineseEnglishSize.PriceAdjustmentFormEntdeadline ? ChineseEnglishSize.PriceAdjustmentFormEntdeadline.descripts:'结束日期'} {...formStype}>
                                    {getFieldDecorator('endDate', {
                                        rules: [{
                                            required: false,
                                            message: '不能为空'
                                        }],
                                        initialValue: moment(new Date)
                                    })(<DatePicker />)}
                                </Form.Item>
                            </Col>
                        </Row>
                    </Form>
                </Col>
                <Col span={6}>
                    <Row>
                        <Button onClick={this.search} style={{ margin: '0px 16px 16px 0px' }}>{ChineseEnglishSize.PriceAdjustmentFormEntsearch ? ChineseEnglishSize.PriceAdjustmentFormEntsearch.descripts:'查询'}</Button>
                        <Button style={{ margin: '0px 16px 16px 0px' }} type={'primary'} onClick={this.save}>{ChineseEnglishSize.PriceAdjustmentFormEntsave ? ChineseEnglishSize.PriceAdjustmentFormEntsave.descripts:'保存'}</Button>
                        <Popconfirm placement={'topRight'} title={ChineseEnglishSize.PriceAdjustmentFormEntconfirmDelete ? ChineseEnglishSize.PriceAdjustmentFormEntconfirmDelete.descripts:'确认是否删除？'} onConfirm={this.del} okText={language.language=='EN'?"YES":"是"} cancelText={language.language=='EN'?"NO":"否"}>
                            <Button type={'danger'} disabled={this.props.selectKeys.length == 0 ? true : false}>{ChineseEnglishSize.PriceAdjustmentFormEntDelete ? ChineseEnglishSize.PriceAdjustmentFormEntDelete.descripts:'删除'}</Button>
                        </Popconfirm>
                    </Row>
                    {/* <Row>

                    </Row> */}
                </Col>
            </Row>
        );
    }
}
const RowForm = Form.create()(EditableRowForm);
const ConditionForm = Form.create()(ConditionFields);
class AdjUnite extends React.Component {
    constructor(props) {
        super(props);
        this.opt = {};
        this.state = {
            formData: {},
            collapsed: false,
            selectedRowKeys: [],
            selectNow: '',
            dataSource: [],
            commonParams: {},
            opt: {},
            columns:[],
            columnsWidth:'',
            language : JSON.parse(window.sessionStorage.userData),
            ChineseEnglishSize:{}
        };
        this.columns = [
            {
                title: '序号',
                dataIndex: 'index',
                key: 'index',
                align: 'center',
                width: 30,
                render: (text, record, index) => {
                    const i = this.state.dataSource.findIndex(r => r === record);
                    return i + 1;
                }
            }, {
                title: '单号',
                dataIndex: 'adjNO',
                key: 'adjNO',
                align: 'center',
                width: 150
            }, {
                title: '调前售价',
                dataIndex: 'priorSp',
                key: 'priorSp',
                width: 81,
                align: 'center',
            }, {
                title: '调后售价',
                dataIndex: 'resultSp',
                key: 'resultSp',
                width: 81,
                align: 'center',
            }, {
                title: '单位',
                dataIndex: 'unit',
                key: 'unit',
                width: 50,
                align: 'center',
                render: (text, record) => {
                    return text ? text.desc : '';
                }
            }, {
                title: '单价(基本)',
                dataIndex: 'resultBaseSp',
                key: 'resultBaseSp',
                width: 100,
                align: 'center'
            }, {
                title: '计划生效日期',
                dataIndex: 'preExeDate',
                key: 'preExeDate',
                width: 120,
                align: 'center',
            }, {
                title: '调价原因',
                dataIndex: 'reason',
                key: 'reason',
                width: 100,
                align: 'center',
                render: (text, record) => {
                    return text ? text.desc : '';
                }
            }, {
                title: '备注',
                dataIndex: 'remark',
                key: 'remark',
                width: 80,
                align: 'center'
            }, {
                title: '批准文号',
                dataIndex: 'warrentNO',
                key: 'warrentNO',
                width: 120,
                align: 'center',
            }, {
                title: '批文日期',
                dataIndex: 'WNODate',
                key: 'WNODate',
                width: 120,
                align: 'center',
            }, {
                title: '状态',
                dataIndex: 'state',
                key: 'state',
                width: 80,
                align: 'center',
                render: (text, record) => {
                    return text ? text.desc : '';
                }
            }, {
                title: '医院',
                dataIndex: 'hosp',
                key: 'hosp',
                width: 120,
                align: 'center',
                render: (text, record) => {
                    return text ? text.desc : '';
                }
            }, {
                title: '创建人',
                dataIndex: 'createUser',
                key: 'createUser',
                width: 80,
                align: 'center',
                render: (text, record) => {
                    return text ? text.desc : '';
                }
            }
        ];
    }
    check = (record, index, event) => {
        const key = this.state.dataSource.findIndex(r => r === record);
        //let key = index + (this.state.current - 1) * this.state.pageSize;
        const selectedRowKeys = [...this.state.selectedRowKeys];
        if (selectedRowKeys.indexOf(key) == -1) {
            this.setState({ selectedRowKeys: [...new Set([...selectedRowKeys, key])], selectNow: key });
            this.dataToForm(key);
        } else {
            let ind = selectedRowKeys.indexOf(key);
            selectedRowKeys.splice(ind, 1);
            this.setState({ selectedRowKeys: [...new Set(selectedRowKeys)], selectNow: '' });
            this.dataToForm();
        }
    }
    //删除选中行
    delRow = () => {
        const selectedRowKeys = [...this.state.selectedRowKeys];
        let storeData = [], localData = [];
        selectedRowKeys.map((value, index) => {
            if (this.state.dataSource[value]) {
                const record = this.state.dataSource[value];
                if (record.adjID) {
                    storeData.push(record.adjID);
                }
                localData.push(value);
            }
        });
        this.delData(localData);
        this.delStoreData(storeData);
        this.setState({ selectedRowKeys: [] });
        this.dataToForm();
    }
    //本地删除数据
    delData = (delSource) => {
        const dataSource = [...this.state.dataSource];
        if (delSource.length == 0) {
            return;
        }
        delSource.map((value, index) => {
            delete dataSource[Number(value)];
        });
        const newArr = dataSource.filter((value) => value);
        this.setState({ dataSource: newArr });
    }
    //删除远程数据
    delStoreData = (delSource) => {
        let {ChineseEnglishSize} =this.state;
        if (delSource.length == 0) {
            return;
        }
        $http.post("", this, {
            code: '02020077',
            data: { params: delSource },
            success: function (res) {
                if (res.errorCode == 0) {
                    message.success(res.errorMessage);
                } else {
                    message.error(res.errorMessage);
                }
            },
            error: function () {
                this.setState({ errMsg: ChineseEnglishSize.PriceAdjustmentFormEnttryAgain ? ChineseEnglishSize.PriceAdjustmentFormEnttryAgain.descripts:"数据加载失败，请重试!" });
            }
        });
    }
    //选中行变化时
    onTableSelectChange = (selectedRowKeys, selectedRows) => {
        this.setState({ selectedRowKeys: [...new Set(selectedRowKeys)] });
    }
    clickEvents = {
        addSearch: (data) => {
            //console.log(data);
            this.setState({ dataSource: data, selectedRowKeys: [] });
        },
        save: () => {
            let {ChineseEnglishSize} =this.state;
            if (this.state.dataSource.length == 0) {
                message.warning(ChineseEnglishSize.PriceAdjustmentFormEntnoSaveData ? ChineseEnglishSize.PriceAdjustmentFormEntnoSaveData.descripts:"暂无数据需要保存");
                return;
            }
            $http.post("", this, {
                code: '02020040',
                data: { params: this.state.dataSource },
                success: function (res) {
                    if (res.errorCode == 0) {
                        message.success(res.errorMessage);
                        if (res.result) {
                            this.setState({ dataSource: res.result });
                        }
                    } else {
                        message.error(res.errorMessage);
                    }
                },
                error: function () {
                    let {ChineseEnglishSize} =this.state;
                    this.setState({ errMsg: ChineseEnglishSize.PriceAdjustmentFormEnttryAgain ? ChineseEnglishSize.PriceAdjustmentFormEnttryAgain.descripts:"数据加载失败，请重试!" });
                }
            });
        },
        del: this.delRow
    }
    addOneData = (oneData, key) => {
        let {ChineseEnglishSize} =this.state;
        let ret = true;
        const { stock } = oneData;
        const { stockID, stockDesc, stkBatID, stkBatNo } = stock;
        if (key) {
            const { dataSource } = this.state;
            if (dataSource[key]) {
                dataSource[key] = Object.assign({}, dataSource[key], oneData);
            }
            this.setState({ dataSource: dataSource });
        } else {
            const index = this.state.dataSource.findIndex((value, index) => value.stock ? JSON.stringify(value.stock) === JSON.stringify(stock) : false);
            if (index > -1) {
                message.error(stockDesc + (stkBatNo ? '(' + stkBatNo + ')' : '') + ChineseEnglishSize.PriceAdjustmentFormEntenteredIntoDetail ? ChineseEnglishSize.PriceAdjustmentFormEntenteredIntoDetail.descripts:"已录入到明细");
                return false;
            }
            this.setState({ dataSource: [...this.state.dataSource, oneData] });
        }

        return true;
        //message.success("修改成功");
    }
    updateOneData = (key, oneData) => {
        const { dataSource,ChineseEnglishSize} = this.state;
        if (dataSource[key]) {
            dataSource[key] = Object.assign({}, dataSource[key], oneData);
        }
        $http.post("", this, {
            code: '02020040',
            data: { params: [dataSource[key]] },
            success: function (res) {
                if (res.errorCode == 0) {
                    message.success(res.errorMessage);
                    this.setState({ dataSource: dataSource });
                    //this.conditionForm.search();
                } else {
                    message.error(res.errorMessage);
                }
            },
            error: function () {
                this.setState({ errMsg: ChineseEnglishSize.PriceAdjustmentFormEnttryAgain ? ChineseEnglishSize.PriceAdjustmentFormEnttryAgain.descripts:"数据加载失败，请重试!" });
            }
        });
        return true;
    }

    dataToForm = (key) => {
        const { dataSource } = this.state;
        if (dataSource[key]) {
            const data = Object.assign({}, dataSource[key]);
            for (let akey in data) {
                if (akey.indexOf('Date') != -1 && data[akey]) {
                    data[akey] = moment(data[akey], "YYYY-MM-DD")
                }
            }
            //console.log(this.rowForm);
            let newData = {};
            newData[key] = data;
            if (this.rowForm.tableDataToForm) {
                this.rowForm.tableDataToForm(newData);
            }
        } else {
            this.rowForm.tableDataToForm();
        }
    }
    toggle = () => {
        this.setState({
            collapsed: !this.state.collapsed,
        });
    }
    CustomExpandIcon(text) {
        let icon;
        text = text ? text : '';
        if (!this.state.collapsed) {
            icon = <Icon type="double-left" onClick={e => { e.stopPropagation(); e.nativeEvent.stopImmediatePropagation(); this.toggle(); }} />
        } else {
            icon = <Icon type="double-right" onClick={e => { e.stopPropagation(); e.nativeEvent.stopImmediatePropagation(); this.toggle(); }} />
        }
        return (
            <span style={{ width: '100%', height: '100%' }}>
                {icon}
                {text}
            </span>
        );
    }



    getInitData() {
        let {ChineseEnglishSize,columns,language} =this.state;
        $http.post("", this, {
            code: '02020038',
            data: {},
            success: function (res) {
                if (res.result) {
                    let hospOpt = [], reasonOpt = [];
                    if ('hosp' in res.result) {
                        res.result.hosp.map((value, key) => {
                            hospOpt.push(<Select.Option key={value.descspell} value={value.id}>{value.descripts}</Select.Option>);
                        })
                    }
                    if ('reason' in res.result) {
                        res.result.reason.map((value, key) => {
                            reasonOpt.push(<Select.Option key={value.Code} value={value.ID}>{value.Desc}</Select.Option>);
                        })
                    }
                    if ('commonParams' in res.result) {
                        this.setState({ commonParams: res.result.commonParams });
                        // this.commonParams.priceRule = res.result.commonParams.priceRule;
                        // this.commonParams.fmtRP = res.result.commonParams.fmtRP;
                        // this.commonParams.fmtSP = res.result.commonParams.fmtSP;
                        // this.commonParams.adjReason = res.result.commonParams.adjReason;
                        // this.commonParams.preExeDate = res.result.commonParams.preExeDate;
                        if (res.result.commonParams.priceRule == 1) {
                            columns.splice(2, 0,
                                {
                                    title: language.language =='EN'?'Drug':'药品',
                                    dataIndex: 'stock',
                                    key: 'stock',
                                    width: 150,
                                    align: 'center',
                                    render: (text, record) => {
                                        return text ? text.stockDesc ? text.stockDesc : '' : '';
                                    }
                                }, {
                                title: language.language =='EN'?'Batch':'批号',
                                dataIndex: 'stock',
                                key: 'stock',
                                width: 100,
                                align: 'center',
                                render: (text, record) => {
                                    return text ? text.stkBatNo ? text.stkBatNo : '' : '';
                                }
                            }
                            );
                        } else {
                            columns.splice(2, 0,
                                {
                                    title: language.language =='EN'?'Drug':'药品',
                                    dataIndex: 'stock',
                                    key: 'stock',
                                    width: 200,
                                    align: 'center',
                                    render: (text, record) => {
                                        return text ? text.stockDesc ? text.stockDesc : '' : '';
                                    }
                                }
                            );
                        }
                    }
                    this.setState({ opt: { hospOpt: hospOpt, reasonOpt: reasonOpt } });
                    //this.opt = { hospOpt: hospOpt, reasonOpt: reasonOpt };
                }
            },
            error: function () {
                this.setState({ errMsg: ChineseEnglishSize.PriceAdjustmentFormEnttryAgain ? ChineseEnglishSize.PriceAdjustmentFormEnttryAgain.descripts:"数据加载失败，请重试!" });
            }
        });
    }
    componentWillMount() {
        this.getColumnsChineseAndEnglish();
        this.getInitData();
    }

    // 获取表单与form英语
	getColumnsChineseAndEnglish = () => {
        let {language} = this.state;
        let data = {
            params: [{
                reactCode: ['PriceAdjustmentFormEnt'],
                compontName: 'PriceAdjustmentFormEnt',
                type: 'C',
            }]
        }
        $http.post('urlS', this, {
            code: '01040073',
            data: data,
            success: function (res) {
                if (+res.errorCode === 0) {

                    let arr = res.result.C&&res.result.C.length > 0 ? JSON.parse(JSON.stringify(res.result.C)).map((item, index) => {
                        return  {
                            ...item,
                            key: index + 1,
                            title: <div onDoubleClick={() => this.columnRef.onOpenModel()}>{language.language== 'EN' ? item.enDescripts : item.title}</div>,
                            render: (text, record, index) => {
                                if(item.code==='index'){
                                    return this.state.dataSource.findIndex(r => r === record)+1;
                                }else if(item.code==='unit'){
                                    return text ? text.desc : '';
                                }else if(item.code==='state'){
                                    return text ? text.desc : '';
                                }else if(item.code==='createUser'){
                                    return text ? text.desc : '';
                                }else{
                                    return text;
                                }

                            }
                        }
                    }) : '';
                    let filterArr = arr.filter(function(item){ return item.display === 'Y'});
                    this.setState({columns: filterArr, columnsWidth: res.totalWidth,ChineseEnglishSize:language.language=='EN' ? res.result.language.EN : res.result.language.CN})
                }
            }
        });
    };
    onColumnRef = (ref) => {
        this.columnRef = ref;
    }
    render() {
        const rowSelection = {
            selectedRowKeys: this.state.selectedRowKeys,
            onChange: this.onTableSelectChange,
            type: 'checkbox'
        };
        const { opt, commonParams,ChineseEnglishSize,columns } = this.state;
        return (
            <div className={'AdjUnite'}>
                <Card size={'small'} title={ChineseEnglishSize.PriceAdjustmentFormEntpriceAdjFormEntry ? ChineseEnglishSize.PriceAdjustmentFormEntpriceAdjFormEntry.descripts:'调价单录入'}>
                    <ConditionForm wrappedComponentRef={el => { this.conditionForm = el }} clickEvents={this.clickEvents} selectKeys={this.state.selectedRowKeys} ChineseEnglishSize={ChineseEnglishSize}/>
                </Card>
                <Row>
                    <Col span={!this.state.collapsed ? 8 : 0}>
                        <Card size={'small'} title={ChineseEnglishSize.PriceAdjustmentFormEntentryDetails ? ChineseEnglishSize.PriceAdjustmentFormEntentryDetails.descripts:'明细录入'}>
                            <RowForm opt={opt} commonParams={commonParams} wrappedComponentRef={el => { this.rowForm = el }} updateOneData={this.updateOneData} addOneData={this.addOneData} ChineseEnglishSize={ChineseEnglishSize}/>
                        </Card>
                    </Col>
                    <Col span={!this.state.collapsed ? 16 : 24}>
                        <Card size={'small'} title={this.CustomExpandIcon(ChineseEnglishSize.PriceAdjustmentFormEntdetailListing ? ChineseEnglishSize.PriceAdjustmentFormEntdetailListing.descripts:'明细列表')}>
                            <Table
                                dataSource={this.state.dataSource}
                                columns={columns.length>0?columns:this.columns}
                                bordered
                                //title={() => title}
                                rowSelection={rowSelection}
                                scroll={{ x: '150%', y: store.getState().tableHeight.y + 'px' }}
                                style={{ height: store.getState().tableHeight.y + 'px' }}
                                rowKey={(record, index) => this.state.dataSource.findIndex(r => r === record)}
                                onRow={(record, index) => ({ onClick: (event) => this.check(record, index, event) })}
                                pagination={false}
                            />
                        </Card>
                    </Col>
                </Row>
                <ColumnAuthoritysModel
                    clientWidth='800px'
                    compontName="PriceAdjustmentFormEnt"
                    configType="C"
                    onRef={this.onColumnRef}
                    reloadData={this.getColumnsChineseAndEnglish}
                />
                {/* <Layout.Content>
                    <Layout>
                        <Layout.Sider
                            collapsedWidth={0}
                            trigger={null}
                            onCollapse={(collapsed, type) => {
                                if (collapsed) {
                                    this.setState({ tableScrollX: '170%' });
                                } else {
                                    this.setState({ tableScrollX: '290%' });
                                }

                            }}
                            collapsible
                            collapsed={this.state.collapsed}
                            width={'40%'}
                        >
                            <RowForm wrappedComponentRef={el => { this.rowForm = el }} updateOneData={this.updateOneData} addOneData={this.addOneData} />
                            <Icon className="trigger" type={this.state.collapsed ? 'menu-unfold' : 'menu-fold'} onClick={this.toggle} />
                        </Layout.Sider>
                        <Layout.Content style={{ height: '500px' }}>
                            <AdjTable scrollX={this.state.tableScrollX} dataToForm={this.dataToForm} delData={this.delData} dataSource={this.state.dataSource} />
                        </Layout.Content>
                    </Layout>
                </Layout.Content> */}
            </div>
        );
    }
}
export default AdjUnite;
