// 物资调价单生效
import React from 'react';
import { Row, Col, Button, Form, Table, DatePicker, message, Card, Switch } from 'antd';
import { $http } from 'containers/config/https';
import { StockBatchItemSelect } from '../Common';
import ColumnAuthoritysModel from 'pages/columnAuthority/ColumnAuthoritysModel';
import moment from 'moment';
import './style/AdjEffective.less';

class ConditionFields extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            language: JSON.parse(window.sessionStorage.userData),
            ChineseEnglishSize: {}
        }
    }

    componentDidMount() {
        this.search(true);
    }

    componentWillReceiveProps(props) {
        this.setState({ ChineseEnglishSize: props.ChineseEnglishSize })
    }

    search = (notip) => {
        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 = values.state ? "yes" : 'audit';
            $http.post("", this, {
                code: '02060143',
                data: { params: [values] },
                success: function (res) {
                    if (res.errorCode == "0") {
                        this.props.clickEvents.addSearch(res.result);
                        if (!notip) {
                            if (res.result.length == 0) {
                                message.warning(ChineseEnglishSize.MaterialPriceAdjustmentOrdernoData ? ChineseEnglishSize.MaterialPriceAdjustmentOrdernoData.descripts : "未查询到数据");
                            } else {
                                message.success(ChineseEnglishSize.MaterialPriceAdjustmentOrdersearchSucc ? ChineseEnglishSize.MaterialPriceAdjustmentOrdersearchSucc.descripts : "查询成功");
                            }
                        }
                    } else {
                        message.error(res.errorMessage);
                    }
                },
                error: function () {
                    this.setState({ errMsg: ChineseEnglishSize.MaterialPriceAdjustmentOrdertryAgain ? ChineseEnglishSize.MaterialPriceAdjustmentOrdertryAgain.descripts : "数据加载失败，请重试!" });
                }
            });
        });
    }

    getSearchParams = () => {
        let ret = {};
        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 = values.state ? "yes" : 'audit';
            ret = values;
        });
        return ret;
    }

    effec = () => {
        this.props.clickEvents.effec(this.getSearchParams());
        //this.search(true);
    }

    getEffecState = () => {
        let ret = true;
        if ((this.props.selectKeys.length > 0) && (!this.props.form.getFieldValue('state'))) {
            ret = false;
        }
        return ret;
    }

    render() {
        let { ChineseEnglishSize } = this.state;
        const { getFieldDecorator } = this.props.form;
        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.MaterialPriceAdjustmentOrderStartDate ? ChineseEnglishSize.MaterialPriceAdjustmentOrderStartDate.descripts : '开始日期'} {...formStype}>
                                    {getFieldDecorator('startDate', {
                                        rules: [{
                                            required: false,
                                            message: '不能为空'
                                        }],
                                        initialValue: moment(new Date)
                                    })(<DatePicker />)}
                                </Form.Item>
                            </Col>
                            <Col span={6}>
                                <Form.Item label={ChineseEnglishSize.MaterialPriceAdjustmentOrderdeadline ? ChineseEnglishSize.MaterialPriceAdjustmentOrderdeadline.descripts : '结束日期'} {...formStype}>
                                    {getFieldDecorator('endDate', {
                                        rules: [{
                                            required: false,
                                            message: '不能为空'
                                        }],
                                        initialValue: moment(new Date)
                                    })(<DatePicker />)}
                                </Form.Item>
                            </Col>
                            <Col span={6}>
                                <Form.Item label={ChineseEnglishSize.MaterialPriceAdjustmentOrderdrugName ? ChineseEnglishSize.MaterialPriceAdjustmentOrderdrugName.descripts : '药品名称'} {...formStype}>
                                    {getFieldDecorator("stockItem", [])(<StockBatchItemSelect allowClear style={{ width: '100%' }} />)}
                                </Form.Item>
                            </Col>
                            <Col span={6}>
                                <Form.Item label={ChineseEnglishSize.MaterialPriceAdjustmentOrderinForce ? ChineseEnglishSize.MaterialPriceAdjustmentOrderinForce.descripts : '已生效'} {...formStype}>
                                    {getFieldDecorator("state", [])(<Switch onChange={(checked) => { this.props.clickEvents.cancelSelect() }} />)}
                                </Form.Item>
                            </Col>
                        </Row>
                    </Form>
                </Col>
                <Col span={6}>
                    <Row>
                        <Button style={{ margin: '0px 16px 16px 0px' }} onClick={() => this.search()}>{ChineseEnglishSize.MaterialPriceAdjustmentOrdersearch ? ChineseEnglishSize.MaterialPriceAdjustmentOrdersearch.descripts : '查询'}</Button>
                        <Button type={'primary'} onClick={this.effec} disabled={this.getEffecState()}>{ChineseEnglishSize.MaterialPriceAdjustmentOrdereffImm ? ChineseEnglishSize.MaterialPriceAdjustmentOrdereffImm.descripts : '立即生效'}</Button>
                    </Row>
                </Col>
            </Row>
        );
    }
}

