import React, { Component } from 'react';
import { Tabs, Card, Row, Button, Col, Input, Radio, DatePicker, Select, Form, Table, Pagination, Modal, message, Icon, Popconfirm } from 'antd';
import Moment from 'moment';
import { $http } from '../../../containers/config/https';
import ColumnAuthoritysModel from '../../columnAuthority/ColumnAuthoritysModel'
import './style/index.less';
import SpecCollectModal from './SpecCollectModal.jsx';
import { Util } from 'tools/index';
import store from 'store';
import CommonRangePicker from 'components/rangePicker/index';
import CommonPagination from 'components/pagination/index';

const { TabPane } = Tabs;
const { Option } = Select;

let user;
let userData = window.sessionStorage.userData ? JSON.parse(window.sessionStorage.userData) : {};

const SpecCollect = Form.create()(
    class SpecCollect extends React.Component {
        constructor(props) {
            super(props);
            user = window.sessionStorage.userData ? JSON.parse(window.sessionStorage.userData) : {};
            this.state = {
                total: 0,
                page: 1,
                pageSize: 10,
                columns: [],    //列
                locNurUser: [], //护士列表
                hospUser: [],   //护工列表
                tableData: [],  //出院患者列表
                sortColumn: 'Date',
                tableType: 'C',
                lisLocAry: [],
                specTransStatus: [], //标本运送状态
                specimenAry: [],    //标本类型
                specTransSheetID: '',
                specSheetNumber: '',    //运单号码
                defaultValueObj: {},    //默认值对象
                transFlag: true,     //移交按钮状态
                updateFlag: true,    //编辑按钮状态
                newSpecFlag: true,   //新增运送单标记
                specTransSheet: {},      //选中行数据对象
                handoverVisible: false,  //移交确认框
                handoverUserModal: '',     //移交弹框护士
                receiveUserModal: '',
                specHandoverUserID: '',
                specReceiveUserID: '',
                specTransStatusCode: 'All',
                cardTypeList: [],
                specTransStatusCodePost: '',
            }
            this.fatherQuery = this.fatherQuery.bind(this);
        }

        componentDidMount() {
            this.loadColumn('SpecCollectSheetList');
            this.initSource();
            this.initDefaultValue();
        }

        componentWillUnmount() {
            // 组件销毁前将静止让setState修改state的状态
            this.setState = (state, callback) => { return; }
            document.querySelector('.ant-table-body').style.height = store.getState().tableHeight.y + 'px';
        }


        //查询列头数据
        loadColumn = (compontName) => {
            let data = {
                params: [{
                    compontName: compontName ? compontName : this.state.compontName,
                    type: "C",
                    reactCode: [compontName ? compontName : this.state.compontName]
                }]
            }
            $http.post('urlDeault', this, {
                code: "01040073",
                data: data,
                success: (res) => {
                    if (res.errorCode == 0) {
                        let column = res.result.C;
                        if (user.language == 'EN') {
                            for (let i = 0; i < column.length; i++) {
                                column[i].title = column[i].enDescripts
                            }
                        }
                        var arr = Object.keys(res.result.language.EN);
                        if (arr.length > 0) {
                            this.setState({
                                [(compontName ? compontName : this.state.compontName) + "Column"]: res.result.C,
                                ENObj: res.result.language.EN,
                                CNObj: res.result.language.CN
                            })
                        } else {
                            this.setState({
                                [(compontName ? compontName : this.state.compontName) + "Column"]: res.result.C,
                            })
                        } if (+res.errorCode === 0) {
                            let resData = res.result[this.state.tableType];
                            for (let index = 0; index < resData.length; index++) {
                                resData[index].key = index;
                            }
                            const optionObj = {
                                title: "操作",
                                key: resData.length,
                                fixed: 'right',
                                align: 'center',
                                width: 100,
                                render: (text, record) => {
                                    return (
                                        ((!Util.isEmpty(record)) && (record.specTransStatusCode == 'New')) ? (
                                            <span>
                                                <Icon type="delete" style={{ color: 'rgba(240,65,52,1)' }}></Icon>
                                                <Popconfirm title="删除不可恢复，你确定要删除吗?"
                                                    onConfirm={() => this.handleDelete(record)} >
                                                    <span className='span' style={{ color: 'rgba(240,65,52,1)' }}>删除</span>
                                                </Popconfirm>
                                            </span>
                                        ) : null
                                    )
                                }
                            }
                            resData.push(optionObj);
                            this.setState({
                                columns: resData,
                                tableWidth: (parseInt(res.totalWidth.split('px')[0]) + optionObj.width) + "px"
                            }
                            )
                        }

                    }
                }
            })
        }

        //查询列头数据
        // loadColumn = () => {
        //     let data = {
        //         params: [{
        //             compontName: "SpecCollectSheetList",
        //             type: this.state.tableType,
        //         }]
        //     }
        //     $http.post('urlS', this, {
        //         code: "01040073",
        //         data: data,
        //         success: (res) => {
        //             if (+res.errorCode === 0) {
        //                 let resData = res.result[this.state.tableType];
        //                 for (let index = 0; index < resData.length; index++) {
        //                     resData[index].key = index;
        //                 }
        //                 const optionObj = {
        //                     title: '操作',
        //                     key: resData.length,
        //                     fixed: 'right',
        //                     align: 'center',
        //                     width: 100,
        //                     render: (text, record) => {
        //                         return (
        //                             ((!Util.isEmpty(record)) && (record.specTransStatusCode == 'New')) ? (
        //                                 <span>
        //                                     <Icon type="delete" style={{ color: 'rgba(240,65,52,1)' }}></Icon>
        //                                     <Popconfirm title="删除不可恢复，你确定要删除吗?"
        //                                         onConfirm={() => this.handleDelete(record)} >
        //                                         <span className='span' style={{ color: 'rgba(240,65,52,1)' }}>删除</span>
        //                                     </Popconfirm>
        //                                 </span>
        //                             ) : null
        //                         )
        //                     }
        //                 }
        //                 resData.push(optionObj);
        //                 this.setState({
        //                     columns: resData,
        //                     tableWidth: (parseInt(res.totalWidth.split('px')[0])+optionObj.width)+"px"
        //                 }
        //                 )
        //             }
        //         }
        //     })
        // }

        initSource = () => {
            let data = {
                params: [{
                    compontName: "SpecCollectSheetList",
                    type: this.state.tableType,
                }]
            }
            $http.post('urlS', this, {
                code: "04130022",
                data: data,
                success: (res) => {
                    if (+res.errorCode === 0) {
                        this.setState({
                            locNurUser: res.result.locNurUser,
                            hospUser: res.result.hospUser,
                            lisLocAry: res.result.lisLocAry,
                            specimenAry: res.result.specimenAry,
                            specTransStatus: res.result.specTransStatus,
                        }
                        )
                    }
                }
            })
        }

        initDefaultValue = () => {
            let data = {
                params: [{
                    defaultAppObj: {
                        SpecTrans: ['startDate', 'stopDate', 'specTransStatusCode'],
                    }
                }]
            }
            $http.post('urlS', this, {
                code: "04110023",
                data: data,
                success: (res) => {
                    if (+res.errorCode == '0') {
                        this.setState({
                            defaultValueObj: res.result,
                            stDate: Moment(res.result.startDate).format('YYYY-MM-DD'),
                            endDate: Moment(res.result.stopDate).format('YYYY-MM-DD')
                        }, () => {
                            this.handleQuery();
                        }
                        )
                    }
                }
            })
        }

        fatherQuery(code) {
            this.handleQuery(code);
        }

        handleQuery = (code) => {
            const formData = this.props.form.getFieldsValue();
            let data = {
                params: [{
                    specSheetNumber: this.state.specSheetNumber,
                    specTransStatusCode: this.state.specTransStatusCode,
                    startDate: this.state.stDate ? Moment(this.state.stDate).utcOffset(480).format('YYYY-MM-DD') : '',
                    stopDate: this.state.endDate ? Moment(this.state.endDate).utcOffset(480).format('YYYY-MM-DD') : '',
                    specHandoverUserID: this.state.specHandoverUserID,
                    specReceiveUserID: this.state.specReceiveUserID,
                }],
                pagination: [{
                    pageSize: this.state.pageSize,
                    currentPage: this.state.page,
                    sortColumn: this.state.sortColumn,
                    sortOrder: 'desc'
                }]
            }
            $http.post('urlS', this, {
                code: "04130021",
                data: data,
                success: (res) => {
                    if (+res.errorCode === 0) {
                        for (let index = 0; index < res.result.Data.length; index++) {
                            res.result.Data[index].key = index;
                        }
                        this.setState({
                            total: res.result.TotalCount,
                            tableData: res.result.Data,
                            code: code
                        })
                        if (code === 'code') {
                            this.setState({
                                specTransSheet: this.state.tableData[0],
                                specTransSheetID: this.state.tableData[0].specTransSheetID,
                                updateFlag: true,
                            })
                        }
                    } else {
                        this.setState({
                            total: 0,
                            tableData: []
                        });
                    }
                }
            })
            // this.commonChild.handleLoading();
        }

        // 调用公共组件的连接事件
        onRef = (ref) => {
            this.child = ref
        }
        handleOnRef = (ref) => {
            this.commonChild = ref
        }


        // 操作行
        onClickRowPublic = (record) => {
            return {
                // 单击行选中
                onClick: () => {
                    if (this.state.specTransSheetID === record.specTransSheetID) {
                        //取消选中
                        this.setState({
                            transFlag: true,
                            updateFlag: true,
                            newSpecFlag: false,
                            specTransSheetID: '',
                            newSpecFlag: true,
                            specTransSheet: {},
                            specTransStatusCodePost: '',
                            code: '',
                        }, () => {
                            //调用子组件查询方法
                            this.child.clearData();
                        })

                    } else {
                        //非建单状态不可编辑
                        let enable = ((record.specTransStatusCode !== "") && (record.specTransStatusCode === 'New')) ? false : true
                        this.setState({
                            transFlag: enable,
                            updateFlag: enable,
                            newSpecFlag: true,
                            newSpecFlag: false,
                            specTransSheetID: record.specTransSheetID,
                            specTransSheet: record,
                            specTransStatusCodePost: record.specTransStatusCode,
                            code: ''
                        }, () => {
                            //调用子组件查询方法
                            this.child.handleQuery();
                        })
                    }
                },
                // 双击行选中
                onDoubleClick: () => {
                    // this.callTable1(record)
                }
            }
        }

        // 选中行操作
        setRowClassNamePublic = (record, index) => {
            if (index == '0' && this.state.code == 'code') {
                return 'clickRowStyle'
            } else {
                return record.specTransSheetID === this.state.specTransSheetID ? 'clickRowStyle' : '';
            }

        }

        //组件权限编辑器
        onColumnRef = (ref) => {
            this.columnRef = ref;
        }

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

            })
        }

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

        // 页码改变的回调，参数是改变后的页码及每页条
        onChange = (page, pageSize) => {
            this.compilePage(page, pageSize);
        }

        // 条数改变的回调
        onShowSizeChange = (current, size) => {
            this.compilePage(1, size);
        }

        AddSpecTrans = () => {
            this.setState({
                specTransSheet: {},
                newSpecFlag: true,
                specTransSheetID: '',
            }
                , () => {
                    this.child.clearData();
                })
        }
        //tab页签切换
        tabPaneChange = (key) => {

        }
        //运单状态切换
        handleStatusChange = (e) => {
            this.setState({ specTransStatusCode: e.target.value }
                , () => {
                    this.handleQuery();
                })
        }
        //运单号回车
        sheetNumberDown = (e) => {
            this.setState({ specSheetNumber: e.target.value }
                , () => { this.handleQuery(); })
        }
        //交接人下拉数据修改
        handoverUserChange = (value) => {
            this.setState({ specHandoverUserID: value }
                , () => {
                    this.handleQuery();
                })
        }
        //运送人下拉数据修改
        receiveUserChange = (value) => {
            this.setState({ specReceiveUserID: value }
                , () => {
                    this.handleQuery();
                })
        }
        //移交点击
        sheetHandover = () => {
            this.setState({
                handoverVisible: true,
            })
        }
        //修改明细
        sheetDetailEdit = () => {
            this.setState({
                transFlag: false,
                updateFlag: true,
                newSpecFlag: true,
            }, () => {
                //修改明细数据
                this.child.editDetailData();
            })
        }
        //移交弹出框取消按钮
        handleOk = () => {
            let data = {
                params: [{
                    specTransSheetID: this.state.specTransSheetID,
                    updateUserID: userData.userID,
                    sheetStatusCode: 'Handover',
                    specReceiveUserID: this.state.receiveUserModal,
                    specHandoverUserID: this.state.handoverUserModal,
                }]
            }
            $http.post('urlADS', this, {
                code: '04130020',
                data: data,
                success: (res) => {
                    if (+res.errorCode === 0) {
                        message.success('移交成功');
                        this.setState({
                            handoverVisible: false,
                            handoverUserModal: '',
                            receiveUserModal: '',
                        }
                            , () => {
                                this.handleQuery();
                            })
                    }
                }
            })
        }
        //移交弹出框取消按钮
        handleCancel = () => {
            this.setState({
                handoverVisible: false,
                handoverUserModal: '',
                receiveUserModal: '',
            })
        }
        //修改移交人
        handoverUserModal = (userID) => {
            this.setState({
                handoverUserModal: userID
            })
        }
        //修改运送人
        receiveUserModal = (userID) => {
            this.setState({
                receiveUserModal: userID
            })
        }
        //删除运单
        handleDelete = (record) => {
            if (Util.isEmpty(record.specTransSheetID)) return
            let data = {
                params: [{
                    specTransSheetID: record.specTransSheetID,
                }]
            }
            $http.post('urlADS', this, {
                code: '04130006',
                data: data,
                success: function (res) {
                    if (res.errorCode === '0') {
                        message.success('删除成功');
                        this.handleQuery();
                        this.AddSpecTrans()
                    }
                }
            })
        }
        render() {
            const tableHeight = store.getState().tableHeight.y - 90;
            const { getFieldDecorator } = this.props.form;
            const formSheetNumber = {
                labelCol: { span: 2 },
                wrapperCol: { span: 18 },
            }

            const selectUserLayout = {
                labelCol: { span: 6 },
                wrapperCol: { span: 14 },
            }

            const dateLayout = {
                labelCol: { span: 7 },
                wrapperCol: { span: 14 },
            }

            const statusCodeLayout = {
                labelCol: { span: 3 },
                wrapperCol: { span: 21 },
            };

            const cardType = [];
            this.state.cardTypeList.map((item) => {
                cardType.push(
                    <Option key={item.id} value={item.id} cardlength={item.cardLength}>
                        {user.language == 'CN' ? item.descripts : item.enDescripts}
                    </Option>
                )
            })

            var language = user.language;
            var languageObj = {}
            if (language == "EN") {
                languageObj = this.state.ENObj
            } else {
                languageObj = this.state.CNObj
            }



            return (
                <div style={{ height: '100%', width: '100%' }} className='specCollect-Tab'>
                    <div style={{ height: '100%', float: 'left', width: '35%' }}>
                        <Card className='specCollect-table1-term' title={languageObj && languageObj.SpecCollectSheetListSpecimendeliverynote.descripts} onPressEnter={this.sheetNumberDown} headStyle={{ height: '25px' }} bodyStyle={{ height: 'calc(100% - 25px)' }}>
                            <Row style={{ height: '28%' }}>
                                <Form >
                                    <Form.Item {...formSheetNumber} label={languageObj && languageObj.SpecCollectSheetListSinglenumber.descripts + ":"}>
                                        {getFieldDecorator('specSheetNumber', {
                                            initialValue: undefined
                                        })(
                                            <Input placeholder={languageObj && languageObj.SpecCollectSheetListPlaceholder.descripts} onPressEnter={this.sheetNumberDown} />
                                        )}
                                    </Form.Item>
                                    <Row>
                                        <Col span={24} {...dateLayout} style={{ paddingLeft: '12px' }}>
                                            <CommonRangePicker
                                                width={300}
                                                label={languageObj && languageObj.SpecCollectSheetListDate.descripts + ":"}
                                                startDate={!Util.isEmpty(this.state.stDate) ? this.state.stDate : ''}
                                                endDate={!Util.isEmpty(this.state.endDate) ? this.state.endDate : ''}
                                                format={'YYYY-MM-DD'}
                                                startChange={(date) => this.setState({ stDate: date })}
                                                endChange={(date) => this.setState({ endDate: date })}
                                            />
                                        </Col>
                                    </Row>
                                    <Form.Item {...statusCodeLayout} label={languageObj && languageObj.SpecCollectSheetListWaybillstatus.descripts + ":"}>
                                        {
                                            getFieldDecorator('specTransStatusCode', {
                                                initialValue: Util.isEmpty(this.state.defaultValueObj.specTransStatusCode) ? '' : this.state.defaultValueObj.specTransStatusCode
                                            })(
                                                <Radio.Group onChange={this.handleStatusChange}>
                                                    {Util.isEmpty(this.state.specTransStatus) ? null : (
                                                        this.state.specTransStatus.map((item, index) => {
                                                            return (
                                                                <Radio.Button value={item.code} key={item.id}
                                                                >{user.language == 'CN' ? item.descripts : item.code}</Radio.Button>
                                                            )
                                                        })
                                                    )
                                                    }
                                                </Radio.Group>
                                            )
                                        }
                                    </Form.Item>
                                    <Row >
                                        <Col span={10}>
                                            <Form.Item {...selectUserLayout} label={languageObj && languageObj.SpecCollectSheetListTRANSFEROFPERSONS.descripts + ":"}
                                            >
                                                {
                                                    getFieldDecorator('specHandoverUserID', {
                                                        initialValue: undefined
                                                    })(
                                                        <Select
                                                            allowClear
                                                            showSearch
                                                            optionFilterProp='role'
                                                            onChange={this.handoverUserChange}
                                                        >
                                                            {
                                                                this.state.locNurUser.map(data => (
                                                                    <Select.Option
                                                                        role={data.code + '^' + data.descripts + '^' + data.descriptsSPCode}
                                                                        key={data.id}
                                                                    >
                                                                        {data.descripts}
                                                                    </Select.Option>
                                                                ))
                                                            }
                                                        </Select>
                                                    )
                                                }
                                            </Form.Item>
                                        </Col>
                                        <Col span={12}>
                                            <Form.Item {...selectUserLayout} label={languageObj && languageObj.SpecCollectSheetListCouriers.descripts + ":"}
                                            >
                                                {
                                                    getFieldDecorator('specReceiveUserID', {
                                                        initialValue: undefined
                                                    })(
                                                        <Select
                                                            allowClear
                                                            showSearch
                                                            optionFilterProp='role'
                                                            onChange={this.receiveUserChange}
                                                        >
                                                            {
                                                                this.state.hospUser.map(data => (
                                                                    <Select.Option
                                                                        role={data.code + '^' + data.descripts + '^' + data.descriptsSPCode}
                                                                        key={data.id}
                                                                    >
                                                                        {data.descripts}
                                                                    </Select.Option>
                                                                ))
                                                            }
                                                        </Select>
                                                    )
                                                }
                                            </Form.Item>
                                        </Col>
                                    </Row>

                                    <div style={{ display: 'flex', marginLeft: '130px', marginTop: '8px' }}>
                                        <Button type="primary" style={{ marginRight: '0px' }}
                                            onClick={this.handleQuery}>{languageObj && languageObj.SpecCollectSheetListQuery.descripts}</Button>
                                        <Button type="primary" disabled={this.state.transFlag} style={{ marginLeft: '7px', marginRight: '0px' }}
                                            onClick={this.sheetHandover}>{languageObj && languageObj.SpecCollectSheetListHandover.descripts}</Button>
                                        <Button type="primary" disabled={this.state.updateFlag} style={{ marginLeft: '7px' }}
                                            onClick={this.sheetDetailEdit}>{languageObj && languageObj.SpecCollectSheetListUpdate.descripts}</Button>
                                        <Button type="primary" style={{ marginLeft: '7px' }} onClick={this.AddSpecTrans}>{languageObj && languageObj.SpecCollectSheetListAddadocument.descripts}</Button>
                                    </div>
                                </Form>
                                {/* <Row style={{ marginBottom: '18px' }} className="button">
                                    <Col span={12} offset={12}> */}
                                {/* </Col>
                                </Row> */}
                            </Row>
                            <div className='spec-collect-table'>
                                <ColumnAuthoritysModel
                                    clientWidth='800px'
                                    compontName={this.state.compontName}
                                    configType="C"
                                    visible={this.state.visible}
                                    onRef={this.onColumnRef}
                                    reloadData={this.loadColumn}
                                />
                                <Table
                                    style={{ height: `${tableHeight}px` }}
                                    columns={this.state.columns}
                                    dataSource={this.state.tableData}
                                    bordered
                                    onRow={(record) => this.onClickRowPublic(record)}
                                    rowClassName={this.setRowClassNamePublic}
                                    pagination={false}
                                    scroll={{ x: 1000, y: store.getState().tableHeight.y - 105 }}
                                    //单击事件 
                                    onHeaderRow={column => {
                                        return {
                                            onDoubleClick: () => {
                                                this.setState({
                                                    compontName: "SpecCollectSheetList",
                                                }, () => {
                                                    this.columnRef.onOpenModel();
                                                })

                                            }
                                        };
                                    }
                                    }

                                />
                                <CommonPagination
                                    size='small'
                                    current={this.state.page}
                                    total={this.state.total}
                                    search='search'
                                    onShowSizeChange={this.onShowSizeChange.bind(this)}
                                    complete={true}
                                    dataSource={this.state.tableData}
                                    onChange={this.onChange.bind(this)}
                                    scroll={{ y: store.getState().tableHeight.y + 'px' }}
                                />
                                {/* <Pagination
                                    showTotal={() => this.showTotal(this.state.total)}
                                    size="small"
                                    showQuickJumper
                                    showSizeChanger
                                    defaultCurrent={1}
                                    defaultPageSize={10}
                                    current={this.state.page}
                                    total={this.state.total}
                                    onChange={this.onChange}
                                    onShowSizeChange={this.onShowSizeChange}
                                    style={{ textAlign: "right", marginTop: '38px' }}
                                /> */}
                            </div>
                        </Card>
                    </div>
                    <div style={{ height: '100%', float: 'right', width: '65%' }}>
                        <Card title={languageObj && languageObj.SpecCollectSheetListtitle.descripts} style={{ height: '100%' }} bodyStyle={{ height: 'calc( 100% - 30px)', padding: '10px' }}>
                            <SpecCollectModal specTransSheetID={this.state.specTransSheetID} specTransSheet={this.state.specTransSheet}
                                onRef={this.onRef} newSpecFlag={this.state.newSpecFlag}
                                handleQuery={this.fatherQuery} 
                                specTransStatusCodePost={this.state.specTransStatusCodePost} />
                        </Card>
                    </div>

                    <Modal
                        title="标本移交"
                        style={{ width: '350px' }}
                        visible={this.state.handoverVisible}
                        maskClosable={false}
                        onOk={this.handleOk}
                        onCancel={this.handleCancel}
                        width='350px'
                        cancelText='取消'
                        okText='确认'
                    >
                        <Row>
                            {languageObj && languageObj.SpecCollectSheetListCouriers.descripts + ":"}
                            <Select
                                allowClear
                                showSearch
                                optionFilterProp='role'
                                value={this.state.handoverUserModal}
                                onChange={this.handoverUserModal}
                                style={{ width: '200px' }}
                            >
                                {
                                    this.state.locNurUser.map(data => (
                                        <Select.Option
                                            role={data.code + '^' + data.descripts + '^' + data.descriptsSPCode}
                                            key={data.id}
                                        >
                                            {data.descripts}
                                        </Select.Option>
                                    ))
                                }
                            </Select>
                        </Row>
                        <Row>
                            {languageObj && languageObj.SpecCollectSheetListTRANSFEROFPERSONS.descripts + ":"}<Select
                                allowClear
                                showSearch
                                optionFilterProp='role'
                                value={this.state.receiveUserModal}
                                onChange={this.receiveUserModal}
                                style={{ width: '200px' }}
                            >
                                {
                                    this.state.hospUser.map(data => (
                                        <Select.Option
                                            role={data.code + '^' + data.descripts + '^' + data.descriptsSPCode}
                                            key={data.id}
                                        >
                                            {data.descripts}
                                        </Select.Option>
                                    ))
                                }
                            </Select>
                        </Row>
                    </Modal>
                </div>
            )
        }
    }
)
export default SpecCollect;