/*
 * Creator:     PYH
 * CreatDate:   2020-03-12
 * Descripts：  快递员工作量统计
 * */

import React from 'react';
import { $http } from '../../containers/config/https';
import {Form,Select,Table,Card,Row,Col,Button } from 'antd'
import RangeDatePicker from 'components/rangePicker/index';
import CommonPagination from 'components/pagination';
import moment from 'moment';
import './style/index.less';
import store from 'store';

const { Option } = Select;
const formLayout = {
    labelCol: { span: 7 },
    wrapperCol: { span: 14 },
}
const searchColConfig = {
    xs: { span: 24 },
    sm: { span: 12 },
    md: { span: 10 },
    lg: { span: 6}
  }

class ExpressWorkloads extends React.Component{
    constructor(){
        super();
        var userData = JSON.parse(sessionStorage.getItem('userData'))
        this.state={
            userData:userData,
            startDate:moment().format('YYYY-MM-DD'),
            endDate:moment().format('YYYY-MM-DD'),
            delivery:'',
            tableData: [], 
            columns: [],
            total: 0,
            page: 1,
            pageSize: 50,
            size: "small",
        }
    }
    componentDidMount() {
        document.querySelector('.expWorkloadDom .ant-table-body').style.height = store.getState().tableHeight.y + 92 + 'px';
        if (this.state.size == "small") {
            this.setState({
                pageSize: 10
            })
        } else {
            this.setState({
                pageSize: 50
            })
        }
        this.getDeliverySelect()
        this.getTableColumns()
        this.getFindData("search");
    }
    
    // 快递人员下拉
    getDeliverySelect(){
        let data = {
            params: [{

            }],
        }
        $http.post('urlS', this, {
            code: '03030063',
            data: data,
            success: function (res) {
                if (+res.errorCode === 0) {
                    this.setState({
                        deliveryArr: res.result
                    })
                }
            }
        })
    }
    // 递归获取分组的表头
    renderColumn(tableColumns, renderColumns){
        tableColumns && tableColumns.map(item => {
            let column = {
                title: item.headDesc,
                key: item.headCode,
            }
            if (item.child){
                let childColumn = this.renderColumn(item.child, [])
                column.children = childColumn
            }else{
                if (item.width) column.width = item.width
                if (item.align) column.align = item.align 
                column.dataIndex = item.headCode
            }
            // 样式处理
            column.render = (text, record, index) => {
                if(index == this.state.tableData.length-1){
                    if((column.dataIndex)&&(column.dataIndex.indexOf ('expService') > -1)){
                        let serviceID=column.dataIndex.replace(/[^0-9]/ig,"");
                        let expFinService='expFinService'+serviceID
                        if (record[expFinService]){
                            return(<span style={{ fontWeight:'bold'}}>{text}{record[expFinService]}</span>)
                        }else{
                            return(<span style={{ fontWeight:'bold'}}>{text}</span>)
                        }
                    }else{
                        return(<span style={{ fontWeight:'bold'}}>{text}</span>)
                    }
                }
                if((column.dataIndex)&&(column.dataIndex.indexOf ('expService') > -1)){
                    let serviceID=column.dataIndex.replace(/[^0-9]/ig,"");
                    let expFinService='expFinService'+serviceID
                    if (record[expFinService]){
                        return(<span>{text}<span style={{color:'#1999db'}}>{record[expFinService]}</span></span>)
                    }else{
                        return (<span>{text}</span> )
                    }
                }else{
                    return (<span>{text}</span> )
                }
            }
            renderColumns.push(column)
        });
        return renderColumns
    }