class AdjTable extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            columns: [],
            ChineseEnglishSize: {}
        };
        this.columns = [
            {
                title: '序号',
                dataIndex: 'index',
                key: 'index',
                align: 'center',
                width: 30,
                render: (text, record, index) => {
                    const i = this.props.dataSource.findIndex(r => r === record);
                    return i + 1;
                }
            }, {
                title: '单号',
                dataIndex: 'adjNO',
                key: 'adjNO',
                align: 'center',
                width: 150
            }, {
                title: '药品--批次',
                dataIndex: 'stock',
                key: 'stock',
                width: 200,
                align: 'center',
                render: (text, record) => {
                    return text ? text.stkBatNo ? text.stockDesc + '--' + text.stkBatNo : text.stockDesc : '';
                }
            }, {
                title: '调前售价',
                dataIndex: 'priorSp',
                key: 'priorSp',
                width: 60,
                align: 'center',
            }, {
                title: '调后售价',
                dataIndex: 'resultSp',
                key: 'resultSp',
                width: 81,
                align: 'center',
            }, {
                title: '调价单位',
                dataIndex: 'unit',
                key: 'unit',
                width: 70,
                align: 'center',
                render: (text, record) => {
                    return text ? text.desc : '';
                }
            }, {
                title: '单价(基本)',
                dataIndex: 'resultBaseSp',
                key: 'resultBaseSp',
                width: 80,
                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 : '';
                }
            }, {
                title: '审核日期',
                dataIndex: 'auditDate',
                key: 'auditDate',
                width: 80,
                align: 'center',
            }, {
                title: '审核时间',
                dataIndex: 'auditTime',
                key: 'auditTime',
                width: 80,
                align: 'center',
            }, {
                title: '审核人',
                dataIndex: 'auditUser',
                key: 'auditUser',
                width: 80,
                align: 'center',
                render: (text, record) => {
                    return text ? text.desc : '';
                }
            }, {
                title: '生效日期',
                dataIndex: 'exeDate',
                key: 'exeDate',
                width: 80,
                align: 'center',
            }, {
                title: '生效人',
                dataIndex: 'exeUser',
                key: 'exeUser',
                width: 80,
                align: 'center',
                render: (text, record) => {
                    return text ? text.desc : '';
                }
            }
        ];
    }

    componentWillReceiveProps(props) {
        this.setState({ ChineseEnglishSize: props.ChineseEnglishSize, columns: props.columns })
    }

    onTableSelectChange = (selectedRowKeys, selectedRows) => {
        this.props.onTableSelectChange(selectedRowKeys, selectedRows);
    }

    check = (record, index, event) => {
        this.props.check(record, index, event);
    }

    render() {
        let { columns } = this.state;
        const rowSelection = {
            selectedRowKeys: this.props.selectedRowKeys,
            onChange: this.onTableSelectChange,
            type: 'checkbox'
        };
        return (
            <Table
                dataSource={this.props.dataSource}
                columns={columns.length > 0 ? columns : this.columns}
                bordered
                rowSelection={rowSelection}
                scroll={{ x: '140%', y: '100%' }}
                style={{ height: '500px' }}
                size='middle'
                rowKey={(record, index) => +record.adjID}
                onRow={(record, index) => ({ onClick: (event) => this.check(record, +record.adjID, event) })}
                pagination={{
                    style: { margin: '0px 0px 0px 0px' }
                }}
            />
        );
    }
}

