// 批准文号维护
import React from 'react';
import { Modal, Row, Col, Card, Form, DatePicker, Input, Select, Button, message } from 'antd';
import Moment from 'moment';
import { $http } from 'containers/config/https';
import PubilcTablePagination from 'pages/common/PubilcTablePagination.jsx';
import store from 'store';
let {Option} = Select;

class ApprovalNomaintain extends React.Component {
    constructor() {
        super();
        var userData = JSON.parse(sessionStorage.getItem('userData'));
        this.state = {
            userData,
            visible: false,
            columns: [],
            tableData: [],
            total: 0,
            page: 1,
            widthTotal: 0,
            loading: false,
            rowData: {},
            rowId: '',
            childSelectData: {},
            approvalPrefixData: [],
            manfDataID: '',
            apprNoID: '',
        }
    }

    componentDidMount() {
        this.props.onRef(this);
    }

    // 关闭弹窗
    handleCancel = () => {
        this.setState({visible: false}, () => {
            this.filterApprNo();
        });
    }

    filterApprNo = () => {
        let str = "";
        for(var i = 0; i < this.state.tableData.length; i++) {
            if(this.state.tableData[i].apprNo) {
                str += this.state.tableData[i].apprNo + ","
            }
        }
        this.props.setApprovalNoValue(str)
    }

    // 打开弹窗
    showModal = (childSelectData, approvalPrefixData) => {
        this.setState({visible: true, childSelectData, approvalPrefixData}, () => {
            if (!(this.state.columns&&this.state.columns > 0)) {
                this.getTableColmus();
                this.getTableData();
            }
        });
    }

    onRef = ref => {
        this.child = ref;
    }

    // 操作行
	onClickRowPublic = (record) => {
		return {
			// 单击行选中
			onClick: () => {
				if (this.state.rowId === '') {
					// 保存行数据以及ID
					this.setState({rowId: record.key, rowData:record});
				} else {
					if (this.state.rowId !== record.key) {
						this.setState({rowId: record.key, rowData:record});
					}
				}
			}
		}
	}

	// 选中行操作
	setRowClassNamePublic = (record) => {
		return record.key === this.state.rowId ? 'clickRowStyle' : '';
    }

    // 重置表单
    resetFields = () => {
        this.setState({rowId: "", rowData: {}})
        this.props.form.resetFields();
    }

    // 获取表格数据
    getTableData = () => {
        // let {pageSize, page} = this.state;
        let data = {
            params: [{
                stockID: this.props.stockID ? this.props.stockID : "", // 库存项id
                manfID: this.state.manfDataID ? this.state.manfDataID : undefined,
                apprNo: this.state.apprNoID ? this.state.apprNoID : undefined,
            }],
            // pagination:[{
            //     pageSize: pageSize,
            //     currentPage: page,
            //     sort: "ID",
            //     dir: "desc"
            // }]
        }
        $http.post('urlS', this, {
            code: '02020321',
            data: data,
            success: function (res) {
                if (+res.errorCode === 0) {
                    for(var i = 0; i < res.rows.length; i++) {
                        res.rows[i].key = i
                    }
                    this.setState({
                        tableData: res.rows,
                        total: res.total,
                    }, () => {
                        this.resetFields();
                        this.child.handleLoading();
                    })
                }
            }
        })
    }

