//新增传染病字典维护窗口
import React from 'react';
import { Modal, Button, Transfer, Table, Input, Select, Row, Col, message } from 'antd';
// import difference from 'lodash/difference';
import { $http } from '../../../containers/config/https';
// Customize Table Transfer
const { Option } = Select;

const TableTransfer = ({ leftColumns, rightColumns, ...restProps }) => (
    <Transfer {...restProps} showSelectAll={false}>
        {({
            direction,
            filteredItems,
            onItemSelectAll,
            onItemSelect,
            selectedKeys: listSelectedKeys,
            disabled: listDisabled,
        }) => {
            const columns = direction === 'left' ? leftColumns : rightColumns;

            const rowSelection = {
                getCheckboxProps: item => ({ disabled: listDisabled || item.disabled }),
                onSelectAll(selected, selectedRows) {
                    // const treeSelectedKeys = selectedRows
                    //     .filter(item => !item.disabled)
                    //     .map(({ key }) => key);
                    // const diffKeys = selected
                    //     ? difference(treeSelectedKeys, listSelectedKeys)
                    //     : difference(listSelectedKeys, treeSelectedKeys);
                    // onItemSelectAll(diffKeys, selected);
                    onItemSelectAll(selected, selectedRows);
                },
                onSelect({ key }, selected) {
                    onItemSelect(key, selected);
                },
                selectedRowKeys: listSelectedKeys,
            };

            return (
                <Table
                    scroll={{ y: 240 }}
                    rowSelection={rowSelection}
                    columns={columns}
                    dataSource={filteredItems}
                    pagination={false}
                    size="small"
                    style={{ width: direction == 'left' ? '550px' : '350px', pointerEvents: listDisabled ? 'none' : null, height: '300px' }}
                    onRow={({ key, disabled: itemDisabled }) => ({
                        onClick: () => {
                            if (itemDisabled || listDisabled) return;
                            onItemSelect(key, !listSelectedKeys.includes(key));
                        },
                    })}
                />
            );
        }}
    </Transfer>
);

let user;
class AddInfectiousDictionary extends React.Component {
    constructor(props) {
        user = window.sessionStorage.userData ? JSON.parse(window.sessionStorage.userData) : {};
        super(props);
        this.state = {
            visible: false,
            disabled: false,
            showSearch: true,
            ENObj: {},
            CNObj: {},
            compontName: "",
            leftFilter: "",
            mockData: [],
            filteredItems: [], // 所有数据
            savedItems: [], //已保存数据
            unSavedItems: [],// 未保存数据
            diseaseOnsetTypeArrData: [],
            DiseaseCategoryArrData: [],
            DiseaseArrData: [],
            leftTableColumns: [],
            rightTableColumns: [],
            diseaseContrastArr: [],
            levelID: "",
            categoryID: "",
            startCode: "",
            endCode: "",
            codeStr: "",
            diseaseID: "",
            targetKeys: [],
            targetIDs: [],

        };
        this.leftTableColumns = [
            {
                dataIndex: 'code',
                width: '120',
                title: 'ICD编码',
            },
            {
                dataIndex: 'descripts',
                width: '300',
                title: 'ICD名称',
            },
        ],
            this.rightTableColumns = [
                {
                    dataIndex: 'descripts',
                    title: 'ICD名称',
                    width: '200',
                },
            ];
    }
    //渲染完成时调用
    componentDidMount() {
        this.props.onRef(this);
        this.getOption();
        this.getOptionType();
        this.getOptionTypeName();
        this.loadColumn("Infectiousdiseasecomponent");
    }

    // 打开弹窗
    handleShowModal = () => {
        this.setState({
            visible: true,
            diseaseID: this.props.diseaseID
        }, () => this.loadDisease(this.state.diseaseID));
    }
    afterClose = () => {
        this.setState({
            filteredItems: [],
            savedItems: [],
            unSavedItems: [],
        }, () => {
            this.props.handleQuery()
        });
    }

