// 退药汇总统计
import React from 'react';
import {Card, Form, DatePicker, Select, Row, Col, Button, message} from 'antd';
import store from 'store';
import { $http } from 'containers/config/https';
import Moment from 'moment';
import { handleExcel } from 'tools/handleExcel.js';
import PubilcTablePagination from 'pages/common/PubilcTablePagination';
import ColumnAuthoritysModel from 'pages/columnAuthority/ColumnAuthoritysModel';
import 'assets/css/common.css';

let {Option} = Select;
let timeout;

class DrugWithdrawalSummaryStatistics extends React.Component {
    constructor() {
        super();
        this.state = {
            basicHeight: 0,
            parameterSetting: {}, // 界面默认数据
            searchOrdLocData: [], // 开单科室下拉框数据
            typeSelectData: [], // 类型下拉框数据
            columns: [],
            page: 1,
            pageSize: 20,
            total: 0,
            widthTotal: 0, // table总宽度
            loading: false
        }
    }

    componentDidMount() {
        this.getParameterSetting();
        this.getMainTableColumns();
        // 关闭loading
        this.child.handleLoading();
        this.setState({basicHeight: document.getElementById("drug-width-drawal-statictics-basic").clientHeight})
    }

    onRef = (ref) => {
        this.child = ref
    }

    // 获取默认参数配置
    getParameterSetting = () => {
        let data = {
			params: []
		}
		$http.post('urlS', this, {
			code: "02050005",
			data: data,
			success: function (res) {
				if (+res.errorCode === 0) {
                    this.setState({
                        parameterSetting: res.result[0] ? res.result[0] : {}
                    })
				}
            }
		})
    }

    // 3.2.1.9.2.获取管制药品统计界面类型下来数据集
    getTypeSelectData = () => {
        if(this.state.typeSelectData&&this.state.typeSelectData.length > 0) {
            return;
        }
        let data = {
			params: []
		}
		$http.post('urlS', this, {
			code: "02050002",
			data: data,
			success: function (res) {
				if (+res.errorCode === 0) {
                    this.setState({typeSelectData: res.result})
				}
			}
		})
    }

    // 开单科室下拉框数据搜索
    handleOrdLocSearch = (value) => {
        if (timeout) {
            clearTimeout(timeout);
            timeout = null;
        }
        timeout = setTimeout(() => {
            if (value) {
                let data = {
                    params: [{
                        alias: value
                    }]
                }
                $http.post('urlS', this, {
                    code: "02030007",
                    data: data,
                    success: function (res) {
                        if (+res.errorCode === 0) {
                            this.setState({searchOrdLocData: res.result})
                        }
                    }
                })
            }
        }, 300)
    }

