/**
 * @ByDYK: 导出功能模块（通用）
 * Create 2022-09-27
 */
import React, { Component } from 'react';
import { message, Input, Button, Col, Form, Row, DatePicker, Icon, Spin } from 'antd';
import moment from 'moment';
import PubilcTablePagination from 'pages/common/PubilcTablePagination.jsx';
const dateFormat = 'YYYY-MM-DD'; //定义全局日期格式


class ExportFile extends Component{

    constructor(props) {
        super(props);
        this.state = {
            page:1,
            pageSize:10,
            total:0,
            loading:false,
            startDate:'',
            endDate:'',
            status:'', //状态  ''全部,0队列中,1导出中,2导出成功,99导出失败
            columns:[],
            recordData:[],
            typeResultOBJ:{},    //当前功能模型配置详情
            maskStatus:false, //整体遮罩
        }
    }

    componentDidMount() {
        this.getColumn();
        this.getTypeInfo();
    }

    // 获取表头信息
    getColumn = async () => {
        let data = {
            params: [{
                compontName: 'ExportFileRecord',
                type: 'C',
                reactCode: ['ExportFileRecord']
            }]
        };
        const resObj = await React.$asyncPost(this,'01040073',data);
        if (resObj) {
            let errorCode = resObj.errorCode;
            if (+errorCode === 0) {
                let columns = resObj.result && resObj.result.C.length > 0 ? JSON.parse(JSON.stringify(resObj.result.C)).map(item => {
                    return {
                        align: item.align,
                        widthNum: parseInt(item.width),
                        width: item.width,
                        dataIndex: item.dataIndex,
                        title: item.title,
                        display: item.display,
                        key: item.seqNo
                    }
                }) : '';
                this.renderList(columns);//对指定的列进行渲染操作
                this.setState({
                    columns:columns
                },function () {
                    this.listAdd(columns.length+1, 0);
                })
            }else {
                message.error(resObj.errorMessage)
            }
        }
    };

    //对表头列进行渲染操作
    renderList = (columnsValue) => {
        for (let i = 0; i < columnsValue.length; i++) {
            //状态渲染
            if (columnsValue[i].dataIndex === 'createDate') {
                columnsValue[i].render = (text,record) => {
                    return (<span>{text} {record.createTime}</span>)
                }
            }
            //状态渲染
            if (columnsValue[i].dataIndex === 'status') {
                columnsValue[i].render = (text) => {
                    if (+text === 2) {
                        return (<span style={{ color: '#45B38E' }}>导出成功</span>)
                    } else if(+text === 99){
                        return (<span style={{ color: '#EE3F3F' }}>导出失败</span>)
                    }else if(+text === 0){
                        return (<span style={{ color: '#eeaa03' }}>队列中</span>)
                    }else if(+text === 1){
                        return (<span style={{ color: '#0c74ee' }}>导出中</span>)
                    }
                }
            }
        }
    };

    //获取功能类型配置详情
    getTypeInfo = async () => {
        let data = {
            params: [{
            }]
        };
        const resObj = await React.$asyncPost(this,'11020003',data);
        if (resObj) {
            let errorCode = resObj.errorCode;
            if (+errorCode === 0) {
                this.setState({
                    typeResultOBJ : resObj?.result
                });
                let fieldTypeArr = resObj.result.subList || [];
                if(fieldTypeArr[0].fieldTypeID === 'date'){ //日期类型
                    this.setState({
                        startDate:fieldTypeArr[0].defaultValue,
                        endDate:fieldTypeArr[1].defaultValue
                    },function () {
                        this.recordListQuery();
                    })
                }
            }else {
                message.error(resObj.errorMessage)
            }
        }
    };

    //时间选择器
    datePickerOnChange = (e,value,key) => {
        this.setState({
            [key]: value
        })
    };
    //输入框
    inputChange = (e,key) => {
        let value = e.target.value;
        this.setState({
            [key]: value
        })
    };