    // 关闭弹窗
    handleCancel = () => {
        this.setState({
            visible: false,
            filteredItems: [],
            savedItems: [],
            unSavedItems: [],
        });

    }
    //查询列头数据
    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,
                        })
                    }

                }
            }
        })
    }
    onChange = (e) => {
        this.setSate({

            leftFilter: e.target.value
        });
    }
    // 获取下拉数据源
    getOption = () => {
        let data = {
            params: [{

            }]
        };
        $http.post('urlDeault', this, {
            code: "04190002",
            data: data,
            success: function (res) {
                if (+res.errorCode === 0) {
                    this.setState({
                        diseaseOnsetTypeArrData: res.result.diseaseOnsetTypeArr,
                    })
                }
            },
            error: function (error) {
                message.error('失败：' + error);
            }
        });
    }

    // 获取传染病类别下拉数据
    getOptionType = (levelID) => {
        let data = {
            params: [{
                levelID: levelID
            }]
        };
        $http.post('urlDeault', this, {
            code: "04190004",
            data: data,
            success: function (res) {
                if (+res.errorCode === 0) {
                    this.setState({
                        DiseaseCategoryArrData: res.result.DiseaseCategoryArr,
                    })
                }
            },
            error: function (error) {
                message.error('失败：' + error);
            }
        });
    }

    // 获取传染病类别下拉数据
    getOptionTypeName = (categoryID) => {
        let data = {
            params: [{
                categoryID: categoryID
            }]
        };
        $http.post('urlDeault', this, {
            code: "04190005",
            data: data,
            success: function (res) {
                if (+res.errorCode === 0) {
                    this.setState({
                        DiseaseArrData: res.result.DiseaseArr,
                    })
                }
            },
            error: function (error) {
                message.error('失败：' + error);
            }
        });
    }



    handleSelectCondition(flag, e) {
        if (flag == "levelID") {
            this.state.DiseaseCategoryArrData = []
            this.getOptionType(e)
        }
        if (flag == "categoryID") {
            this.state.DiseaseArrData = []
            this.getOptionTypeName(e)
        }
        if (flag == "diseaseID") {
            this.loadDisease(e)
        }
        this.setState({
            [flag]: e
        });
    }

    showModal = () => {
        this.setState({
            visible: true,
        });
    };


    handleOk = e => {

        this.setState({
            visible: false,
        });
    };

    handleCancel = e => {

        this.setState({
            visible: false,
        });
    };
    //移动穿梭框数据 nextTargetKeys 右侧数据  direction方向  moveKeys 从右侧移出
    tableOnChange = (nextTargetKeys, direction, moveKeys) => {
        this.setState({
            targetKeys: nextTargetKeys,
        })
        if (direction == "left") {
            this.deleteDisease(moveKeys)
        }


    };

    triggerDisable = disabled => {
        this.setState({ disabled });
    };

    triggerShowSearch = showSearch => {
        this.setState({ showSearch });
    };

    //查询
    loadDispatch = () => {
        let data = {
            params: [{
                startCode: this.state.startCode,
                endCode: this.state.endCode,
                codeStr: this.state.codeStr,
                diseaseID: this.state.diseaseID,
            }]
        }

        if (this.state.codeStr === "") {
            message.warning("请输入ICD名称");
            return;
        }

        $http.post('urlDeault', this, {
            code: "04190006",
            data: data,
            success: (res) => {
                if (res.errorCode == "0") {
                    let savedItems = this.state.savedItems;
                    let filterItem = res.result.diseaseOnsetTypeArr.concat(savedItems);
                    this.setState({
                        unSavedItems: res.result.diseaseOnsetTypeArr,
                        filteredItems: filterItem,
                    })


                }
            }
        })
    }

    //查询
    loadDisease = (ID) => {
        let data = {
            params: [{
                diseaseID: ID,
            }]
        }

        if (ID === "") {
            return;
        }

        // if (typeof (ID) == "undefined") {
        //     message.warning("请选择疾病");

        //     this.setState({
        //         filteredItems: [],
        //     },() =>this.loadDispatch());

        //     return;
        // }
        $http.post('urlDeault', this, {
            code: "04190007",
            data: data,
            success: (res) => {
                if (res.errorCode == "0") {
                    let targetKeys = [];
                    let targetIDs = [];
                    for (var i = 0; i < res.result.diseaseContrastArr.length; i++) {
                        let obj = res.result.diseaseContrastArr[i];
                        targetKeys.push(obj.diagICDID + "");
                    }
                    this.setState({
                        filteredItems: res.result.diseaseContrastArr,
                        savedItems: res.result.diseaseContrastArr,
                        targetKeys: targetKeys,
                        targetIDs: targetIDs,
                    })
                }
            }
        })
    }

    //保存
    saveDisease = () => {
        let data = {
            params: [{
                diseaseID: this.state.diseaseID,
                contrastID: this.state.targetKeys,
            }]
        };
        $http.post('urlS', this, {
            code: '04190008',
            data: data,
            success: (res) => {
                if (res.errorCode == "0") {
                    message.success('成功');
                    this.loadDisease(this.state.diseaseID);
                    this.handleCancel();
                }
            },
            error: function (error) {
                message.error('失败：' + error);
            }

        });
    }

    //删除
    deleteDisease = (ID) => {
        let data = {
            params: [{
                diseaseID: this.state.diseaseID,
                ICDID: ID,
            }]
        };
        $http.post('urlS', this, {
            code: '04190009',
            data: data,
            success: (res) => {
                if (res.errorCode == "0") {
                    message.success('成功');
                }
            },
            error: function (error) {
                message.error('失败：' + error);
            }

        }, () => {
            this.loadDisease(diseaseID);
        });
    }

    changeInput = (e) => {
        this.setState({
            data: e.target.value

        }, () => {
            this.loadDispatch()
        })
    }
    inputOnChange = (code, e) => {

        this.setState({
            [code]: e.target.value
        }
        )
    }

    render() {
        const { filteredItems, disabled, showSearch } = this.state;

        let diseaseOnsetTypeArr = [];
        this.state.diseaseOnsetTypeArrData.map((item) => {
            diseaseOnsetTypeArr.push(
                <Option key={item.id} value={item.id} >
                    {item.descripts}
                </Option>
            )
        })

        let DiseaseArr = [];
        this.state.DiseaseArrData.map((item) => {
            DiseaseArr.push(
                <Option key={item.id} value={item.id} >
                    {item.descripts}
                </Option>
            )
        })

        let DiseaseCategoryArr = [];
        this.state.DiseaseCategoryArrData.map((item) => {
            DiseaseCategoryArr.push(
                <Option key={item.id} value={item.id} >
                    {item.descripts}
                </Option>
            )
        })

        let mockData = [];
        this.state.filteredItems.map((item) => {
            mockData.push({
                key: item.diagICDID,
                code: item.ICDCode,
                descripts: item.descripts,
            });
        })

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

        return (
            <div>
                <Modal
                    destroyOnClose={true}
                    title="新增"
                    visible={this.state.visible}
                    afterClose={this.afterClose}
                    width='1200px'
                    okText="保存"
                    onOk={this.saveDisease}
                    onCancel={this.handleCancel}
                    style={{
                        overflow: 'hidden',
                        paddingBottom: '108px',
                        height: '800px',
                    }}>
                    <Row style={{ minHeight: '80px', padding: '0 24px 24px 24px', width: '1000px' }}>
                        <Col span={24}>
                            <span>*</span>
                            {languageObj.InfectiousdiseasecomponentInfectiousdiseasegrade != null ? languageObj.InfectiousdiseasecomponentInfectiousdiseasegrade.descripts : ""}:<Select value={this.state.levelID}
                                allowClear={true}
                                showSearch
                                optionFilterProp="children"
                                onChange={this.handleSelectCondition.bind(this, "levelID")}
                                style={{ width: '160px', margin: '0 30px 0 0' }}>
                                <Option key="" value="" >{languageObj.Infectiousdiseasecomponentwhole != null ? languageObj.Infectiousdiseasecomponentwhole.descripts : ""}</Option>
                                {diseaseOnsetTypeArr}
                            </Select>
                            <span>*</span>
                            {languageObj.InfectiousdiseasecomponentCategoryofinfectiousdiseases != null ? languageObj.InfectiousdiseasecomponentCategoryofinfectiousdiseases.descripts : ""}:<Select value={this.state.categoryID}
                                allowClear={true}
                                showSearch
                                optionFilterProp="children"
                                onChange={this.handleSelectCondition.bind(this, "categoryID")}
                                style={{ width: '160px', margin: '0 20px 0 0' }}>
                                <Option key="" value="" >{languageObj.Infectiousdiseasecomponentwhole != null ? languageObj.Infectiousdiseasecomponentwhole.descripts : ""}</Option>
                                {DiseaseCategoryArr}
                            </Select>
                            <span>*</span>
                            {languageObj.InfectiousdiseasecomponentNameofinfectiousdisease != null ? languageObj.InfectiousdiseasecomponentNameofinfectiousdisease.descripts : ""}:<Select value={this.state.diseaseID}
                                allowClear={true}
                                showSearch
                                optionFilterProp="children"
                                // defaultValue={this.state.savedItems.descripts}
                                // onChange={(val,opt) => this.setState({ diseaseID: val }) }
                                onChange={this.handleSelectCondition.bind(this, "diseaseID")}
                                style={{ width: '160px', margin: '0 80px 0 0' }}>
                                {DiseaseArr}
                            </Select>
                        </Col>
                    </Row>
                    <TableTransfer
                        titles={[(
                            <div width="500px" style={{ margin: '-5px 0 0 0' }}>{languageObj.InfectiousdiseasecomponentIDCnumber != null ? languageObj.InfectiousdiseasecomponentIDCnumber.descripts : ""}：
                                <Input type="text" size="small" placeholder="A00.000" style={{ width: "80px" }} onChange={this.inputOnChange.bind(this, 'startCode')} onPressEnter={this.loadDispatch} />~
                                <Input type="text" size="small" placeholder="A00.001" style={{ width: "80px" }} onChange={this.inputOnChange.bind(this, 'endCode')} onPressEnter={this.loadDispatch} />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                                <Input type="text" size="small" placeholder="输入ICD名称按回车查询" style={{ width: "180px" }} onChange={this.inputOnChange.bind(this, 'codeStr')} onPressEnter={this.loadDispatch} />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                                <Button type="primary" onClick={this.loadDispatch}>{languageObj.InfectiousdiseasecomponentQuery != null ? languageObj.InfectiousdiseasecomponentQuery.descripts : ""}</Button></div>), '诊断记录']}
                        dataSource={mockData}
                        targetKeys={this.state.targetKeys}
                        disabled={disabled}
                        // operations={[(onClick = { this.}), "2"]}
                        showSearch={false}
                        onChange={this.tableOnChange}
                        filterOption={(inputValue, item) =>
                            item.title.indexOf(inputValue) !== -1 || item.tag.indexOf(inputValue) !== -1
                        }
                        leftColumns={this.leftTableColumns}
                        rightColumns={this.rightTableColumns}
                    />
                </Modal>
            </div>
        );
    }
}
export default AddInfectiousDictionary;