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

let userData = window.sessionStorage.userData ? JSON.parse(window.sessionStorage.userData) : {};
let user;
export default class SpecCollectModal extends Component {
    constructor(props) {
        super(props);
        user = window.sessionStorage.userData ? JSON.parse(window.sessionStorage.userData) : {};
        this.state = {
            total: 0,
            page: 1,
            pageSize: 10,
            columns: [],//列
            tableData: [], //
            sortColumn: 'Date',
            tableType: 'C',
            specimenAry: [],
            specimenID: '',
            cardTypeList: [],
            specTransSheetID: '',
            lisLocAry: [],
            patFindTermAry: [],  //患者查询条件下拉框
            lisLocID: '',    //检验科室ID
            newSpecFlag: true,   //建单、编辑标志
            addSpecFlag: true,   //添加按钮标志
            cancelSpecFlag: true,   //取消按钮标志
            patInfo: '',       //查询患者信息
            labNo: '',       //标本号
            specContainerNumber: '',     //容器编号
            addValue: '',
            defaultValueObj: {}, //默认值对象
        }
    }

    componentDidMount() {
        this.props.onRef(this);
        this.loadColumn("SpecTransDetailList");
        this.initSource();
        this.initDefaultValue();
        document.querySelector('.ant-table-body').style.height = store.getState().tableHeight.y + 'px';
    }

    componentWillUnmount() {
        // 组件销毁前将静止让setState修改state的状态
        this.setState = (state, callback) => { return; }
    }

    //查询列头数据
    // loadColumn = () => {
    //     let data = {
    //         params: [{
    //             compontName: "SpecTransDetailList",
    //             type: this.state.tableType,
    //         }]
    //     }
    //     $http.post('urlS', this, {
    //         code: "01040073",
    //         data: data,
    //         success: (res) => {
    //             if (+res.errorCode === 0) {
    //                 // let widthNumber = 0
    //                 let resData = res.result[this.state.tableType];
    //                 for (let index = 0; index < resData.length; index++) {
    //                     // widthNumber += parseInt(res.result[index].width);
    //                     let columnCode = resData[index].code;
    //                 }

    //                 let optionObj = {
    //                     title: '操作',
    //                     key: 16,
    //                     fixed: 'right',
    //                     align: "center",
    //                     width: 100,
    //                     render: (text, record) => {
    //                         return (
    //                             ((!Util.isEmpty(record)) && (record.statusCode == 'N')) ? (
    //                             <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"
    //                 }
    //                     // , () => {
    //                     //     this.handleQuery();
    //                     // }
    //                 )
    //             }
    //         }
    //     })
    // }

