import React from 'react';
import { Row, Col, Button, Form, Table, Card, DatePicker, message, Switch, Popconfirm } from 'antd';
import ColumnAuthoritysModel from 'pages/columnAuthority/ColumnAuthoritysModel';
import { $http } from '../../../containers/config/https';
import { StockBatchItemSelect } from '../Common';
import moment from 'moment';
import './style/AdjAudit.less';

class ConditionFields extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            visible: false,
            ChineseEnglishSize:{},
            language : JSON.parse(window.sessionStorage.userData),
        }
    }
    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 ? "audit" : 'no';
            $http.post("", this, {
                code: '02020044',
                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.PriceReviewnoData ? ChineseEnglishSize.PriceReviewnoData.descripts:"未查询到数据");
                            } else {
                                message.success(ChineseEnglishSize.PriceReviewsearchSucc ? ChineseEnglishSize.PriceReviewsearchSucc.descripts:"查询成功");
                            }
                        }
                    } else {
                        message.error(res.errorMessage);
                    }
                },
                error: function () {
                    this.setState({ errMsg: ChineseEnglishSize.PriceReviewtryAgain ? ChineseEnglishSize.PriceReviewtryAgain.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 ? "audit" : 'no';
            ret = values;
        });
        return ret;
    }
    //仅审核
    audit = () => {
        this.props.clickEvents.audit(false, this.getSearchParams());
        //this.search(true);
    }
    //审核后立即生效
    auditAndEff = () => {
        this.props.clickEvents.audit(true, this.getSearchParams());
        //this.search(true);
    }
    //取消审核
    cancelAudit = () => {
        this.props.clickEvents.cancelAudit(this.getSearchParams());
        //this.search(true);
    }
    handleVisibleChange = visible => {
        if (!visible) {
            this.setState({ visible });
            return;
        }
        // Determining condition before show the popconfirm.
        if (this.props.popConfirm) {
            this.setState({ visible }); // show the popconfirm
        } else {
            this.audit(); // next step
        }
    };
    render() {
        let {ChineseEnglishSize,language} = this.state;
        const style = { style: { margin: '10px 0px' } };
        //const colSpan = { labelCol: { span: 4 }, wrapperCol: { span: 20 } }
        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.PriceReviewStartDate ? ChineseEnglishSize.PriceReviewStartDate.descripts:'开始日期'} {...formStype}>
                                    {getFieldDecorator('startDate', {
                                        rules: [{
                                            required: false,
                                            message: '不能为空'
                                        }],
                                        initialValue: moment(new Date)
                                    })(<DatePicker />)}
                                </Form.Item>
                            </Col>
                            <Col span={6}>
                                <Form.Item label={ChineseEnglishSize.PriceReviewdeadline ? ChineseEnglishSize.PriceReviewdeadline.descripts:'结束日期'} {...formStype}>
                                    {getFieldDecorator('endDate', {
                                        rules: [{
                                            required: false,
                                            message: '不能为空'
                                        }],
                                        initialValue: moment(new Date)
                                    })(<DatePicker />)}
                                </Form.Item>
                            </Col>
                            <Col span={6}>
                                <Form.Item label={ChineseEnglishSize.PriceReviewdrugName ? ChineseEnglishSize.PriceReviewdrugName.descripts:'药品名称'} {...formStype}>
                                    {getFieldDecorator("stockItem", [])(<StockBatchItemSelect allowClear style={{ width: '100%' }} />)}
                                </Form.Item>
                            </Col>
                            <Col span={6}>
                                <Form.Item label={ChineseEnglishSize.PriceReviewchecked ? ChineseEnglishSize.PriceReviewchecked.descripts:'已审核'} {...formStype}>
                                    {getFieldDecorator("state", [])(<Switch />)}
                                </Form.Item>
                            </Col>
                        </Row>
                    </Form>
                </Col>
                <Col span={6}>
                    <Row>
                        <Button style={{ margin: '0px 16px 16px 0px' }} onClick={() => this.search()}>{ChineseEnglishSize.PriceReviewsearch ? ChineseEnglishSize.PriceReviewsearch.descripts:'查询'}</Button>
                        <Popconfirm placement={'topRight'} onVisibleChange={this.handleVisibleChange} visible={this.state.visible} title={ChineseEnglishSize.PriceReviewtipsLeft ? ChineseEnglishSize.PriceReviewtipsLeft.descripts:'存在预生效日期为今天的调价单，'+(ChineseEnglishSize.PriceReviewtipsRight ? ChineseEnglishSize.PriceReviewtipsRight.descripts:'是否审核后立即生效')} onConfirm={this.auditAndEff} onCancel={this.audit} 
                        okText={language.language=='EN'?"YES":"是"} cancelText={language.language=='EN'?"NO":"否"}>
                            <Button style={{ margin: '0px 16px 16px 0px' }} type={'primary'} disabled={this.props.selectKeys.length == 0 ? true : false}>{ChineseEnglishSize.PriceReviewCheck ? ChineseEnglishSize.PriceReviewCheck.descripts:'审核'}</Button>
                        </Popconfirm>
                        <Button onClick={this.cancelAudit} disabled={this.props.selectKeys.length == 0 ? true : false}>{ChineseEnglishSize.PriceReviewunapprove ? ChineseEnglishSize.PriceReviewunapprove.descripts:'取消审核'}</Button>
                    </Row>
                </Col>
            </Row>
        );
    }
}
class AdjTable extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            columns:[]
        };
        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 : '';
                }
            }
        ];
    }
    componentWillReceiveProps(props){
        this.setState({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: '160%', y: '100%' }}
                style={{ height: '500px' }}
                size='middle'
                rowKey={(record, index) => index}
                onRow={(record, index) => ({ onClick: (event) => this.check(record, index, event) })}
                pagination={{
                    style: { margin: '0px 0px 0px 0px' }
                }}
            />
        );
    }
}
const ConditionForm = Form.create()(ConditionFields);
class AdjUnite extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            tableSource: [],
            selectedRowKeys: [],
            popConfirm: false,
            columns:[],
            columnsWidth:'',
            language : JSON.parse(window.sessionStorage.userData),
            ChineseEnglishSize:{}
        }
    }
    componentWillMount() {
        this.getColumnsChineseAndEnglish();
    }
    onTableSelectChange = (selectedRowKeys, selectedRows) => {
        const keys = [...new Set(selectedRowKeys)];
        this.setState({ selectedRowKeys: keys });
        this.isTodayEff(keys);
    }
    check = (record, index, event) => {
        const selectedRowKeys = [...this.state.selectedRowKeys];
        let keys = [];
        if (selectedRowKeys.indexOf(index) == -1) {
            keys = [...new Set([...selectedRowKeys, index])];

        } else {
            let ind = selectedRowKeys.indexOf(index);
            selectedRowKeys.splice(ind, 1);
            keys = [...new Set(selectedRowKeys)];
        }
        this.setState({ selectedRowKeys: keys });
        this.isTodayEff(keys);
    }
    //查找是否存在有今天生效的调价单
    isTodayEff(keys) {
        const index = keys.findIndex((value, index) => {
            const { preExeDate, adjID } = this.state.tableSource[Number(value)];
            if (moment(preExeDate).isSame(new Date(), 'day')) {
                this.setState({ popConfirm: true });
                return true;
            }
        });
    }
    clickEvents = {
        addSearch: (data) => {
            //console.log(data);
            this.setState({ tableSource: data, selectedRowKeys: [] });
        },
        cancelAudit: (searchParams) => {
            let {ChineseEnglishSize} = this.state;
            const { selectedRowKeys, tableSource } = this.state;
            let auditArr = [];
            selectedRowKeys.map((value, key) => {
                if (tableSource[Number(value)]) {
                    auditArr.push(tableSource[Number(value)]);
                }
            })
            if (auditArr.length == 0) {
                message.warning(ChineseEnglishSize.PriceReviewnoDataToChecked ? ChineseEnglishSize.PriceReviewnoDataToChecked.descripts:"暂无数据需要审核");
                return;
            }
            $http.post("", this, {
                code: '02020078',
                data: { params: auditArr, searchParams: [searchParams] },
                success: function (res) {
                    if (res.errorCode == '0') {
                        message.success(res.errorMessage);
                        this.clickEvents.addSearch(res.result);
                    }
                }
            });
        },
        audit: (bool, searchParams) => {
            let {ChineseEnglishSize} = this.state;
            const { selectedRowKeys, tableSource } = this.state;
            let auditArr = [];
            selectedRowKeys.map((value, key) => {
                if (tableSource[Number(value)]) {
                    const { preExeDate, adjID } = tableSource[Number(value)];
                    let dataObj = { adjID: adjID }
                    if (bool && moment(preExeDate).isSame(new Date(), 'day')) {
                        dataObj.eff = true;
                    }
                    auditArr.push(dataObj);
                }
            })
            if (auditArr.length == 0) {
                message.warning(ChineseEnglishSize.PriceReviewnoDataToChecked ? ChineseEnglishSize.PriceReviewnoDataToChecked.descripts:"暂无数据需要审核");
                return;
            }
            $http.post("", this, {
                code: '02020045',
                data: { params: auditArr, searchParams: [searchParams] },
                success: function (res) {
                    if (res.errorCode == '0') {
                        message.success(res.errorMessage);
                        this.clickEvents.addSearch(res.result);
                    }
                },
                error: function () {
                    this.setState({ errMsg: ChineseEnglishSize.PriceReviewtryAgain ? ChineseEnglishSize.PriceReviewtryAgain.descripts:"数据加载失败，请重试!" });
                }
            });
        }
    }

    // 获取表单与form英语
	getColumnsChineseAndEnglish = () => {
        let {language} = this.state;
        let data = {
            params: [{
                reactCode: ['PriceReview'],
                compontName: 'PriceReview',
                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{
                                        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() {
        let {ChineseEnglishSize,columns} = this.state;
        return (
            <div className={'AdjAudit'}>
                <Card size={'small'} title={ChineseEnglishSize.PriceReviewSearchTitle ? ChineseEnglishSize.PriceReviewSearchTitle.descripts:'查询条件'} >
                    <ConditionForm clickEvents={this.clickEvents} popConfirm={this.state.popConfirm} selectKeys={this.state.selectedRowKeys} ChineseEnglishSize={this.state.ChineseEnglishSize}/>
                </Card>
                <Card size={'small'} title={ChineseEnglishSize.PriceReviewdetailListing ? ChineseEnglishSize.PriceReviewdetailListing.descripts:'明细列表'} >
                    <AdjTable selectedRowKeys={this.state.selectedRowKeys} check={this.check} onTableSelectChange={this.onTableSelectChange} dataSource={this.state.tableSource} columns={columns}/>
                </Card>
                <ColumnAuthoritysModel
                        clientWidth='800px'
                        compontName='PriceReview'
                        configType="C"
                        onRef={this.onColumnRef}
                        reloadData={this.getColumnsChineseAndEnglish}
                    />
            </div>
        );
    }
}
export default AdjUnite;