// 批准文号前缀维护
import React from 'react';
import { Card, Row, Col, Form, DatePicker, Select, Button, Checkbox, Table, Switch, message, Pagination, Input  } from 'antd';
import { $http } from 'containers/config/https';
import CommonPagination from 'components/pagination/index';
import Moment from 'moment';
import store from 'store';

const { Option } = Select;
const FormItem = Form.Item;
const formItemLayout = {    // label 和input宽度
    labelCol: { span:8 },
    wrapperCol: { span: 16 },
};
const formItemItem  = {
    labelCol: {span: 10},
    wrapperCol: {span: 14}
};
const ApprovalPrefixMaintenance = Form.create()(
    class extends React.Component {
        constructor() {
            super();
            this.state = {
                userInfo: {}, //表单数据详情
                ApprovalPrefixListData: [], //批准文号前缀列表数据
                pageSize: 10,
                page: 1,
                total:0,
                rowKey: '', //行选中id
                rowData: {}, //当前行数据
                language: JSON.parse(window.sessionStorage.userData),
                ChineseEnglishSize: [],
                modalColumns:[],
            }
            // 库存单的数据表头
            this.columns = [

                {
                    key: 1,
                    title: '代码',
                    dataIndex: 'imCode',
                    align: "center",
                    width: '20%'
                },
                {
                    key: 2,
                    title: '描述',
                    dataIndex: 'imDesc',
                    align: "center",
                    width: '40%'
                },
                {
                    key: 3,
                    title: '状态',
                    dataIndex: 'imState',
                    align: "center",
                    width: '20%'
                }
            ]
        }

        componentDidMount() {
            // 初始化数据
            this.getApprovalPrefixList();
            this.getDetailTableColumns();
            
      
        }

        componentWillUnmount() {
            // 组件销毁前将静止让setState修改state的状态，防止内存泄漏
            this.setState = (state,callback)=>{ return; }
        }

        //清空表格内容
        resetFields = () => {
            this.props.form.resetFields();
            this.setState({userInfo: {}, rowKey: '', rowData: ''});
        };
        handleReset=()=> {
            this.resetFields();
            this.setState({ApprovalPrefixListData: [],total: 0});
        }
        //导入数据
        importData=()=>{
            
        }
        searchInformation=()=>{
            this.setState({page: 1},()=>{
                this.getApprovalPrefixList()
            })
        };
   
        // 获取库存子类列表数据
        getApprovalPrefixList=()=>{
            let imCode = this.props.form.getFieldValue('imCode');
            let imDesc = this.props.form.getFieldValue('imDesc');
            let imState = this.props.form.getFieldValue('imState');
            this.setState({loading: false})
            let data = {
                params: [
                    {
                      imCode : imCode ? imCode :undefined,
                      imDesc : imDesc ? imDesc :undefined,
                      imState : imState ? imState :undefined,
                    }
                ],
                pagination: [
                    {
                        pageSize:this.state.pageSize,
                        currentPage:this.state.page,
                        sort:"ID",
                        dir:"asc",
                    }
                ],
            };
            $http.post('urlS', this, {
                code: "02020281",
                data: data,
                success: function (res) {
                    if(res.errorCode==0 && res.result.rows.length > 0){
                        for(let i = 0; i < res.result.rows.length; i++){
                            res.result.rows[i].key = i;
                        }
                        this.setState({ ApprovalPrefixListData: res.result.rows, total: res.result.total, loading: false});
                    }else {
                        this.setState({ ApprovalPrefixListData: [],total:0,loading: false});
                        if (language.language =='EN'){
                            message.error("No related data was found");
                        }else{
                            message.error("没数据");
                        }
                        this.props.form.resetFields();
                    }
                }
            });
        };

        //保存
        saveData=()=>{
            this.props.form.validateFields((error, value)=> {
                let obj = JSON.parse(JSON.stringify(value));
    
                if(error == null){
                    let data = {
                        params: [
                            {
                                imID:this.state.userInfo.imID ,	//盘点组ID
                                imCode:obj.code ,	//代码
                                imDesc:obj.descripts ,	//描述
                                imENDesc:obj.ENDescripts ,
                                imSeqNo:obj.seqNo ? obj.seqNo :'',//序号
                                imStartDate:obj.startDate?Moment(obj.startDate).format('YYYY-MM-DD'): '',	//生效日期
                                imEndDate:obj.endDate ? Moment(obj.endDate).format('YYYY-MM-DD') : '',	//失效日期
                            }
                        ]
                    };          
                    $http.post('urlS', this, {
                        code: "02020283",
                        data: data,
                        success: function (res) {
                            if(res.errorCode == 0) {
                                message.success(res.errorMessage);
                                this.getApprovalPrefixList();
                            }
                        }
                    });
                }
            })
        }
        // 设置行属性
        onClickRow = (record) => {
            return {
                // 单击行选中
                onClick: (e) => {
                    e.stopPropagation();
                    this.resetFields();
                    if (this.state.rowKey === '') {
                        // 保存行数据以及ID
                        this.setState({rowKey: record.ID});
                        this.approvalPrefixData(record.ID)
                    } else {
                        if (this.state.rowKey !== record.ID) {
                            this.setState({rowKey: record.ID});
                            this.approvalPrefixData(record.ID)
                        } else {
                            this.setState({rowKey: '', userInfo: {}});
                            this.resetFields();
                        }
                    }
                }
            }
        };

        // 表格行的类名
        setRowClassName = (record) => {
            return record.ID === this.state.rowKey ? 'clickRowStyle' : '';
        };

        approvalPrefixData=(id)=>{

            let data = {
                params: [
                    {
                        imID: id
                    }
                ]
            };
            $http.post('urlS', this, {
                code: "02020282",
                data: data,
                success: function (res) {
                    if (+res.errorCode === 0) {
                     console.log('res',res);
                     this.setState({userInfo: res.result})
                    }
                }
            })

        };
        // 页码改变的回调，参数是改变后的页码及每页条数 库存单
        onChange = (page, pageSize) => {
            this.setState({page: page, pageSize: this.state.pageSize}, () => {
                // 重新调用查询方法
                this.getApprovalPrefixList();
            });
        };

        onShowSizeChange = (current, size) => {
            this.setState({page: current, pageSize: size}, () => {
                // 重新调用查询方法
                this.onChange(current,size);
            })
        };

        // 显示分页总条数
        showTotal(total) {
            return `共 ${total} 条`;
        }

                 //页面中英文翻译
        getDetailTableColumns = () => {
            let {language} = this.state;
            let data = {
                params: [{
                    reactCode: ['ApprovalPrefixMaintenance'],
                    compontName: 'ApprovalPrefixMaintenance',
                    type: 'C',
                }]
            }
            $http.post('urlS', this, {
                code: '01040073',
                data: data,
                success: function (res) {
                    console.log(res)
                    if (+res.errorCode === 0) {
                        // let userInfo=JSON.parse(window.sessionStorage.userData);
                        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: language.language =='EN' ? item.enDescripts : item.title
                            }
                        }) : '';
                        let filterArr = arr.filter(function(item){ return item.display === 'Y'});
                        this.setState({modalColumns: filterArr, listLength: res.totalWidth,ChineseEnglishSize:  language.language=='EN' ? res.result.language.EN : res.result.language.CN})
                    }
                    // if (+res.errorCode === 0) {
                    //     this.setState({ChineseEnglishSize:  language.language=='EN' ? res.result.language.EN : res.result.language.CN})
                    // }
                }
            })
        };
        render() {
        //   console.log();
            const { getFieldDecorator } = this.props.form;
            const {userInfo,ChineseEnglishSize} = this.state;
            return (
                <div className="ApprovalPrefixMaintenance">
                    <Col span={12}>
                        <Row>
                            <Card
                                size="small"
                                title={<div className="card-title-left-icon"><div></div>{ChineseEnglishSize.ApprovalPrefixMaintenancelist ? ChineseEnglishSize.ApprovalPrefixMaintenancelist.descripts:'批准文号列表'}</div>}
                            >
                                <Col span={24}>
                                    <Row >
                                        <Col span={6}>
                                            <FormItem {...formItemLayout} label={ChineseEnglishSize.ApprovalPrefixMaintenancemfCode ? ChineseEnglishSize.ApprovalPrefixMaintenancemfCode.descripts:'代码'}>
                                                {getFieldDecorator('imCode',{
                                                    initialValue: undefined
                                                })(
                                                    <Input />
                                                ) }
                                            </FormItem>
                                        </Col>
                                        <Col span={6}>
                                            <FormItem {...formItemLayout} label={ChineseEnglishSize.ApprovalPrefixMaintenancemfDesc ? ChineseEnglishSize.ApprovalPrefixMaintenancemfDesc.descripts:'描述'}>
                                                {getFieldDecorator('imDesc',{
                                                    initialValue: undefined
                                                })(
                                                    <Input />
                                                ) }
                                            </FormItem>
                                        </Col>
                                        <Col span={6}>
                                            <FormItem {...formItemLayout} label={ChineseEnglishSize.ApprovalPrefixMaintenancestate ? ChineseEnglishSize.ApprovalPrefixMaintenancestate.descripts:'状态'}>
                                                {getFieldDecorator('imState',{
                                                    initialValue: undefined
                                                })(
                                                    <Select allowClear style={{width: '100%'}}>
                                                        <Option value="1" key="1" >{ChineseEnglishSize.ApprovalPrefixMaintenanceeffective ? ChineseEnglishSize.ApprovalPrefixMaintenanceeffective.descripts:'有效'}</Option>
                                                        <Option value="0" key="0" >{ChineseEnglishSize.ApprovalPrefixMaintenanceinvalid ? ChineseEnglishSize.ApprovalPrefixMaintenanceinvalid.descripts:'失效'}</Option>
                                                    </Select>
                                                ) }
                                            </FormItem>
                                        </Col>
                                        <Col style={{textAlign: 'center'}} span={6}>
                                            <Button onClick={this.searchInformation}>{ChineseEnglishSize.ApprovalPrefixMaintenancesearch ? ChineseEnglishSize.ApprovalPrefixMaintenancesearch.descripts:'查询'}</Button>
                                            <Button type="primary" onClick={this.importData} style={{marginLeft: '20px'}}>{ChineseEnglishSize.ApprovalPrefixMaintenanceclean ? ChineseEnglishSize.ApprovalPrefixMaintenanceclean.descripts:'清屏'}</Button>
                                        </Col>
                                    </Row>
                                </Col>
                            </Card>
                        </Row>
                        <Row>
                            <Col>
                                <Card
                                    size="small"
                                >
                                    <div  style={{height: store.getState().tableHeight.y +94 + 'px'}}>
                                        <Table
                                            columns={this.state.modalColumns?this.state.modalColumns:this.columns}
                                            dataSource={this.state.ApprovalPrefixListData}
                                            pagination={false}
                                            bordered
                                            style={{height: store.getState().tableHeight.y +61 + 'px'}}
                                            scroll={{ y: store.getState().tableHeight.y +10 }}
                                            rowKey={record => record.key}
                                            onRow={this.onClickRow}
                                            rowClassName={this.setRowClassName}
                                        />
                                        <CommonPagination size='small' current={this.state.page} total={this.state.total} search= 'search'
                                                          onShowSizeChange={this.onShowSizeChange.bind(this)} complete={true} dataSource={this.state.ApprovalPrefixListData}
                                                          loading={this.state.loading} onChange={this.onChange.bind(this)} />
                                    </div>
                                </Card>
                            </Col>
                        </Row>
                    </Col>
                    <Col span={12}>
                        <Col >
                            
                            <Form>
                                <Card
                                    title={<div className="card-title-left-icon"><div></div>{ChineseEnglishSize.ApprovalPrefixMaintenanceinfo ? ChineseEnglishSize.ApprovalPrefixMaintenanceinfo.descripts:'批准文号信息'}</div>}
                                    size="small"
                                >
                                    <div  style={{height: store.getState().tableHeight.y +129 + 'px'}}>
                                    <Col >
                                        <Row>
                                            <Col span={11}>
                                                <FormItem label={ChineseEnglishSize.ApprovalPrefixMaintenancecode ? ChineseEnglishSize.ApprovalPrefixMaintenancecode.descripts:'批准文号代码：'} {...formItemItem}>
                                                    {getFieldDecorator('code', {
                                                        initialValue: userInfo.imCode ? userInfo.imCode : undefined,
                                                        rules:[{ required : ChineseEnglishSize.ApprovalPrefixMaintenancecode ? ChineseEnglishSize.ApprovalPrefixMaintenancecode.required =='Y'? true:false: false, message: ChineseEnglishSize.ApprovalPrefixMaintenancecode ? ChineseEnglishSize.ApprovalPrefixMaintenancecode.message:'请输入批准文号代码'}]
                                                    })(
                                                        <Input style={{width: '100%'}} />
                                                    )}
                                                </FormItem>
                                            </Col>
                                            <Col span={11}>
                                                <FormItem label={ChineseEnglishSize.ApprovalPrefixMaintenanceseqNo ? ChineseEnglishSize.ApprovalPrefixMaintenanceseqNo.descripts:'批准文号序号：'} {...formItemItem}>
                                                    {getFieldDecorator('seqNo', {
                                                        initialValue: userInfo.imSeqNo ? userInfo.imSeqNo : undefined,
                                                    })(
                                                        <Input style={{width: '100%'}} type="number" />
                                                    )}
                                                </FormItem>
                                            </Col>
                                        </Row>
                                        <Row>
                                            <Col span={11}>
                                                <FormItem label={ChineseEnglishSize.ApprovalPrefixMaintenancedesc ? ChineseEnglishSize.ApprovalPrefixMaintenancedesc.descripts:'批准文号描述：'} {...formItemItem}>
                                                    {getFieldDecorator('descripts', {
                                                        initialValue: userInfo.imDesc ? userInfo.imDesc : undefined,
                                                        rules:[{ required : ChineseEnglishSize.ApprovalPrefixMaintenancedesc ? ChineseEnglishSize.ApprovalPrefixMaintenancedesc.required =='Y'? true:false: false, message: ChineseEnglishSize.ApprovalPrefixMaintenancedesc ? ChineseEnglishSize.ApprovalPrefixMaintenancedesc.message:'请输入批准文号描述'}]
                                                    })(
                                                        <Input style={{width: '100%'}} />
                                                    )}
                                                </FormItem>
                                            </Col>
                                            <Col span={11}>
                                            <FormItem label={ChineseEnglishSize.ApprovalPrefixMaintenanceENDesc ? ChineseEnglishSize.ApprovalPrefixMaintenanceENDesc.descripts:'英文描述：'} {...formItemItem}>
                                                {getFieldDecorator('ENDescripts', {
                                                    initialValue:  userInfo.imENDesc ? userInfo.imENDesc : undefined,
                                                })(
                                                    <Input style={{width: '100%'}} />
                                                )}
                                            </FormItem>
                                            </Col>
                                        </Row>
                                        <Row>
                                            <Col span={11}>
                                            <FormItem label={ChineseEnglishSize.ApprovalPrefixMaintenancestartDate ? ChineseEnglishSize.ApprovalPrefixMaintenancestartDate.descripts:'生效日期：'} {...formItemItem}>
                                                {getFieldDecorator('startDate', {
                                                    initialValue:  userInfo.imStartDate ? Moment(userInfo.imStartDate) : undefined,
                                                    rules:[{ required : ChineseEnglishSize.ApprovalPrefixMaintenancestartDate ? ChineseEnglishSize.ApprovalPrefixMaintenancestartDate.required =='Y'? true:false: false, message: ChineseEnglishSize.ApprovalPrefixMaintenancestartDate ? ChineseEnglishSize.ApprovalPrefixMaintenancestartDate.message:'请选择生效日期'}]
                                                })(
                                                    <DatePicker
                                                        format="YYYY-MM-DD"
                                                        style={{width:'100%'}}
                                                    >
                                                    </DatePicker>
                                                )}
                                            </FormItem>
                                            </Col>
                                            <Col span={11}>
                                            <FormItem label={ChineseEnglishSize.ApprovalPrefixMaintenanceendDate ? ChineseEnglishSize.ApprovalPrefixMaintenanceendDate.descripts:'失效日期：'} {...formItemItem}>
                                                {getFieldDecorator('endDate', {
                                                    initialValue:  userInfo.imEndDate ? Moment(userInfo.imEndDate) : undefined,
                                                })(
                                                    <DatePicker
                                                        format="YYYY-MM-DD"
                                                        style={{width:'100%'}}
                                                    >
                                                    </DatePicker>
                                                )}
                                            </FormItem>
                                            </Col>
                                        </Row>
                                    </Col>
                                    </div>
                                </Card>
                            </Form>
                            
                        </Col>
                        <Col>
                            <Row style={{marginTop: '10px',textAlign: 'right'}} >
                                <Button type="primary" style={{marginRight: '30px'}} onClick={this.saveData}>{ChineseEnglishSize.ApprovalPrefixMaintenancesave ? ChineseEnglishSize.ApprovalPrefixMaintenancesave.descripts:'保存'}</Button>
                                <Button onClick={this.resetFields}>{ChineseEnglishSize.ApprovalPrefixMaintenancereset ? ChineseEnglishSize.ApprovalPrefixMaintenancereset.descripts:'重置'}</Button>
                            </Row>
                        </Col>
                    </Col>
                </div>
            )
        }
    }
);
export default ApprovalPrefixMaintenance;