    //查询列头数据
    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)) && (this.props.specTransStatusCodePost == '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({
                        lisLocAry: res.result.lisLocAry,
                        specimenAry: res.result.specimenAry,
                        patFindTermAry: res.result.patFindTerm,
                    }
                    )
                }
            }
        })
    }

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

    initDefaultValue = () => {
        let data = {
            params: [{
                defaultAppObj: {
                    SpecTrans: ['patFindDefaultTerm'],
                }
            }]
        }
        $http.post('urlS', this, {
            code: "04110023",
            data: data,
            success: (res) => {
                if (+res.errorCode === 0) {
                    this.setState({
                        defaultValueObj: res.result
                    })
                }
            }
        })
    }

    handleQuery = (specTransSheetID) => {
        let data = {
            params: [{
                specTransSheetID: Util.isEmpty(this.props.specTransSheetID) ? specTransSheetID : this.props.specTransSheetID,
                recLocID: this.state.lisLocID,
                specID: this.state.specimenID,
                patCondition: this.state.patInfo,
            }],
            pagination: [{
                pageSize: this.state.pageSize,
                currentPage: this.state.page,
                sortColumn: this.state.sortColumn,
                sortOrder: 'desc'
            }]
        }
        // if (!Util.isEmpty(this.state.patInfo)) {
        //     if (Util.isEmpty(this.state.patFindTerm)) {
        //         data.params[0][this.state.defaultValueObj.patFindDefaultTerm] = this.state.patInfo
        //     } else {
        //         data.params[0][this.state.patFindTerm] = this.state.patInfo
        //     }
        // }
        $http.post('urlS', this, {
            code: "04130001",
            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,
                    })
                } else {
                    this.setState({
                        total: 0,
                        tableData: []
                    });
                }
            }
        })
    }

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

    handleOnRef = (ref) => {
        this.commonChild = 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);
    }
    // 选中行操作
    setRowClassNamePublic = (record, index) => {
        return record.specTransSheetID === this.state.specTransSheetID ? 'clickRowStyle' : '';
    }

    //删除转移明细记录
    handleDelete = (record) => {
        let specTransDetailIDs = []
        specTransDetailIDs.push(record.id)
        let data = {
            params: [{
                specTransSheetID: this.props.specTransSheetID,
                specTransDetailIDs: specTransDetailIDs
            }]
        }
        $http.post('urlADS', this, {
            code: '04130002',
            data: data,
            success: function (res) {
                if (res.errorCode === '0') {
                    message.success('删除成功');
                    this.handleQuery('')
                }
            }
        })
    }
    //检验科室切换
    handleLisLocChange = (e) => {
        this.setState({ lisLocID: e.target.value }
            , () => {
                this.handleQuery();
            })
    }
    //标本类型下拉框
    specimenChange = (value) => {
        this.setState({ specimenID: value }
            , () => {
                this.handleQuery();
            }
        )
    }
    //患者信息回车
    patNoDown = (e) => {
        this.setState({ patInfo: e.target.value }
            , () => { this.handleQuery(); })
    }
    //容器编号回车
    specContainerNumberDown = (e) => {
        this.setState({
            addSpecFlag: false,
            specContainerNumber: e.target.value,
        })
    }
    //标本号回车
    labNoDown = (e) => {
        this.setState({
            addSpecFlag: false,
            labNo: e.target.value,
        }
            , () => {
                this.saveTransDetail();
            })
    }
    //保存标本运送明细
    saveTransDetail = () => {
        let data = {
            params: [{
                specTransSheetID: this.props.specTransSheetID,
                updateUserID: userData.userID,
                sheetStatusCode: 'New',
                specLabNo: this.state.labNo,
                userID: userData.userID,
                status: 'N',
            }]
        }
        let code = '04130004'
        if (this.props.specTransSheetID !== "") {
            let specTransDetails = []
            let specTransDetailsObj = {}
            specTransDetailsObj.specLabNo = this.state.labNo
            specTransDetails.push(specTransDetailsObj);
            data.params[0].specTransDetails = specTransDetails
        } else {
            data.params[0].specContainerNumber = Util.isEmpty(this.props.specTransSheet) ? this.state.specContainerNumber : this.props.specTransSheet.specContainerNumber
            data.params[0].specLocID = userData.locID
            code = '04130020'
        }
        $http.post('urlADS', this, {
            code: code,
            data: data,
            success: (res) => {
                if (+res.errorCode === 0) {
                    message.success('保存成功');
                    let specTransSheetID
                    if (this.props.specTransSheetID == '') {
                        specTransSheetID = res.result.specTransSheetID
                        var { handleQuery } = this.props;
                        handleQuery && handleQuery('code')
                    }
                    this.setState({
                        addValue: ''
                    }
                        , () => {
                            this.handleQuery(specTransSheetID);
                        })
                }
            }
        })
    }
    //添加标本运送明细[判断是否创建新的标本运送单
    addSpecTrans = () => {
        this.saveTransDetail();
    }

    //患者查询条件
    patFindTermChange = (value) => {
        this.setState({
            patFindTerm: value
        })
    }

    //修改明细数据
    editDetailData = () => {
        this.handleQuery();
        //标本号获取焦点
        this.refs.labNoInput.focus();
    }

    //清空数据
    clearData = () => {
        this.setState({
            specContainerNumber: '',
            addValue: '',
            lisLocID: '',
            specimenID: '',
            patFindTerm: '',
            patInfo: '',
        }, () => {
            this.handleQuery();
            //容器编号获取焦点
            this.refs.containerNumber.focus();
        })
    }
    render() {

        let editText = this.props.specTransSheetID !== "" ? '编辑单据' : '新增单据';
        let iconType = this.props.specTransSheetID !== "" ? 'edit' : 'diff';

        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 className='specDetail-Gard'>
                {(this.props.newSpecFlag) ? (
                    <div>
                        <Row>
                            <span style={{ fontSize: '16px', margin: '0px', color: '#278DFD' }}>
                                <Icon type={iconType} />{editText === '新增单据' ? languageObj && languageObj.SpecTransDetailListAddadocument.descripts : languageObj && languageObj.SpecTransDetailListEditingdocuments.descripts}
                            </span>
                        </Row>
                        <Row>
                            <Col span={18} style={{ marginBottom: '6px' }}>
                                <Input placeholder={languageObj && languageObj.SpecTransDetailListPlaceholder != null ? languageObj.SpecTransDetailListPlaceholder.descripts : ""}
                                    addonBefore={languageObj && languageObj.SpecTransDetailListContainernumber != null ? languageObj.SpecTransDetailListContainernumber.descripts + ":" : ""}
                                    ref='containerNumber'
                                    allowClear={Util.isEmpty(this.props.specTransSheet) ? true : false}
                                    disabled={Util.isEmpty(this.props.specTransSheet) ? false : true}
                                    value={Util.isEmpty(this.props.specTransSheet) ? this.state.specContainerNumber : this.props.specTransSheet.specContainerNumber}
                                    onChange={(e) => { this.setState({ specContainerNumber: e.target.value }) }}
                                    style={{ width: '400px', marginTop: '2px' }}
                                    onPressEnter={this.specContainerNumberDown} />
                                <Input
                                    addonBefore={languageObj && languageObj.SpecTransDetailListSpecimennumber ? languageObj.SpecTransDetailListSpecimennumber.descripts + ":" : ""}
                                    ref='labNoInput'
                                    placeholder={languageObj && languageObj.SpecTransDetailListPlaceholderb ? languageObj.SpecTransDetailListPlaceholderb.descripts : ""}
                                    style={{ width: '400px', marginTop: '2px', marginLeft: '40px' }}
                                    allowClear
                                    value={this.state.addValue}
                                    onChange={(e) => { this.setState({ addValue: e.target.value }) }}
                                    onPressEnter={this.labNoDown} />
                            </Col>
                            <Col span={6}>
                                <Button type="primary" disabled={this.state.addSpecFlag} style={{ marginRight: '30px' }} onClick={this.addSpecTrans}>{languageObj && languageObj.SpecTransDetailListAddto.descripts}</Button>
                                {/* <Button type="primary" disabled={this.state.cancelSpecFlag} style={{ marginRight: '0px' }}>取消</Button> */}
                            </Col>
                        </Row>
                    </div>
                ) : (
                        <div>
                            <Row style={{ height: '40px' }}>
                                接收科室：
                                <Radio.Group onChange={this.handleLisLocChange}
                                    style={{ marginTop: '2px' }}
                                >
                                    <Radio.Button value="">全部科室</Radio.Button>
                                    {Util.isEmpty(this.state.lisLocAry) ? null : (
                                        this.state.lisLocAry.map((item, index) => {
                                            return (
                                                <Radio.Button value={item.id} key={item.id}>{item.descripts}</Radio.Button>
                                            )
                                        })
                                    )
                                    }
                                </Radio.Group>
                            </Row>
                            <Row style={{ height: '40px' }}>
                                <Col span={6}>
                                    类型：
                                    <Select
                                        allowClear
                                        showSearch
                                        optionFilterProp='role'
                                        style={{ width: '200px', marginTop: '2px' }}
                                        onChange={this.specimenChange}
                                    >
                                        {this.state.specimenAry.map((item, index) => (
                                            <Select.Option
                                                role={item.code + '^' + item.descripts + '^' + item.descriptsSPCode}
                                                key={item.id}>
                                                {item.descripts}
                                            </Select.Option>
                                        ))
                                        }
                                    </Select>
                                </Col>
                                <Col span={12}>
                                    患者：
                                    {/* <Select
                                        showSearch
                                        optionFilterProp='role'
                                        style={{ width: '100px', marginTop: '2px' }}
                                        defaultValue={Util.isEmpty(this.state.defaultValueObj) ? '' : this.state.defaultValueObj.patFindDefaultTerm}
                                        onChange={this.patFindTermChange}
                                    >
                                        {this.state.patFindTermAry.map((item, index) => (
                                            <Select.Option
                                                role={item.code + '^' + item.descripts + '^' + item.descriptsSPCode}
                                                value={item.code}
                                                key={item.id}>
                                                {item.descripts}
                                            </Select.Option>
                                        ))
                                        }
                                    </Select> */}
                                    <Input placeholder='患者ID/姓名/床号回车查询'
                                        allowClear
                                        style={{ width: '200px', marginTop: '2px' }}
                                        value={this.state.patInfo}
                                        onChange={(e) => { this.setState({ patInfo: e.target.value }) }}
                                        onPressEnter={this.patNoDown}
                                    ></Input>
                                </Col>
                            </Row>
                        </div>
                    )

                }
                <Row style={{ height: 'calc(100% - 80px)' }}>
                    <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: 'calc(100% - 80px)' }}
                            columns={this.state.columns}
                            dataSource={this.state.tableData}
                            bordered
                            // onRow={(record) => this.onClickRowPublic(record)}
                            rowClassName={this.setRowClassNamePublic}
                            pagination={false}
                            //单击事件 
                            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: '13px' }}
                        /> */}
                    </div>
                </Row>
            </div>
        )
    }
}