     // 获取主列表columns
     getMainTableColumns = () => {
        let data = {
			params: [{
                compontName: "DrugReturnList", // 病人登记号/证件号
                type: 'C', // 卡类型id
            }]
		}
		$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()}>{item.title}</div>
                        }
                    }) : '';
                    let filterArr = arr.filter(function(item){ return item.display === 'Y'});
                    this.setState({columns: filterArr, widthTotal: res.totalWidth})
                }
			}
		})
    }

    onMainColumnRef = (ref) => {
        this.mainColumnRef = ref;
    }

    // 请求列表数据
	getTableData () {
        this.setState({loading: true});
        const { form: { validateFields } } = this.props;
        validateFields((errors, values) => {
            if (errors === null) {
                let { page, pageSize } = this.state;
                let data = {
                    params: [{
                        startDate: values.startDate ? Moment(values.startDate).format("YYYY-MM-DD") : Moment(), // 开始日期
                        endDate: values.endDate ? Moment(values.endDate).format("YYYY-MM-DD") : '', // 截止日期
                        phaTypeID: values.phaTypeID, // 类型ID
                        ordLocID: values.ordLocID, // 科室
                    }],
                    pagination:[{
                        pageSize: pageSize,
                        currentPage: page,
                        sortColumn: "Describe",
                        sortOrder: "asc"
                    }]
                }
                $http.post('urlS', this, {
                    code: "02050006",
                    data: data,
                    success: function (res) {
                        if (+res.errorCode === 0 && res.result) {
                            let arr = res.result[0].rows ? res.result[0].rows : [];
                            for (var i = 0; i < arr.length; i++) {
                                arr[i].key = i + 1
                            }
                            this.setState({tableData: arr, total: res.result[0].total, loading: false}, () => {
                                // 数据加载成功关闭loading
                                this.child.handleLoading()
                            })
                        } else {
                            this.setState({tableData: [], total: 0, loading: false}, () => {
                                // 数据加载成功关闭loading
                                this.child.handleLoading();
                            })
                        }
                    },
                    error: function () {
                        this.setState({tableData: [], total: 0, loading: false}, () => {
                            // 数据加载成功关闭loading
                            this.child.handleLoading();
                        })
                    }
                })
            }
        })

	}

    // 查询
    handleQuery = () => {
        this.setState({page: 1}, () => {
            this.getTableData()
        })
    }

    // 提供修改page和pageSize的回调函数
    compilePage(page, pageSize) {
        this.setState({ page: page, pageSize: pageSize }, () => {
            // 重新调用查询方法
            this.getTableData();
        })
    }

    // 导出
    exportTableData = () => {
        let {tableData, columns} = this.state;
        if (!(tableData&&tableData.length > 0)) {
            message.info("统计列表有数据时才支持导出功能");
            return;
        }
        const { form: { validateFields } } = this.props;
        validateFields((errors, values) => {
            if (errors === null) {
                let data = {
                    params: [{
                        startDate: values.startDate ? Moment(values.startDate).format("YYYY-MM-DD") : Moment(), // 开始日期
                        endDate: values.endDate ? Moment(values.endDate).format("YYYY-MM-DD") : '', // 截止日期
                        phaTypeID: values.phaTypeID, // 类型ID
                        ordLocID: values.ordLocID, // 科室
                    }],
                    pagination:[{
                        pageSize: 10000,
                        currentPage: 1,
                        sortColumn: "Describe",
                        sortOrder: "asc"
                    }]
                }
                $http.post('urlS', this, {
                    code: "02050006",
                    data: data,
                    success: function (res) { 
                        if (+res.errorCode === 0) {
                            let arr = res.result[0]&&res.result[0].rows ? res.result[0].rows : [];
                            // console.log(columns, arr)
                            handleExcel.exportExcel(columns, arr, '退药汇总统计');
                        }
                    }
                })
            }
        })
    }

    // 清屏
    resetFields = () => {
        this.props.form.resetFields();
        this.setState({tableData: [], total: 0})
    }

    render() {
        let {parameterSetting, searchOrdLocData, typeSelectData, basicHeight, columns, tableData, total, page, widthTotal, loading} = this.state;
        const { getFieldDecorator } = this.props.form;
        const formItemInput  = {
            labelCol: {span: 9},
            wrapperCol: {span: 15}
        };
        // 组件所需参数
		const param = {
			// 表头配置
			columns,
			// 表格数据
			data: tableData,
			// 数据总条数
			total,
			// 当前页数
			page,
			// 表格的宽度
			x: widthTotal,
			y: store.getState().tableHeight.y + 202 - 123 - basicHeight + 'px',
            height: store.getState().tableHeight.y + 202 - 77 - basicHeight + 'px',
            loading,
            pageSize: "20"
        }

        // 类型
		let typeOption = typeSelectData && typeSelectData.map((item, index) => {
			return (<Option key={index} value={item.id} title={item.descripts} seatchprop={item.descripts + '^' + item.descriptsSPCode}>{item.descripts}</Option>)
        })
        // 开单科室
        let ordLocOption = searchOrdLocData&&searchOrdLocData.map((item, index) => {
			return (<Option key={index} value={item.id} title={item.descripts} seatchprop={item.descripts + '^' + item.descriptsSPCode}>{item.descripts}</Option>)
        })
        return (
            <div>
                 <Card
                    size="small"
                    title={<div className="card-title-left-icon"><div></div>基本操作</div>}
                    id="drug-width-drawal-statictics-basic"
                >
                    <Form>
                        <Row style={{marginTop: '12px'}}>
                            <Col span={3}>
                                <Form.Item label="开始日期" {...formItemInput}>
                                    {getFieldDecorator('startDate', {
                                        initialValue: parameterSetting.startDate ? Moment(parameterSetting.startDate) : Moment(),
                                    })(
                                        <DatePicker style={{width: '100%'}} />
                                    )}
                                </Form.Item>
                            </Col>
                            <Col span={3}>
                                <Form.Item label="截止日期" {...formItemInput}>
                                    {getFieldDecorator('endDate', {
                                        initialValue: parameterSetting.endDate ? Moment(parameterSetting.endDate) : Moment(),
                                    })(
                                        <DatePicker style={{width: '100%'}} />
                                    )}
                                </Form.Item>
                            </Col>
                            <Col span={3}>
                                <Form.Item label="类型" {...formItemInput}>
                                    {getFieldDecorator('phaTypeID', {
                                            initialValue: undefined,
                                        })(
                                            <Select
                                                showSearch optionFilterProp="seatchprop"
                                                allowClear
                                                placeholder="请选择"
                                                onFocus={this.getTypeSelectData}
                                            >
                                                {typeOption}
                                            </Select>
                                        )}
                                </Form.Item>
                            </Col>
                            <Col span={3}>
                                <Form.Item label="开单科室" {...formItemInput}>
                                    {getFieldDecorator('ordLocID', {
                                        initialValue: undefined,
                                    })(
                                        <Select
                                            showSearch
                                            defaultActiveFirstOption={false}
                                            showArrow={false}
                                            filterOption={false}
                                            onSearch={this.handleOrdLocSearch}
                                            notFoundContent={null}
                                            placeholder="请输入搜索条件"
                                            allowClear
                                        >
                                            {ordLocOption}
                                        </Select>
                                    )}
                                </Form.Item>
                            </Col>
                            <Col span={12} style={{marginTop: '4px'}}>
                                <Button onClick={this.handleQuery} style={{marginLeft: '150px'}}>查询</Button>
                                <Button
                                    type="dashed"
                                    style={{margin: '0 15px'}}
                                >打印</Button>
                                <Button
                                    type="dashed"
                                    onClick={this.exportTableData}
                                    style={{marginRight: '15px'}}
                                >导出</Button>
                                <Button
                                    type="primary"
                                    onClick={this.resetFields}
                                >清屏</Button>
                            </Col>
                        </Row>
                    </Form>
                </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>}
                >
                    <div style={{height: store.getState().tableHeight.y + 202 - 30 - basicHeight + 'px', overflow: 'auto'}}>
                        <PubilcTablePagination param={param} handelThis={this} onRef={this.onRef} />
                    </div>
                </Card>
                <ColumnAuthoritysModel
                    clientWidth='800px'
                    compontName='DrugReturnList'
                    configType="C"
                    onRef={this.onMainColumnRef}
                    reloadData={this.getMainTableColumns}
                />
            </div>
        )
    }
};
const DrugWithdrawalSummaryStatisticsForm = Form.create()(DrugWithdrawalSummaryStatistics);
export default DrugWithdrawalSummaryStatisticsForm;