// 标本接收
import React, { Component } from 'react';
import { Row, Col, Table, Button, Select, message, Input } from 'antd';
import ColumnAuthoritysModel from '../../columnAuthority/ColumnAuthoritysModel'
import { $http } from '../../../containers/config/https';
// 用户数据
const userData = sessionStorage.userData ? JSON.parse(sessionStorage.userData) : {};
let user;
export default class SpecReceive extends Component {
    constructor(props) {
        super(props);
        user = window.sessionStorage.userData ? JSON.parse(window.sessionStorage.userData) : {};
        this.state = {
            inputNo: '',
            tableData: [],              // 表格全部数据
            selectedData: [],           // 选中数据
            reasonData: [],             // 拒绝原因
            clickFlag: false,
            selectedIDs: [],            // 选中的table数据ID
            cardTypeList: [],
            tableType: 'C',
            columns: [],
            compontName: "",
        }
        // this.columns = [{
        //     key: 1,
        //     title: '序号',
        //     dataIndex: 'seqNo',
        //     align: "center",
        //     width: '3%'
        // }, {
        //     key: 2,
        //     title: '标本号',
        //     dataIndex: 'specNo',
        //     align: "center",
        //     width: '10%',
        // }, {
        //     key: 3,
        //     title: '容器号',
        //     dataIndex: 'containerNo',
        //     align: "center", 
        //     width: '6%',
        // }, {
        //     key: 4,
        //     title: '拒绝原因',
        //     dataIndex: 'reason',
        //     align: "center",
        //     width: '10%',
        //     render: (text, record) => {
        //         return (
        //             <Select
        //                 value={record.reason}
        //                 allowClear
        //                 style={{ width: "100%", textAlign: "center" }}
        //                 onChange={(val) => this.handleFieldChange(val, record.seqNo)}
        //                 showSearch
        //                 optionFilterProp='role'
        //             >
        //                 {this.state.reasonData.map(data => (
        //                     <Select.Option
        //                         role={datacode. + '^' + data.descripts + '^' + data.descriptsSPCode}
        //                         key={data.id}
        //                     >
        //                         {data.descripts}
        //                     </Select.Option>))}
        //             </Select>
        //         )
        //     }
        // }, {
        //     key: 5,
        //     title: '类别',
        //     dataIndex: 'specDesc',
        //     align: "center",
        //     width: '4%'
        // }, {
        //     key: 6,
        //     title: '接收科室',
        //     dataIndex: 'recLocDesc',
        //     align: "center",
        //     width: '8%',
        // }, {
        //     key: 7,
        //     title: '录入时间',
        //     dataIndex: 'ordDateTime',
        //     align: "center",
        //     width: '10%',
        // }, {
        //     key: 8,
        //     title: '患者ID',
        //     dataIndex: 'patNo',
        //     align: "center",
        //     width: '8%'
        // }, {
        //     key: 9,
        //     title: '姓名',
        //     dataIndex: 'patName',
        //     align: "center",
        //     width: '6%',
        // }, {
        //     key: 10,
        //     title: '床号',
        //     dataIndex: 'bedCode',
        //     align: "center",
        //     width: '5%',
        // }, {
        //     key: 11,
        //     title: '医嘱信息',
        //     dataIndex: 'medDesc',
        //     align: "center",
        //     width: '10%'
        // }, {
        //     key: 12,
        //     title: '开医嘱时间',
        //     dataIndex: 'ordDateTime',
        //     align: "center",
        //     width: '10%',
        // }, {
        //     key: 13,
        //     title: '状态',
        //     dataIndex: 'status',
        //     align: "center",
        //     width: '5%',
        // }, {
        //     key: 14,
        //     title: '操作',
        //     dataIndex: 'operate',
        //     align: "center",
        //     render: (text, record) => {
        //         return (
        //             <span>
        //                 <a onClick={(e) => {
        //                     let { tableData } = this.state;
        //                     tableData.splice(tableData.findIndex(item => item.id === record.id), 1);
        //                     // 加序号
        //                     for (let i = 0; i < tableData.length; i++) {
        //                         tableData[i].seqNo = i + 1;
        //                     }
        //                     this.setState({
        //                         tableData,
        //                         selectedIDs: [],
        //                         selectedData: []
        //                     })
        //                 }
        //                 }>删除</a>
        //             </span>
        //         )
        //     }
        // }]
    }
    componentDidMount() {
        this.getRejectReasonData();
        this.loadColumn("SpecReceive")
        // this.Input.focus()
    }