    //查询
    recordListQuery = async () => {
        let {startDate,endDate,status,page,pageSize} = this.state;
        if(startDate === ''){
            message.warning('[开始日期]不能为空！');
            return
        }else if(endDate === '') {
            message.warning('[结束日期]不能为空！');
            return
        }else if(startDate > endDate){
            message.warning('[结束日期]不能早于[开始日期]！');
            return
        }
        let data = {
            params: [{
                startDate,
                endDate,
                status
            }],
            pagination: [{
                pageSize: pageSize,
                currentPage: page
            }]
        };
        let resObj = await React.$asyncPost(this,'11020001',data);
        if (resObj) {
            let errorCode = resObj.errorCode;
            if (+errorCode === 0) {
                let resListData = resObj.result && resObj.result.rows;
                if(resListData.length === 0){
                    message.warning('查询数据为空！');
                    this.setState({
                        recordData:[],
                        total:0
                    });
                    return
                }
                for (let i = 0; i < resListData.length; i++) {
                    resListData[i].key = i;
                }
                 this.setState({
                     recordData:resListData,
                     total:resObj.result.total
                 },function () {
                     this.setState({
                         maskStatus:false
                     });
                 })
            }else {
                message.error(resObj.errorMessage)
            }
        }
    };

    // 提供修改page和pageSize的回调函数
    compilePage = (page, pageSize) => {
        this.setState({ page, pageSize }, () => {
            this.recordListQuery();
        })
    };

    //render 自定义项目名称
    listAdd = (i, j) => {
        let { columns } = this.state;
        columns.splice(i, j,
            {
                title: '操作',
                key: 'op',
                align: 'center',
                width: '80px',
                render: (text, record) => (
                    <span>
                        {+record.status === 2 ?
                            <a className='span' download="" href={record.downloadURL}><Icon type="download"/> 下载</a>:
                            <span style={{color:'#ccc'}}><Icon type="download"/> 下载</span>
                        }
                    </span>
                ),
            },
        )
    };

    render() {
        let {page,total,loading,columns,recordData,maskStatus} = this.state;
        const params = {
            page,
            total,
            loading,
            columns,
            data: recordData,
            x: 900,
            y: 400,
            height: 450,
            rowKey: 'ID',
            componentName:'ExportFileRecord'
        };
        return (
            <div>
                <Spin spinning={maskStatus} tip="导出中，请勿离开...">
                    <Row justify='space-between'>
                        <Col span={18} style={{paddingLeft:'20px'}}>
                            {
                                this.state.typeResultOBJ?.subList && this.state.typeResultOBJ?.subList.length > 0 ?
                                    this.state.typeResultOBJ?.subList.map((item,index) => {
                                        if(item?.fieldTypeID === 'date') {
                                           return (
                                               <span>
                                                   {item?.desc} :
                                                <DatePicker
                                                    allowClear={false}
                                                    placeholder={item?.desc}
                                                    style={{ marginRight:'20px',marginLeft:'10px'}}
                                                    format={dateFormat}
                                                    defaultValue={moment(item?.defaultValue, dateFormat)}
                                                    onChange={(e,value) => this.datePickerOnChange(e,value,item?.code)}/>
                                               </span>
                                           )
                                        }else if(item?.fieldTypeID === 'Input'){
                                            return (
                                                <span>
                                                   {item?.desc} :
                                                    <Input
                                                        style={{width: '200px',marginRight:'20px',marginLeft:'10px'}}
                                                        onPressEnter={this.recordListQuery}
                                                        onChange={(e)=>this.inputChange(e,item?.code)}
                                                    />
                                               </span>
                                            )
                                        }else {

                                        }
                                    })
                                :''
                            }
                        </Col>
                        <Col span={6} style={{ textAlign: 'right',paddingRight:'20px'}}>
                            <Button type='primary' onClick={this.recordListQuery}>查询</Button>
                        </Col>
                    </Row>
                    <Row style={{marginTop:20}}>
                        <PubilcTablePagination param={params} compilePage={this.compilePage}  getColumns={this.getColumn}/>
                    </Row>
                </Spin>
            </div>
        );
    }
}
const ExportForm = Form.create()(ExportFile);
export default ExportForm;
