// 盘点组维护单
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 DataMaintenance = Form.create()(
    class extends React.Component {
        constructor() {
            super();
            this.state = {
                userInfo: {}, //表单数据详情
                // SelectData: {}, //下拉数据
                GroupListData: [], //盘点组列表数据
                pageSize: 20,
                page: 1,
                total:0,
                rowKey: '', //行选中id
                rowData: {}, //当前行数据
                language: JSON.parse(window.sessionStorage.userData),
                ChineseEnglishSize: [],
                columns:[],
                detailWidthTotal:''
            }
            // 库存单的数据表头
            this.columns = [

                {
                    key: 1,
                    title: '代码',
                    dataIndex: 'tkCode',
                    align: "center",
                    width: '20%'
                },
                {
                    key: 2,
                    title: '描述',
                    dataIndex: 'tkDesc',
                    align: "center",
                    width: '40%'
                },
                {
                    key: 3,
                    title: '状态',
                    dataIndex: 'tkState',
                    align: "center",
                    width: '20%'
                }
                // {
                //     key: 4,
                //     title: '操作',
                //     dataIndex: 'purUnitDesc',
                //     align: "center",
                //     width: '20%'
                // }
            ]
        }

        componentDidMount() {
            // 初始化数据
            // this.getTacitlyApproveData();
            this.getInventroyGroupList();
            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({GroupListData: [],total: 0});
        }
        //导入数据
        importData=()=>{
            
        }

        searchInformation=()=>{
            this.setState({page: 1},()=>{
                this.getInventroyGroupList()
            })
        };
        // 获取盘点组列表数据
        getInventroyGroupList=()=>{
            let {language} = this.state;
            let tkCode = this.props.form.getFieldValue('tkCode');
            let tkDesc = this.props.form.getFieldValue('tkDesc');
            let tkState = this.props.form.getFieldValue('tkState');
            this.setState({loading: true})
            let data = {
                params: [
                    {
                        tkCode : tkCode ? tkCode :undefined,
                        tkDesc : tkDesc ? tkDesc :undefined,
                        tkState : tkState ? tkState :undefined,
                    }
                ],
                pagination: [
                    {
                        pageSize:this.state.pageSize,
                        currentPage:this.state.page,
                        sort:"ID",
                        dir:"asc",
                    }
                ],
            };
            $http.post('urlS', this, {
                code: "02020261",
                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({ GroupListData: res.result.rows, total: res.result.total, loading: false});
                    }else {
                        this.setState({ GroupListData: [],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: [
                            {
                                tkID:this.state.userInfo.tkID,	//盘点组ID
                                tkCode:obj.code ,	//代码
                                tkDesc:obj.descripts ,	//描述
                                tkENDesc:obj.ENDescripts,
                                tkSeqNo:obj.seqNo ? obj.seqNo : '', //序号
                                tkStartDate:Moment(obj.startDate).format('YYYY-MM-DD'),	//生效日期
                                tkEndDate:obj.endDate ? Moment(obj.endDate).format('YYYY-MM-DD') : '',	//失效日期
                            }
                        ]
                    };
                    $http.post('urlS', this, {
                        code: "02020263",
                        data: data,
                        success: function (res) {
                            if(res.errorCode == 0) {
                                message.success(res.errorMessage);
                                this.getInventroyGroupList();
                            }
                        }
                    });
                }
            })
        }
        // 设置行属性
        onClickRow = (record) => {
            return {
                // 单击行选中
                onClick: (e) => {
                    e.stopPropagation();
                    this.resetFields();
                    if (this.state.rowKey === '') {
                        // 保存行数据以及ID
                        this.setState({rowKey: record.ID});
                        this.inventoryGroupData(record.ID)
                    } else {
                        if (this.state.rowKey !== record.ID) {
                            this.setState({rowKey: record.ID});
                            this.inventoryGroupData(record.ID)
                        } else {
                            this.setState({rowKey: '', userInfo: {}});
                            this.resetFields();
                        }
                    }
                }
            }
        };

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

        inventoryGroupData=(id)=>{

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

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

        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: ['StkTakeMaintenance'],
                    compontName: 'StkTakeMaintenance',
                    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>{language.language== 'EN' ? item.enDescripts : item.title}</div>
                            }
                        }) : '';
                        let filterArr = arr.filter(function(item){ return item.display === 'Y'});
                        this.setState({columns: filterArr, detailWidthTotal: res.totalWidth,ChineseEnglishSize:language.language=='EN' ? res.result.language.EN : res.result.language.CN})
                    }
                }
            })
        };


        render() {
            const { getFieldDecorator} = this.props.form;
            const {userInfo,ChineseEnglishSize,columns } = this.state;
            // // 关联收费项
            // const chargeItemOptions = this.state.chargeData.map(d => <Option title={d.text} key={d.value}>{d.text}</Option>);
            // 状态
            // let stateOption = SelectData&&SelectData.PC&&SelectData.PC.map((item, index) => {
            //     return (<Option key={index} value={item.id} title={item.descripts} seatchprop={item.descripts + '^' + item.descriptsSPCode}>{item.descripts}</Option>)
            // })
            return (
                <div className="DataMaintenance">
                    <Col span={12}>
                        <Row>
                            <Card
                                size="small"
                                title={<div className="card-title-left-icon"><div></div>{ChineseEnglishSize.StkTakeMaintenancelist ? ChineseEnglishSize.StkTakeMaintenancelist.descripts:'盘点组列表'}</div>}
                            >
                                <Col span={24}>
                                    <Row >
                                        <Col span={6}>
                                            <FormItem {...formItemLayout} label={ChineseEnglishSize.StkTakeMaintenancetkCode ? ChineseEnglishSize.StkTakeMaintenancetkCode.descripts:'代码'}>
                                                {getFieldDecorator('tkCode',{
                                                    initialValue: undefined,
                                                })(
                                                    <Input />
                                                ) }
                                            </FormItem>
                                        </Col>
                                        <Col span={6}>
                                            <FormItem {...formItemLayout} label={ChineseEnglishSize.StkTakeMaintenancetkDesc ? ChineseEnglishSize.StkTakeMaintenancetkDesc.descripts:'描述'}>
                                                {getFieldDecorator('tkDesc',{
                                                    initialValue: undefined,
                                                })(
                                                    <Input />
                                                ) }
                                            </FormItem>
                                        </Col>
                                        <Col span={6}>
                                            <FormItem {...formItemLayout} label={ChineseEnglishSize.StkTakeMaintenancestate ? ChineseEnglishSize.StkTakeMaintenancestate.descripts:'状态'}>
                                                {getFieldDecorator('tkState',{
                                                    initialValue: undefined,
                                                })(
                                                    <Select allowClear style={{width: '100%'}}>
                                                        {/* {this.state.SelectData.stkSubCat && this.state.SelectData.stkSubCat.map(item => {
                                                            return <Option value={item.id} key={item.id} title={item.descripts} seatchprop={item.descripts}>{item.descripts}</Option>
                                                        })} */}
                                                        <Option value="1" key="1">{ChineseEnglishSize.StkTakeMaintenanceeffective ? ChineseEnglishSize.StkTakeMaintenanceeffective.descripts:'有效'}</Option>
                                                        <Option value="0" key="0">{ChineseEnglishSize.StkTakeMaintenanceinvalid ? ChineseEnglishSize.StkTakeMaintenanceinvalid.descripts:'失效'}</Option>
                                                    </Select>
                                                ) }
                                            </FormItem>
                                        </Col>
                                        <Col style={{textAlign: 'center'}} span={6}>
                                            <Button onClick={this.searchInformation}>{ChineseEnglishSize.StkTakeMaintenancesearch ? ChineseEnglishSize.StkTakeMaintenancesearch.descripts:'查询'}</Button>
                                            <Button type="primary" onClick={this.importData} style={{marginLeft: '20px'}}>{ChineseEnglishSize.StkTakeMaintenanceclean ? ChineseEnglishSize.StkTakeMaintenanceclean.descripts:'清屏'}</Button>
                                        </Col>
                                    </Row>
                                </Col>
                            </Card>
                        </Row>
                        <Row>
                            <Col>
                                <Card
                                    size="small"
                                >
                                    <div  style={{height: store.getState().tableHeight.y +94 + 'px'}}>
                                        <Table
                                            columns={columns.length>0?columns:this.columns}
                                            dataSource={this.state.GroupListData}
                                            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.GroupListData}
                                                          loading={this.state.loading} onChange={this.onChange.bind(this)} pageSize={true} />
                                    </div>
                                </Card>
                            </Col>
                        </Row>
                    </Col>
                    <Col span={12}>
                        <Col >
                            
                            <Form>
                                <Card
                                    title={<div className="card-title-left-icon"><div></div>{ChineseEnglishSize.StkTakeMaintenanceinfo ? ChineseEnglishSize.StkTakeMaintenanceinfo.descripts:'盘点组信息'}</div>}
                                    size="small"
                                >
                                    <div  style={{height: store.getState().tableHeight.y +129 + 'px'}}>
                                    <Col >
                                        <Row>
                                            <Col span={11}>
                                                <FormItem label={ChineseEnglishSize.StkTakeMaintenancecode ? ChineseEnglishSize.StkTakeMaintenancecode.descripts:'盘点组代码：'} {...formItemItem}>
                                                    {getFieldDecorator('code', {
                                                        initialValue: userInfo.tkCode ? userInfo.tkCode : undefined,
                                                        rules:[{ required : ChineseEnglishSize.StkTakeMaintenancecode ? ChineseEnglishSize.StkTakeMaintenancecode.required =='Y'? true:false: false, message: ChineseEnglishSize.StkTakeMaintenancecode ? ChineseEnglishSize.StkTakeMaintenancecode.message:'请输入盘点组代码'}]
                                                    })(
                                                        <Input style={{width: '100%'}} />
                                                    )}
                                                </FormItem>
                                            </Col>
                                            <Col span={11}>
                                                <FormItem label={ChineseEnglishSize.StkTakeMaintenanceseqNo ? ChineseEnglishSize.StkTakeMaintenanceseqNo.descripts:'盘点组序号：'} {...formItemItem}>
                                                    {getFieldDecorator('seqNo', {
                                                        initialValue: userInfo.tkSeqNo ? userInfo.tkSeqNo : undefined,
                                                    })(
                                                        <Input style={{width: '100%'}} type="number" />
                                                    )}
                                                </FormItem>
                                            </Col>
                                        </Row>
                                        <Row>
                                            <Col span={11}>
                                                <FormItem label={ChineseEnglishSize.StkTakeMaintenancedesc ? ChineseEnglishSize.StkTakeMaintenancedesc.descripts:'盘点组描述：'} {...formItemItem}>
                                                    {getFieldDecorator('descripts', {
                                                        initialValue: userInfo.tkDesc ? userInfo.tkDesc : undefined,
                                                        rules:[{ required : ChineseEnglishSize.StkTakeMaintenancedesc ? ChineseEnglishSize.StkTakeMaintenancedesc.required =='Y'? true:false: false, message: ChineseEnglishSize.StkTakeMaintenancedesc ? ChineseEnglishSize.StkTakeMaintenancedesc.message:'请输入盘点组描述'}]  
                                                    })(
                                                        <Input style={{width: '100%'}} />
                                                    )}
                                                </FormItem>
                                            </Col>
                                            <Col span={11}>
                                            <FormItem label={ChineseEnglishSize.StkTakeMaintenanceENDesc ? ChineseEnglishSize.StkTakeMaintenanceENDesc.descripts:'英文描述：'} {...formItemItem}>
                                                {getFieldDecorator('ENDescripts', {
                                                    initialValue:  userInfo.tkENDesc ? userInfo.tkENDesc : undefined,
                                                })(
                                                    <Input style={{width: '100%'}} />
                                                )}
                                            </FormItem>
                                            </Col>
                                        </Row>
                                        <Row>
                                            <Col span={11}>
                                            <FormItem label={ChineseEnglishSize.StkTakeMaintenancestartDate ? ChineseEnglishSize.StkTakeMaintenancestartDate.descripts:'生效日期：'} {...formItemItem}>
                                                {getFieldDecorator('startDate', {
                                                    initialValue:  userInfo.tkStartDate ? Moment(userInfo.tkStartDate) : undefined,
                                                    rules:[{ required : ChineseEnglishSize.StkTakeMaintenancestartDate ? ChineseEnglishSize.StkTakeMaintenancestartDate.required =='Y'? true:false: false, message: ChineseEnglishSize.StkTakeMaintenancestartDate ? ChineseEnglishSize.StkTakeMaintenancestartDate.message:'请选择生效日期'}]
                                                })(
                                                    <DatePicker
                                                        format="YYYY-MM-DD"
                                                        style={{width:'100%'}}
                                                    >
                                                    </DatePicker>
                                                )}
                                            </FormItem>
                                            </Col>
                                            <Col span={11}>
                                            <FormItem label={ChineseEnglishSize.StkTakeMaintenanceendDate ? ChineseEnglishSize.StkTakeMaintenanceendDate.descripts:'失效日期：'} {...formItemItem}>
                                                {getFieldDecorator('endDate', {
                                                    initialValue:  userInfo.tkEndDate ? Moment(userInfo.tkEndDate) : undefined,
                                                })(
                                                    <DatePicker
                                                        format="YYYY-MM-DD"
                                                        style={{width:'100%'}}
                                                    >
                                                    </DatePicker>
                                                )}
                                            </FormItem>
                                            </Col>
                                        </Row>
                                        {/* <Row>
                                            <Col span={6}>
                                                <FormItem label="独立医嘱：" {...formItemCheckbox}>
                                                    {getFieldDecorator('medNoAloneOrder', {
                                                        valuePropName: 'checked',
                                                        initialValue: userInfo.medNoAloneOrder === 'Y' ? true : false,
                                                    })(
                                                        <Checkbox />
                                                    )}
                                                </FormItem>
                                            </Col>
                                            <Col span={6}>
                                                <FormItem label="无库存医嘱：" {...formItemCheckbox}>
                                                    {getFieldDecorator('medNoStockFlag', {
                                                        valuePropName: 'checked',
                                                        initialValue:  userInfo.medNoStockFlag === 'Y' ? true : false,
                                                    })(
                                                        <Checkbox />
                                                    )}
                                                </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.StkTakeMaintenancesave ? ChineseEnglishSize.StkTakeMaintenancesave.descripts:'保存'}</Button>
                                <Button onClick={this.resetFields}>{ChineseEnglishSize.StkTakeMaintenancereSet ? ChineseEnglishSize.StkTakeMaintenancereSet.descripts:'重置'}</Button>
                            </Row>
                        </Col>
                    </Col>
                </div>
            )
        }
    }
);
export default DataMaintenance;