const ConditionForm = Form.create()(ConditionFields);
class AdjEffective extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            tableSource: [],
            selectedRowKeys: [],
            columns: [],
            columnsWidth: '',
            language: JSON.parse(window.sessionStorage.userData),
            ChineseEnglishSize: {}
        }
    }

    componentWillMount() {
        this.getColumnsChineseAndEnglish();
    }

    // 获取表单与form英语
    getColumnsChineseAndEnglish = () => {
        let { language } = this.state;
        let data = {
            params: [{
                reactCode: ['MaterialPriceAdjustmentOrder'],
                compontName: 'MaterialPriceAdjustmentOrder',
                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.tableSource.findIndex(r => r === record) + 1;
                                } else if (item.code === 'stock') {
                                    return text ? text.stkBatNo ? text.stockDesc + '--' + text.stkBatNo : text.stockDesc : '';
                                } else if (item.code === 'state' || item.code === 'unit' || item.code === 'createUser' || item.code === 'hosp' || item.code === 'reason' || item.code === 'auditUser' || item.code === 'exeUser') {
                                    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 })
                }
            }
        });
    };

    onTableSelectChange = (selectedRowKeys, selectedRows) => {
        this.setState({ selectedRowKeys: [...new Set(selectedRowKeys)] });
    }

    onColumnRef = (ref) => {
        this.columnRef = ref;
    }

    check = (record, index, event) => {
        const { selectedRowKeys } = this.state;
        if (selectedRowKeys.indexOf(index) == -1) {
            this.setState({ selectedRowKeys: [...new Set([...selectedRowKeys, index])] });
        } else {
            let ind = selectedRowKeys.indexOf(index);
            selectedRowKeys.splice(ind, 1);
            this.setState({ selectedRowKeys: [...new Set(selectedRowKeys)] });
        }
    }

    clickEvents = {
        addSearch: (data) => {
            this.setState({ tableSource: data, selectedRowKeys: [] });
        },
        effec: (searchParams) => {
            let { ChineseEnglishSize } = this.state;
            const { selectedRowKeys, tableSource } = this.state;
            let auditArr = [];
            selectedRowKeys.map((value, key) => {
                for (let i = 0; i < tableSource.length; i++) {
                    if (+value === +tableSource[i].adjID) {
                        auditArr.push(tableSource[i]);
                    }
                }
            })
            if (auditArr.length == 0) {
                message.warning(ChineseEnglishSize.MaterialPriceAdjustmentOrdernoDataToChecked ? ChineseEnglishSize.MaterialPriceAdjustmentOrdernoDataToChecked.descripts : "暂无数据需要审核");
                return;
            }
            $http.post("", this, {
                code: '02060145',
                data: { params: auditArr, searchParams: [searchParams] },
                success: function (res) {
                    if (res.errorCode == '0') {
                        message.success(ChineseEnglishSize.MaterialPriceAdjustmentOrdereffImmSucc ? ChineseEnglishSize.MaterialPriceAdjustmentOrdereffImmSucc.descripts : "立即生效成功");
                        this.clickEvents.addSearch(res.result);
                    } else {
                        message.error(res.errorMessage);
                    }
                },
                error: function () {
                    this.setState({ errMsg: ChineseEnglishSize.MaterialPriceAdjustmentOrdertryAgain ? ChineseEnglishSize.MaterialPriceAdjustmentOrdertryAgain.descripts : "数据加载失败，请重试!" });
                }
            });
        },
        del: () => {
            let { ChineseEnglishSize } = this.state;
            $http.post("", this, {
                code: '02020038',
                data: {},
                success: function (res) {
                    if (res.result) {

                    }
                },
                error: function () {
                    this.setState({ errMsg: ChineseEnglishSize.MaterialPriceAdjustmentOrdertryAgain ? ChineseEnglishSize.MaterialPriceAdjustmentOrdertryAgain.descripts : "数据加载失败，请重试!" });
                }
            });
        },
        cancelSelect: () => {
            this.setState({ selectedRowKeys: [] });
        }
    }

    render() {
        let { ChineseEnglishSize } = this.state;
        return (
            <div className={'AdjEffective'}>
                <Card size={'small'} title={ChineseEnglishSize.MaterialPriceAdjustmentOrderSearchTitle ? ChineseEnglishSize.MaterialPriceAdjustmentOrderSearchTitle.descripts : '查询条件'} >
                    <ConditionForm clickEvents={this.clickEvents} selectKeys={this.state.selectedRowKeys} ChineseEnglishSize={this.state.ChineseEnglishSize} />
                </Card>
                <Card size={'small'} title={ChineseEnglishSize.MaterialPriceAdjustmentOrderdetailListing ? ChineseEnglishSize.MaterialPriceAdjustmentOrderdetailListing.descripts : '明细列表'} >
                    <AdjTable selectedRowKeys={this.state.selectedRowKeys} check={this.check} onTableSelectChange={this.onTableSelectChange} dataSource={this.state.tableSource} ChineseEnglishSize={this.state.ChineseEnglishSize} columns={this.state.columns} />
                </Card>
                <ColumnAuthoritysModel
                    clientWidth='800px'
                    compontName="MaterialPriceAdjustmentOrder"
                    configType="C"
                    onRef={this.onColumnRef}
                    reloadData={this.getColumnsChineseAndEnglish}
                />
            </div>
            // <Layout className={'AdjEffective'}>
            //     <Layout.Header>
            //         <ConditionForm clickEvents={this.clickEvents} />
            //     </Layout.Header>
            //     <Layout.Content>
            //         <AdjTable selectedRowKeys={this.state.selectedRowKeys} check={this.check} onTableSelectChange={this.onTableSelectChange} dataSource={this.state.tableSource} />
            //     </Layout.Content>
            // </Layout>
        );
    }
};

export default AdjEffective;