    //查询列头数据
    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
                        }
                    }
                    for (let i = 0; i < column.length; i++) {
                        if (column[i].code == 'reason') {
                            column[i].render = (text, record) => {
                                return (
                                    <Select
                                        value={record.reason}
                                        allowClear
                                        style={{ width: "100%", textAlign: "center" }}
                                        onChange={(val) => this.handleFieldChange(val, record.seqNo)}
                                        showSearch
                                        optionFilterProp='role'
                                    >
                                        {this.state.reasonData.map(data => (
                                            <Select.Option
                                                role={data.code + '^' + data.descripts + '^' + data.descriptsSPCode}
                                                key={data.id}
                                            >
                                                {data.descripts}
                                            </Select.Option>))}
                                    </Select>
                                )
                            }
                        }
                        if (column[i].code == 'operate') {
                            column[i].render = (text, record) => {
                                return (
                                    <span>
                                        <a onClick={(e) => {
                                            let { tableData } = this.state;
                                            tableData.splice(tableData.findIndex(item => item.id === record.id), 1);
                                            // 加序号
                                            for (let i = 0; i < tableData.length; i++) {
                                                tableData[i].seqNo = i + 1;
                                            }
                                            this.setState({
                                                tableData,
                                                selectedIDs: [],
                                                selectedData: []
                                            })
                                        }
                                        }>删除</a>
                                    </span>
                                )
                            }
                        }
                    }
                    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];
                        this.setState({
                            columns: resData,
                            tableWidth: res.totalWidth
                        }
                            , () => {
                                //  this.handleQuery();
                            })
                    }

                }
            }
        })
    }

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

    //遍历拒绝原因方法
    reason = (text, record) => {
        return (
            <Select
                value={record.reason}
                allowClear
                style={{ width: "100%", textAlign: "center" }}
                onChange={(val) => this.handleFieldChange(val, record.seqNo)}
                showSearch
                optionFilterProp='role'
            >
                {this.state.reasonData.map(data => (
                    <Select.Option
                        role={datacode + '^' + data.descripts + '^' + data.descriptsSPCode}
                        key={data.id}
                    >
                        {data.descripts}
                    </Select.Option>))}
            </Select>
        )
    }

    //操作方法
    operate = (text, record) => {
        return (
            <span>
                <a onClick={(e) => {
                    let { tableData } = this.state;
                    tableData.splice(tableData.findIndex(item => item.id === record.id), 1);
                    // 加序号
                    for (let i = 0; i < tableData.length; i++) {
                        tableData[i].seqNo = i + 1;
                    }
                    this.setState({
                        tableData,
                        selectedIDs: [],
                        selectedData: []
                    })
                }
                }>删除</a>
            </span>
        )
    }


    // 获取拒绝原因下拉数据
    getRejectReasonData = () => {
        let data = {
            params: [{}]
        }
        $http.post('urlS', this, {
            code: '04130005',
            data: data,
            success: function (res) {
                if (+res.errorCode === 0) {
                    this.setState({ reasonData: res.result })
                }
            }
        })
    }
    // 变更拒绝原因
    handleFieldChange = (val, seqNo) => {
        let { tableData } = this.state;
        const index = seqNo - 1;
        tableData[index].reason = val
        this.setState({ tableData })
    }
    // 查询标本号对应医嘱信息
    addTableData = () => {
        let { tableData } = this.state;
        // console.log(tableData);
        let data = {
            "params": [{
                inputNo: this.state.inputNo
            }]
        };
        $http.post('urlDeault', this, {
            code: "04130003",
            data: data,
            success: function (res) {
                if (+res.errorCode === 0) {
                    tableData = [...tableData, ...res.result];
                    // 去重
                    let obj = {};
                    tableData = tableData.reduce((item, next) => {
                        obj[next.id] ? "" : obj[next.id] = true && item.push(next);
                        return item;
                    }, [])
                    // 加序号
                    for (let i = 0; i < tableData.length; i++) {
                        tableData[i].seqNo = i + 1;
                    }
                    this.setState({
                        tableData,
                        selectedIDs: [],
                        selectedData: [],
                        inputNo: ''
                    })
                }
            },
            error: function (error) {
                message.error('失败：' + error);
            }
        });
    }
    // 保存标本运送明细信息
    saveSpecTransDetails = (e, code) => {
        // console.log('==========',code);
        let { tableData, selectedData, selectedIDs } = this.state;
        let postArr = [];
        for (let i = 0; i < tableData.length; i++) {
            let obj = {};
            obj.specTransDetailID = tableData[i].id;
            if (code === "RE") {
                obj.rejectReasonID = tableData[i].reason
            }
            postArr.push(obj)
        }
        let selectedArr = [];
        for (let i = 0; i < selectedData.length; i++) {
            let obj = {};
            obj.specTransDetailID = selectedData[i].id;
            if (code === "RE") {
                obj.rejectReasonID = selectedData[i].reason
            }
            selectedArr.push(obj)
        }
        let data = {
            "params": [{
                status: code,
                userID: userData.userID,
                specTransDetails: selectedArr.length != 0 ? selectedArr : postArr
            }]
        };
        $http.post('urlDeault', this, {
            code: "04130004",
            data: data,
            success: function (res) {
                if (+res.errorCode === 0) {
                    if (selectedIDs.length != 0) {
                        for (let i = 0; i < selectedIDs.length; i++) {
                            tableData.splice(tableData.findIndex(item => item.id === selectedIDs[i]), 1);
                        }
                    } else {
                        tableData = []
                    }
                    this.setState({
                        tableData,
                        selectedIDs: [],
                        selectedData: []
                    }, () => {
                        if ((code === "CR") && (res.result.length > 0)) {
                            for (let i = 0; i < res.result.length; i++) {
                                tableData.push(res.result[i]);
                            }
                        }
                        // 加序号
                        for (let i = 0; i < tableData.length; i++) {
                            tableData[i].seqNo = i + 1;
                        }
                    })
                    this.setState({ tableData })
                }
            },
            error: function (error) {
                message.error('失败：' + error);
            }
        });
    }
    render() {

        const rowSelection = {
            selectedRowKeys: this.state.selectedIDs,
            columnWidth: '30px',
            fixed: true,
            onChange: (selectedRowKeys, selectedRows) => {
                this.setState({
                    selectedIDs: selectedRowKeys,
                    selectedData: selectedRows
                })
            }
        }


        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>

                <ColumnAuthoritysModel
                    clientWidth='800px'
                    compontName={this.state.compontName}
                    configType="C"
                    visible={this.state.visible}
                    onRef={this.onColumnRef}
                    reloadData={this.loadColumn}
                />

                <div style={{ padding: '20px 0 0' }}>
                    <Row>
                        <Col span={5} style={{ marginLeft: '20px' }}>
                            <Input
                                value={this.state.inputNo}
                                placeholder={languageObj && languageObj.SpecReceivePlaceholder != null ? languageObj.SpecReceivePlaceholder.descripts : ""}
                                allowClear
                                onChange={(e) => this.setState({ inputNo: e.target.value })}
                                onPressEnter={this.addTableData}
                                autoFocus
                            />
                        </Col>
                        <Col span={15}>
                            <Button type='primary' style={{ marginLeft: '10px' }} onClick={this.addTableData}>{languageObj && languageObj.SpecReceiveAdd.descripts}</Button>
                        </Col>
                        <Col span={2} style={{ width: 'auto' }}>
                            <Button type='primary' onClick={() => this.saveSpecTransDetails(this, 'R')}>{languageObj && languageObj.SpecReceiveCancel != null ? languageObj.SpecReceiveCancel.descripts : ""}</Button>
                        </Col>
                        <Col span={2} style={{ width: 'auto', marginLeft: '5px', marginRight: '5px' }}>
                            <Button type='primary' onClick={() => this.saveSpecTransDetails(this, 'CR')}>{languageObj && languageObj.SpecReceiveCancelreception != null ? languageObj.SpecReceiveCancelreception.descripts : ""}</Button>
                        </Col>
                        <Col span={2} style={{ width: 'auto' }}>
                            <Button type='primary' onClick={() => this.saveSpecTransDetails(this, 'RE')}>{languageObj && languageObj.SpecReceiveRefuse != null ? languageObj.SpecReceiveRefuse.descripts : ""}</Button>
                        </Col>
                    </Row>
                </div>
                <br />
                <div style={{ margin: '0 20px 0' }}>
                    <Table
                        columns={this.state.columns}
                        dataSource={this.state.tableData}
                        pagination={false}
                        bordered
                        rowKey={(row) => {
                            return row.id
                        }}
                        rowSelection={rowSelection}
                        //单击事件 
                        onHeaderRow={column => {
                            return {
                                onDoubleClick: () => {
                                    this.setState({
                                        compontName: "SpecReceive",
                                    }, () => {
                                        this.columnRef.onOpenModel();
                                    })

                                }
                            };
                        }
                        }
                    />
                </div>
            </div>
        )
    }
}