    // 获取列表columns
    getTableColumns(){
        let data = {
            params: [{

            }],
        }
        $http.post('urlS', this, {
            code: '03030064',
            data: data,
            success: function (res) {
                if (+res.errorCode === 0) {
                   if (res.result){
                       this.setState({
                            columns: this.renderColumn(res.result, [])
                       })
                   }
                }
            }
        });  
    }
    // 点击查询
    handleQuery = () => {
        this.props.form.validateFields((err, values) => {
            if (!err) {
                this.setState({
                    values,
                }, () => {
                    this.onShowSizeChange("1", this.state.pageSize)
                })
            }
        })
    }
     //查询
     getFindData = (e) => {
        let { page, pageSize, startDate, endDate} = this.state;
        this.props.form.validateFields((err, values) => {
           let data = {
            params: [{
                startDate: startDate,
                endDate: endDate,
                deliveryUserID:values.deliveryID
            }],
            pagination: [{
                pageSize: pageSize,
                currentPage: page,
            }]
        } 
        $http.post('urlS', this, {
            code: '03030065',
            data: data,
            success: function (res) {
                if (+res.errorCode === 0) {
                    this.setState({
                        search: e,
                        tableData: res.result.data,
                        total: res.result.totalCount,
                    })
                }
            }
        })
        })
    }
    startChange(date) {
        this.setState({
            startDate: date,
        })
    }
    endChange(date) {
        this.setState({
            endDate: date,
        })
    }
    onChange = (e) => {
        this.setState({ page: e, pageSize: this.state.pageSize, }, () => {
            this.getFindDate();
        })
    }
    onShowSizeChange = (page, pageSize) => {
        this.setState({ page: 1, pageSize: pageSize }, () => {
            this.getFindData("search");
        })
    }
    showTotal(total) {
        return `共 ${total} 条`;
    }
    render(){
         let deliveryOp = []
         this.state.deliveryArr && this.state.deliveryArr.map((item) => {
            deliveryOp.push(<Option key={item.id} value={String(item.id)}>{item.descripts}</Option>)
         })
          let columns=this.state.columns
         const { getFieldDecorator } = this.props.form;
        return(
            <div className="expWorkloadDom">
                <Form>
                    <Row  style={{ margin: "0", padding: "14px 0 0 1px" }}>
                        <Col {...searchColConfig} style={{ padding: "4px 16px" }}>  
                            <RangeDatePicker isChange={true} label={ this.state.userData.language == 'EN' ? 'Delivery time：' : '配送时间：' } format='YYYY-MM-DD' width={'300px'}
                                allowClear={false}
                                locale={this.state.userData.language}
                                startDate={this.state.startDate} endDate={this.state.endDate}
                                startChange={this.startChange.bind(this)} endChange={this.endChange.bind(this)}  />
                        </Col>
                        <Col span={5}>
                            <Form.Item  {...formLayout} label={this.state.userData.language == 'EN' ? 'Delivery user：' : '配送人员：'}>
                                {getFieldDecorator('deliveryID', {
                                    initialValue:  undefined,
                                    rules: [{ required: false, message: "" }],
                                })(
                                    <Select allowClear>
                                            {deliveryOp }
                                    </Select>
                                    )}
                            </Form.Item>
                        </Col>
                        <Col span={4}>
                            <Button style={{ margin: '3px 0 0 10px' }} type="primary" onClick={this.handleQuery}>{this.state.userData.language == 'EN' ? 'Search' : '查询'}</Button>
                        </Col>
                    </Row>
                    <div style={{ widht: '100%', height: '10px', background: '#f0f2f5' }}></div>
                    <div className='expWorkload-table'>
                        <Table
                                columns={columns}
                                dataSource={this.state.tableData}
                                pagination={false}
                                bordered
                                style={{ height: store.getState().tableHeight.y + 128+ 'px'}}
                                scroll={{ x: 400}}
                            />
                            <CommonPagination size={this.state.size} current={this.state.page} total={this.state.total} search={this.state.search}
                                onShowSizeChange={this.onShowSizeChange.bind(this)} complete={true} dataSource={this.state.tableData}
                                    onChange={this.onChange.bind(this)} />
                        </div>
                </Form>
            </div>
        );

    }
};

const ExpressWorkload = Form.create()(ExpressWorkloads);
export default ExpressWorkload;