    // 获取表头信息
    getTableColmus = () => {
        let {userData} = this.state;
        let data = {
        params: [{
            compontName: "ApprovalNomaintain",
            reactCode: ['ApprovalNomaintain'],
            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.mainColumnRef.onOpenModel()}>{userData.language == 'EN' ? (item&&item.enDescripts ? item.enDescripts : item.title) : item.title}</div>
                }
            }) : '';
            let filterArr = arr.filter(function(item){ return item.display === 'Y'});
            this.setState({
                columns: filterArr, widthTotal: res.totalWidth,
                localeProvider: userData.language == 'EN' ? res.result.language.EN : res.result.language.CN
            })
            }
        }
        })
    }

    // 保存
    handleSave = () => {
        const { form: { validateFields } } = this.props;
        validateFields((errors, values) => {
            // 验证成功
            if (errors === null) {
                let data = {
                    params: []
                }
                let obj = JSON.parse(JSON.stringify(values));
                obj.id = this.state.rowData.id ? this.state.rowData.id : "";
                obj.stockID = this.props.stockID ? this.props.stockID : "";
                obj.apprExpDate =  obj.apprExpDate ? Moment(obj.apprExpDate).format('YYYY-MM-DD') : "";
                obj.regCertExpDate = obj.regCertExpDate ? Moment(obj.regCertExpDate).format('YYYY-MM-DD') : "";
                data.params.push(obj);
                $http.post('urlADS', this, {
                    code: "02020320",
                    data: data,
                    success: function (res) {
                        if (+res.errorCode === 0) {
                            // 提示
                            message.success(res.errorMessage);
                            this.getTableData();
                        }
                    }
                })
            }
        })
    };
    apprNoData=(v)=>{
        console.log('app',v);
        this.setState({apprNoID: v.target.value})
    }
    manfData=(v)=>{
        console.log('manfData',v)
        this.setState({manfDataID: v})
    }
    render() {
        let {visible, columns, tableData, total, page, widthTotal, loading, rowData, childSelectData, approvalPrefixData} = this.state;
        const { getFieldDecorator } = this.props.form;
        const formItemInput  = {
            labelCol: {span: 10},
            wrapperCol: {span: 14}
        };

        // 组件所需参数
		const param = {
			// 表头配置
			columns: columns&&columns.length > 0 ? columns : this.columns,
			// 表格数据
			data: tableData,
			// 数据总条数
			// total,
			// 当前页数
			// page,
			// 表格的宽度
			x: widthTotal,
			y: store.getState().tableHeight.y-136 + 'px',
			height: store.getState().tableHeight.y-100 + 'px',
			isOnRow: true,
            rowClassName: true,
            loading,
        }

        // 厂商
        let pubBidManfOption = childSelectData&&childSelectData.pubBidManf ? childSelectData.pubBidManf.map((item, index) => {
            return (<Option key={index} value={item.id} title={item.descripts} seatchprop={item.descripts + '^' + item.descriptsSPCode}>{item.descripts}</Option>)
        }) : "";

        // 认证情况
        let appCertificatOption = childSelectData&&childSelectData.appCertificat ? childSelectData.appCertificat.map((item, index) => {
            return (<Option key={index} value={item.id} title={item.descripts} seatchprop={item.descripts + '^' + item.descriptsSPCode}>{item.descripts}</Option>)
        }) : "";
        return (
            <Modal
                visible={visible}
                title="批文信息维护"
                onCancel={this.handleCancel}
                footer={null}
                width={1200}
                className="approva-no-maintain"
            >
                <Row>
                    <Col span={11}>
                        <Card
							size="small"
                            title={<div className="card-title-left-icon">
                                <div></div>
                                查询条件
                            </div>}
						>
                            <div style={{height: "32px"}}>
                                批准文号：<Input style={{width: "150px", marginRight: "12px"}} placeholder="请输入" onChange={this.apprNoData}  />
                                厂商：<Select style={{width: "150px", marginRight: "24px"}} placeholder="请选择"  optionFilterProp="seatchprop" showSearch allowClear onChange={this.manfData}>
                                    {pubBidManfOption}
                                </Select>
                                <Button onClick={this.getTableData}>查询</Button>
                            </div>
                        </Card>
                        <div style={{height: '6px', background: 'rgba(240, 242, 245, 1)', width: '100%'}}></div>
                        <Card
                            size="small"
                            title={<div className="card-title-left-icon"><div></div>批文明细</div>}
                        >
                            <PubilcTablePagination
                                param={param}
                                handelThis={this}
                                onRef={this.onRef}
                                onClickRowPublic={this.onClickRowPublic}
                                setRowClassNamePublic={this.setRowClassNamePublic}
                            />
                        </Card>

                    </Col>
                    <Col span={13}>
                        <div style={{paddingLeft: '6px', position: 'relative'}}>
                            <Card
                                size="small"
                                title={<div className="card-title-left-icon">
                                    <div></div>
                                    维护
                                </div>}
                            >
                                <div style={{height: store.getState().tableHeight.y + 'px'}}>
                                    <Form>
                                        <Row>
                                            <Col span={12}>
                                                <Form.Item label="生产厂商：" {...formItemInput}>
                                                    {getFieldDecorator('manfID', {
                                                        initialValue: rowData.manfID ? rowData.manfID : undefined,
                                                        rules: [{ required: true, message: '生产厂商不能为空' }]
                                                    })(
                                                        <Select placeholder="请选择" optionFilterProp="seatchprop" showSearch allowClear>
                                                            {pubBidManfOption}
                                                        </Select>
                                                    )}
                                                </Form.Item>
                                            </Col>
                                            <Col span={12}>
                                                <Form.Item label="原批准文号：" {...formItemInput}>
                                                    {getFieldDecorator('lastApprNo', {
                                                        initialValue: rowData.lastApprNo ? rowData.lastApprNo : undefined,
                                                    })(
                                                        <Input disabled />
                                                    )}
                                                </Form.Item>
                                            </Col>
                                        </Row>
                                        <Row>
                                            <Col span={12}>
                                                <Form.Item {... formItemInput} label='批准文号前缀'>
                                                    {getFieldDecorator('appPreFixID', {
                                                        initialValue:rowData.appPreFixID ? rowData.appPreFixID : undefined,
                                                        rules: [{ required: true, message: '批准文号前缀是必填项,请选择！' }]
                                                    })(
                                                        <Select
                                                            allowClear={true}
                                                            showSearch
                                                            optionFilterProp="children"
                                                            // onChange={this.selectOnChange.bind(this,"appPreFixID")}
                                                            filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                                                        >
                                                            {this.state.approvalPrefixData}
                                                        </Select>
                                                    )}
                                                </Form.Item>
                                            </Col>
                                            <Col span={12}>
                                                <Form.Item label="批准文号：" {...formItemInput}>
                                                    {getFieldDecorator('apprNo', {
                                                        initialValue: rowData.apprNo ? rowData.apprNo : undefined,
                                                        rules: [{ required: true, message: '批准文号不能为空' }]
                                                    })(
                                                        <Input placeholder="请输入" />
                                                    )}
                                                </Form.Item>
                                            </Col>
                                        </Row>
                                        <Row>
                                            <Col span={12}>
                                                <Form.Item label="批文有效期：" {...formItemInput}>
                                                    {getFieldDecorator('apprExpDate', {
                                                        initialValue: rowData.apprExpDate ? Moment(rowData.apprExpDate) : Moment(),
                                                        rules: [{ required: true, message: '批文有效日期不能为空' }]
                                                    })(
                                                        <DatePicker format="YYYY-MM-DD" style={{width: '100%'}} />
                                                    )}
                                                </Form.Item>
                                            </Col>
                                            <Col span={12}>
                                                <Form.Item label="药品本位码：" {...formItemInput}>
                                                    {getFieldDecorator('standardCode', {
                                                        initialValue: rowData.standardCode ? rowData.standardCode : undefined,
                                                    })(
                                                        <Input placeholder="请输入" />
                                                    )}
                                                </Form.Item>
                                            </Col>
                                        </Row>
                                        <Row>
                                            <Col span={12}>
                                                <Form.Item label="进口药品注册证号：" {...formItemInput}>
                                                    {getFieldDecorator('regCertNo', {
                                                        initialValue: rowData.regCertNo ? rowData.regCertNo : undefined,
                                                    })(
                                                        <Input placeholder="请输入" />
                                                    )}
                                                </Form.Item>
                                            </Col>
                                            <Col span={12}>
                                                <Form.Item label="注册证效期：" {...formItemInput}>
                                                    {getFieldDecorator('regCertExpDate', {
                                                        initialValue: rowData.regCertExpDate ? Moment(rowData.regCertExpDate) : Moment(),
                                                        rules: [{ required: false, message: '注册证效期不能为空' }]
                                                    })(
                                                        <DatePicker format="YYYY-MM-DD" style={{width: '100%'}} />
                                                    )}
                                                </Form.Item>
                                            </Col>
                                        </Row>
                                        <Row>
                                            <Col span={12}>
                                                <Form.Item label="注册商标：" {...formItemInput}>
                                                    {getFieldDecorator('regLabel', {
                                                        initialValue: rowData.regLabel ? rowData.regLabel : undefined,
                                                        rules: [{ required: false, message: '注册商标不能为空' }]
                                                    })(
                                                        <Input placeholder="请输入" />
                                                    )}
                                                </Form.Item>
                                            </Col>
                                            <Col span={12}>
                                                <Form.Item label="认证情况：" {...formItemInput}>
                                                    {getFieldDecorator('certificat', {
                                                        initialValue: rowData.certificat ? rowData.certificat : undefined,
                                                    })(
                                                        <Select placeholder="请选择">
                                                            {appCertificatOption}
                                                        </Select>
                                                    )}
                                                </Form.Item>
                                            </Col>

                                        </Row>
                                        <Row style={{textAlign: "center", marginTop: "24px"}}>
                                            <Button type="primary" style={{marginRight: "24px"}} onClick={this.handleSave}>保存</Button>
                                            <Button onClick={this.resetFields}>重置</Button>
                                        </Row>
                                    </Form>
                                </div>
                            </Card>
                            <div style={{width: '6px', background: 'rgba(240, 242, 245, 1)', position: 'absolute', top: 0, left: 0, height: '100%'}}></div>
                        </div>
                    </Col>
                </Row>
            </Modal>
        )
    }
};
const ApprovalNomaintainForm = Form.create()(ApprovalNomaintain);
export default ApprovalNomaintainForm;
