/*
 * Creator:     ML
 * CreatDate:   2020-01-26
 * descripts：  治疗工作站-服务项目
 * */
import React from 'react';
import { Form, Row, Col, Input, Select, Button, DatePicker, Popconfirm, Modal, Table, Icon, Pagination, message, Divider, Tooltip, Card } from 'antd';
import moment from 'moment';
import { $http } from 'containers/config/https';
import store from 'store';
import '../style/index.less';
import ColumnAuthoritysModel from 'pages/columnAuthority/ColumnAuthoritysModel';

const FormItem = Form.Item;
const Option = Select.Option;
const paddRightCol = {
    paddingRight: "0px"
}

const formItemLayoutTT = {
    labelCol: { span: 9 },
    wrapperCol: { span: 15 },
}
const formItemLayoutLocItem = {
    labelCol: { span: 6 },
    wrapperCol: { span: 18 },
}

const ServiceGroupItems = Form.create()(
    class ServiceGroupItems extends React.Component {
        constructor(props) {
            super(props)
            var userData = JSON.parse(sessionStorage.getItem('userData'))
            this.state = {
                userData: userData,
                baseParms: [],//下拉框数据
                total: 0,//表格总数据
                baseData: [],//查询数据
                values: {},//查询条件数据
                searchLoading: false,//查询请求
                rowIds: '',//表格行选中 页面数据
                headerHeight: "",
                page: 1,
                pageSize: 10,
                size: "small",
                sizeDoc: "small",
                search: "",
                docArr: [],
                pageSizeDoc: 10,
                pageDoc: 1,
                selectedData: []
            }
        }
        componentDidMount() {
            this.props.onItems(this)
            this.getMainTableColumnsItem()
            this.getSubData()
            this.getAuthorizationList(this.props.rowIds)
            this.getOtherLoc(this.props.rowIdtoHosId)
        }

        //动态表头
        onColumnRef = (ref) => {
            this.columnRef = ref;
        }

        onColumnRefLoc = (ref) => {
            this.columnRefLoc = ref;
        }
        // 获取主列表columns--服务项目列表
        getMainTableColumnsItem = () => {
            let data = {
                params: [{
                    compontName: "ServiceGroupAssociatedOrder",
                    reactCode: ['ServiceGroupAssociatedOrder'],
                    type: 'C',
                }]
            }
            $http.post('urlS', this, {
                code: '01040073',
                data: data,
                success: function (res) {
                    if (+res.errorCode === 0) {
                        let arr = res.result && res.result.C.length > 0 ? JSON.parse(JSON.stringify(res.result.C)).map(item => {
                            return {
                                align: item.align,
                                widthNum: parseInt(item.width),
                                width: item.width,
                                dataIndex: item.dataIndex,
                                title: <div onDoubleClick={() => this.columnRefLoc.onOpenModel()}>{this.state.userData.language == 'EN' ? item.descripts : item.title}</div>,
                                display: item.display,
                                key: item.seqNo,
                            }
                        }) : '';
                        let filterArr = arr.filter(function (item) { return item.display === 'Y' });
                        this.setState({ colcolumnsLeftTab: filterArr, })
                    }
                }
            })
        }
        //获取医嘱子类
        getSubData = () => {
            let data = {
                params: [{
                }],
            }
            $http.post('urlS', this, {
                code: '05100173',
                data: data,
                success: function (res) {
                    if (+res.errorCode === 0) {
                        this.setState({
                            subArr: res.data
                        })
                    }
                }
            })
        }
        //左侧数据项目列表
        getOtherLoc = (Id) => {
            let data = {
                params: [{
                    hospID: Id || "",
                    MedItemName: this.props.form.getFieldValue("searchLoc") || "",
                    OrderTypeCode: this.props.form.getFieldValue("subDr") || ""
                }]
            }
            $http.post('urlS', this, {
                code: "01040161",
                data: data,
                success: (res) => {
                    if (+res.errorCode === 0) {
                        res.dataArr.map((item, index) => {
                            res.dataArr[index].key = index;
                            return res.dataArr;
                        })
                        this.setState({
                            leftLocData: res.dataArr,
                        })
                    }
                }

            })
        }
        //查询已选项目
        getAuthorizationList = (Id, input) => {
            // console.log(inpVal)
            let data = {
                params: [{
                    GroupID: Id || "",
                    MedItemName: this.props.form.getFieldValue("searchRightItem") || "",
                }]
            }

            $http.post('urlS', this, {
                code: "01040163",
                data: data,
                success: (res) => {
                    if (+res.errorCode === 0) {
                        res.dataArr.map((item, index) => {
                            res.dataArr[index].key = index;
                            return res.dataArr;
                        })
                        this.setState({
                            rightLocData: res.dataArr,
                            selectedRowKeys_right: []
                        })
                    }
                }
            })
        }
        findLeftLocData = () => {
            if (this.props.rowIds!="") {
                this.handleRestLeftItemSearch()
                this.getOtherLoc(this.props.rowIdtoHosId)
            } else {
                message.warning("请选择左侧服务组列表")
            }
        }
        findRightLocData = () => {
            if (this.props.rowIds!="") {
                this.handleRestRightItemSearch()
                this.getAuthorizationList(this.props.rowIds)
            } else {
                message.warning("请选择左侧服务组列表")
            }
        }
        //批量删除
        moreDel = () => {
            if (this.state.selectedRowKeys_right && this.state.selectedRowKeys_right.length > 0) {
                let data = {
                    params: [{
                        IDs: this.state.selectedRowKeys_right,
                        updateUserID: JSON.parse(sessionStorage.userData).userID || '',
                    }]
                }
                $http.post('urlS', this, {
                    code: "01040164",
                    data: data,
                    success: (res) => {
                        if (+res.errorCode === 0) {
                            message.success(this.state.localeProvider && this.state.localeProvider.CureServiceGroupDocSuccessfullyDeleted ? this.setMessage('CureServiceGroupDocSuccessfullyDeleted', 'descripts') : "删除成功")
                            this.getAuthorizationList(this.props.rowIds)
                            this.getOtherLoc(this.props.rowIdtoHosId)
                        }
                    }
                })
            } else {
                message.warning(this.state.localeProvider && this.state.localeProvider.CureServiceGroupDocClickOnBatchDelete ? this.setMessage('CureServiceGroupDocClickOnBatchDelete', 'descripts') : "请勾选后再点击批量删除")
            }
        }
        handelAdd = () => {
            const { selectedData } = this.state
            if (this.state.selectedRows.length > 0) {
                let data = {
                    params:
                        selectedData,
                }
                // this.state.selectedRows.map((item) => {
                //     return data.params[0].MenuDetail.push({
                //         MenuDetailDr: item.id,
                //         SeqNo: '',
                //         LocDr: '',
                //         PreMenuGroupDr: this.state.selectrow,
                //         UpdateUserDr: user.userID
                //     });
                // })
                $http.post('urlS', this, {
                    code: "01040165",
                    data: data,
                    success: (res) => {
                        if (+res.errorCode === 0) {
                            message.success(this.state.localeProvider && this.state.localeProvider.CureServiceGroupDocAddedSuccessfully ? this.setMessage('CureServiceGroupDocAddedSuccessfully', 'descripts') : "新增成功");
                            this.getAuthorizationList(this.props.rowIds);
                            this.getOtherLoc(this.props.rowIdtoHosId)
                            this.setState({ selectedRowKeys: [], selectedRowKeys_right: [], selectedData: [], selectrow: '', selectedRows: '' });
                        }
                    },
                    error: (error) => {
                        message.error(this.state.localeProvider && this.state.localeProvider.CureServiceGroupDocAddFailed ? this.setMessage('CureServiceGroupDocAddFailed', 'descripts') : "新增失败" + error);
                    }
                })
            } else {
                message.error(this.state.localeProvider && this.state.localeProvider.CureServiceGroupDocPleaseCheck ? this.setMessage('CureServiceGroupDocPleaseCheck', 'descripts') : "请勾选后再点击增加");
            }
        }
        /*
        状态重置
        新增/查询服务组-- 服务组列表取消选中
        服务组列表取消选中-- 右侧服务组医生 服务组项目重置 服务组列表选中id置空
        服务组列表切换选中-- 右侧服务组医生 服务组项目重置
        右侧服务组医生列表 新增-- 服务组医生列表选中取消 服务组项目置空
        右侧服务组医生列表 切换选中--  服务组项目置空
        // 右侧服务组医生列表 取消选中--  服务组项目置空
        右侧服务项目列表 查询-- 服务组项目列表置空 取消已选中
        右侧已选服务项目列表 查询-- 已选服务组项目列表置空 取消已选中
        */
        handleRestListCancel = () => {
            this.props.form.setFieldsValue({ docID: undefined, subDr: undefined, searchLoc: undefined, searchRightItem: undefined })
            this.setState({
                rowIds: "", parms: "",
                rowIdHos: "", rowIdtoHosId: "", sourceDocData: [], searchDoc: "search", pageDoc: 1,
                selectedRowKeys: [], selectedRowKeys_right: [], selectedData: [], selectrow: '', selectedRows: '', leftLocData: [], rightLocData: []
            });
        }
        handleRestListchange = () => {
            this.props.form.setFieldsValue({ subDr: undefined, searchLoc: undefined, searchRightItem: undefined })
            this.setState({
                rowIdHos: "", sourceDocData: [], searchDoc: "search", pageDoc: 1,
                selectedRowKeys: [], selectedRowKeys_right: [], selectedData: [], selectrow: '', selectedRows: '', leftLocData: [], rightLocData: []
            });
        }
        handleRestDocChange = () => {
            this.props.form.setFieldsValue({ subDr: undefined, searchLoc: undefined, searchRightItem: undefined })
            this.setState({
                selectedRowKeys: [], selectedRowKeys_right: [], selectedData: [], selectrow: '', selectedRows: '', leftLocData: [], rightLocData: []
            });
        }
        handleRestLeftItemSearch = () => {
            this.setState({
                selectedRowKeys: [], selectedData: [], leftLocData: [],
            });
        }
        handleRestRightItemSearch = () => {
            this.setState({
                selectedRowKeys_right: [], selectrow: '', selectedRows: '', rightLocData: []
            });
        }
        //国际化
        setMessage(name, message) {
            return this.state.localeProvider ? this.state.localeProvider[name][message] : ''
        }

        render() {
            const { getFieldDecorator } = this.props.form;
            const { searchLoading, columns, columnsDoc, colcolumnsLeftTab } = this.state;
            //医嘱子类
            let subOp = []
            this.state.subArr && this.state.subArr.map((item) => {
                subOp.push(<Option key={item.id} role={item.descripts + '^' + item.descriptsSPCode} title={item.descripts} value={String(item.id)}>{item.descripts}</Option>)
            })
            const { selectedRowKeys, selectedRow_right } = this.state
            const rowSelection = {
                selectedRowKeys,
                onChange: (selectedRowKeys, selectedRows) => {
                    // console.log("selectedRows",selectedRows)
                    let arr = []
                    selectedRows.map((item, i) => {
                        let obj = {
                            updateUserID: JSON.parse(sessionStorage.userData).userID || '',
                            hospID: this.props.rowIdtoHosId,
                            GroupID: this.props.rowIds,
                            MedItemID: "",
                            createDate: moment().format('YYYY-MM-DD') || undefined,//创建日期
                            startDate: moment().format('YYYY-MM-DD') || undefined,//开始日期
                            stopDate: undefined,
                        }
                        // obj["GroupId"] = item.groupId
                        obj["MedItemID"] = item.medIiemID
                        arr.push(obj)
                        if (!obj["MedItemID"]) {
                            arr.splice(i)
                        }
                    })
                    this.setState({ selectedData: arr, selectedRows, selectedRowKeys });
                },
                onSelect: (record, selected, selectedRows) => {
                    // console.log("onSelect",record, selected,selectedRows)
                    let arr = []

                    selectedRows.map((item, i) => {
                        let obj = {
                            updateUserID: JSON.parse(sessionStorage.userData).userID || '',
                            hospID: this.props.rowIdtoHosId,
                            GroupID: this.props.rowIds,
                            MedItemID: "",
                            createDate: moment().format('YYYY-MM-DD') || undefined,//创建日期
                            startDate: moment().format('YYYY-MM-DD') || undefined,//开始日期
                            stopDate: undefined,
                        }
                        // obj["GroupId"] = item.groupId
                        obj["MedItemID"] = item.medIiemID
                        arr.push(obj)
                        if (!obj["MedItemID"]) {
                            arr.splice(i)
                        }
                    })
                    this.setState({ selectedData: arr, selectedRows });
                },
                onSelectAll: (selected, selectedRows, changeRows) => {
                    let arr = []

                    selectedRows.map((item, i) => {
                        let obj = {
                            updateUserID: JSON.parse(sessionStorage.userData).userID || '',
                            hospID: this.props.rowIdtoHosId,
                            GroupID: this.props.rowIds,
                            MedItemID: "",
                            createDate: moment().format('YYYY-MM-DD') || undefined,//创建日期
                            startDate: moment().format('YYYY-MM-DD') || undefined,//开始日期
                            stopDate: undefined,
                        }
                        // obj["GroupId"] = item.groupId
                        obj["MedItemID"] = item.medIiemID
                        arr.push(obj)
                        if (!obj["MedItemID"]) {
                            arr.splice(i)
                        }
                    })
                    this.setState({ selectedData: arr, selectedRows });
                }
            };
            const rowSelection_right = {
                selectedRowKeys: this.state.selectedRowKeys_right,
                onChange: (selectedRowKeys, selectedRows) => {
                    let btnStatus = 'active';
                    let selectrow = "";
                    if (selectedRowKeys.length === 0) {
                        btnStatus = 'default';
                    } else {
                        selectrow = selectedRowKeys[selectedRowKeys.length - 1];
                    }
                    this.setState({ btnStatus: btnStatus, selectrow: selectrow, selectedRow_right: selectedRows, selectedRowKeys_right: selectedRowKeys });
                },
                onSelectAll: (selected, selectedRows, changeRows) => {
                    if (selectedRows.length > 0) {
                        this.setState({
                            btnStatus: 'active'
                        })
                    } else {
                        this.setState({
                            btnStatus: 'default'
                        })
                    }
                    this.setState({ selectedRow_right: selectedRows });
                }
            };
            return (
                <div style={{ padding: '4px 2px' }} className="serviceGroupDom">
                    <Row>
                        <Col span={24}>
                            {/* <div className="diagTitle">
                                <span className='scheduling-title-border' style={{ marginLeft: '10px' }}></span>
                                <span style={{ marginLeft: 5, }}>{this.state.localeProvider && this.state.localeProvider.CureServiceGroupDocServicesAvailable ? this.setMessage('CureServiceGroupDocServicesAvailable', 'descripts') : "服务项目"}</span>
                            </div> */}
                            <div className={"flexBox locDom"}>
                                <div className={"leftTbale"}>
                                    <Row>
                                        <Col span={24}>
                                            <ul style={{ paddingLeft: '15px' }}>
                                                <li style={{ color: '#F7805D' }}><span style={{ color: 'green', fontSize: '16px' }}>{this.state.localeProvider && this.state.localeProvider.CureServiceGroupDocItemList ? this.setMessage('CureServiceGroupDocItemList', 'descripts') : "项目列表"}</span></li>
                                            </ul>

                                        </Col>
                                    </Row>
                                    <Row>
                                        <Col span={12} style={paddRightCol}>
                                            <FormItem {...formItemLayoutTT} label={this.state.localeProvider && this.state.localeProvider.CureServiceGroupDocMedicalSubclass ? this.setMessage('CureServiceGroupDocMedicalSubclass', 'descripts') : "医嘱子类"}>
                                                {getFieldDecorator('subDr', {
                                                    initialValue: undefined,
                                                    rules: [{ required: false, message: '' }],
                                                })(
                                                    <Select
                                                        allowClear
                                                        showSearch
                                                        optionFilterProp="role"
                                                        style={{ width: "100%" }}
                                                    >
                                                        {subOp}
                                                    </Select>
                                                )}
                                            </FormItem>
                                        </Col>
                                        <Col span={12} style={paddRightCol}>
                                            <FormItem {...formItemLayoutLocItem} label={this.state.localeProvider && this.state.localeProvider.CureServiceGroupDocMedicalOrder ? this.setMessage('CureServiceGroupDocMedicalOrder', 'descripts') : "医嘱项"}>
                                                {getFieldDecorator('searchLoc', {
                                                    initialValue: undefined,
                                                    rules: [{ required: false, message: '' }],
                                                })(
                                                    <Input placeholder={this.state.localeProvider && this.state.localeProvider.CureServiceGroupDocCodeNameOrFirstSpell ? this.setMessage('CureServiceGroupDocCodeNameOrFirstSpell', 'descripts') : "代码、名称或首拼"} onPressEnter={this.findLeftLocData}></Input>
                                                )}
                                            </FormItem>
                                        </Col>
                                    </Row>
                                    <Row style={{ textAlign: "right", marginTop: "-10px" }}>
                                        <Col span={24} style={{ marginBottom: "4px", }}>
                                            <Button type="primary" onClick={this.findLeftLocData}>{this.state.localeProvider && this.state.localeProvider.CureServiceGroupDocSearch ? this.setMessage('CureServiceGroupDocSearch', 'descripts') : "查询"}</Button>
                                        </Col>
                                    </Row>
                                    <div id="item-dom">
                                        <Table
                                            // style={{ height: this.state.windowheight - 380 + 'px' }}
                                            bordered
                                            // loading={this.state.leftTabLoading}
                                            // components={this.components}
                                            columns={colcolumnsLeftTab}
                                            dataSource={this.state.leftLocData}
                                            rowKey={(row) => {
                                                return row.ID
                                            }}
                                            pagination={false}
                                            style={{ height: store.getState().tableHeight.y - 41 + 'px', overflow: "auto" }}
                                            // scroll={{ x: 240, y: this.state.windowheight - 380 - 40 }}
                                            rowSelection={rowSelection}
                                        />
                                    </div>
                                    <ColumnAuthoritysModel
                                        clientWidth='800px'
                                        compontName='ServiceGroupAssociatedOrder'
                                        configType="C"
                                        onRef={this.onColumnRefLoc}
                                        reloadData={this.getMainTableColumnsItem}
                                    />
                                </div>
                                < Icon type="right-circle" style={{ fontSize: '30px', display: 'flex', alignItems: 'center' }} size="small" onClick={this.handelAdd} />
                                <div className={"rightTbale"} style={{ overflow: 'hidden', padding: "0 20px 20px 20px", margintop: '4px' }}>
                                    <Row>
                                        <Col span={24}>
                                            <ul style={{ paddingLeft: '15px' }}>
                                                <li style={{ color: '#42B983' }}><span style={{ color: 'green', margintop: '1rem', fontSize: '16px' }}>{this.state.localeProvider && this.state.localeProvider.CureServiceGroupDocListOfItemsAdded ? this.setMessage('CureServiceGroupDocListOfItemsAdded', 'descripts') : "已添加项目列表"}</span></li>
                                            </ul>

                                        </Col>
                                    </Row>
                                    <Row>
                                        <Col span={12} style={paddRightCol}>
                                            <FormItem {...formItemLayoutLocItem} label={this.state.localeProvider && this.state.localeProvider.CureServiceGroupDocMedicalOrder ? this.setMessage('CureServiceGroupDocMedicalOrder', 'descripts') : "医嘱项"}>
                                                {getFieldDecorator('searchRightItem', {
                                                    initialValue: undefined,
                                                    rules: [{ required: false, message: '' }],
                                                })(
                                                    <Input placeholder={this.state.localeProvider && this.state.localeProvider.CureServiceGroupDocCodeNameOrFirstSpell ? this.setMessage('CureServiceGroupDocCodeNameOrFirstSpell', 'descripts') : "代码、名称或首拼"} onPressEnter={this.findRightLocData}></Input>
                                                )}
                                            </FormItem>
                                        </Col>
                                    </Row>
                                    <Row style={{ textAlign: "left", }}>
                                        <Col span={24} style={{ marginBottom: "4px", marginTop: "-10px" }}>
                                            <Button style={{ background: "#fff", border: "0", color: "#40a9ff" }} type="primary" onClick={this.moreDel} >{this.state.localeProvider && this.state.localeProvider.CureServiceGroupDocDeleteInBatches ? this.setMessage('CureServiceGroupDocDeleteInBatches', 'descripts') : "批量删除"}</Button>
                                        </Col>
                                    </Row>
                                    <div id="items-dom">
                                        <Table
                                            // style={{ height: this.state.windowheight - 380 + 'px', marginTop: '1.18rem' }}
                                            columns={colcolumnsLeftTab}
                                            bordered
                                            // loading={this.state.rightTabLoading}
                                            indentSize={15}
                                            dataSource={this.state.rightLocData}
                                            rowKey={(row) => {
                                                return row.ID
                                            }}
                                            rowClassName={this.setRowClassName}
                                            // onRow={this.onClickRow}
                                            pagination={false}
                                            rowSelection={rowSelection_right}
                                            style={{ height: store.getState().tableHeight.y - 41 + 'px', overflow: "auto" }}
                                        // scroll={{ x: 440, y: this.state.windowheight - 380 - 40 }}
                                        />
                                    </div>

                                </div>
                            </div>
                        </Col>
                    </Row>
                </div>

            )
        }
    })
export default ServiceGroupItems    