/*
 * Creator:     ML
 * CreatDate:   2019-12-25
 * 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 ServiceGroupListModal from './component/ServiceGroupListModal';
import CommonPagination from 'components/pagination/index';
import ColumnAuthoritysModel from 'pages/columnAuthority/ColumnAuthoritysModel';
import ServiceGroupTabs from './ServiceGroupTabs';

const FormItem = Form.Item;
const Option = Select.Option;
const paddRightCol = {
    paddingRight: "0px"
}
const formItemLayoutType = {
    labelCol: { span: 5 },
    wrapperCol: { span: 18 }
}
const formItemLayout = { // label 和input宽度
    labelCol: { span: 8 },
    wrapperCol: { span: 14 },
}

const ServiceGroup = Form.create()(
    class ServiceGroup 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() {
            // 初始化设置table的高度以及表体的高度
            document.querySelector('.listDom .ant-table-body').style.height = store.getState().tableHeight.y + 104 + 'px';
            this.getHopSelect()
            this.getFindDate()
            this.getMainTableColumns()
        }
        //服务组tabs
        onTabs=(ref)=>{
            this.onTabsRef = ref
        }
        //动态表头
        onColumnRef = (ref) => {
            this.columnRef = ref;
        }
        // 获取主列表columns --服务组列表
        getMainTableColumns = () => {
            let data = {
                params: [{
                    compontName: "DocCureServiceGroup",
                    reactCode: ['DocCureServiceGroup'],
                    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.columnRef.onOpenModel()}>{item.title}</div>,
                                display: item.display,
                                key: item.seqNo,
                            }
                        }) : '';
                        let filterArr = arr.filter(function (item) { return item.display === 'Y' });
                        let seqArr = {
                            align: "center",
                            widthNum: 140,
                            width: "50px",
                            code: "edit",
                            dataIndex: "edit",
                            title: "操作",
                            display: "Y",
                            render: (value, row, index) => {
                                return (
                                    <span>
                                        <a onClick={(e) => this.toggleEditable(row, "1")}>{this.state.localeProvider && this.state.localeProvider.CureServiceGroupDocEdit ? this.setMessage('CureServiceGroupDocEdit', 'descripts') : "编辑"}</a>
                                        <Divider type="vertical" />
                                        <Popconfirm title={this.state.localeProvider && this.state.localeProvider.CureServiceGroupDocWhetherToDelete ? this.setMessage('CureServiceGroupDocWhetherToDelete', 'descripts') : "是否要删除"} onConfirm={() => this.toggleEditable(row, "2")}>
                                            <a style={{ color: "red" }} >{this.state.localeProvider && this.state.localeProvider.CureServiceGroupDocDelete ? this.setMessage('CureServiceGroupDocDelete', 'descripts') : "删除"}</a>
                                        </Popconfirm>
                                    </span>
                                )
                            },
                        }
                        filterArr.push(seqArr)
                        this.setState({ columns: filterArr, widthTotal: res.totalWidth })
                    }
                }
            })
        }
        //获取医院下拉框
        getHopSelect = () => {
            let data = {
                params: [{
                    hospID: sessionStorage.userData ? JSON.parse(sessionStorage.userData).hospID : "",
                    logonGroupID: sessionStorage.userData ? JSON.parse(sessionStorage.userData).groupID : "",
                    logonHospID: sessionStorage.userData ? JSON.parse(sessionStorage.userData).hospID : "",
                }],
            }
            $http.post('urlS', this, {
                code: '01040001',
                data: data,
                success: function (res) {
                    if (+res.errorCode === 0) {
                        this.setState({
                            hospArr: res.result
                        })
                    }
                }
            })
        }
        //医院选择带出科室
        handleBaseHosp = (id) => {
            this.props.form.setFieldsValue({ locID: undefined })
            if (id) {
                this.setState({
                    hosID: id
                }, () => {
                    this.getPublicBaseLocSelect()
                })
            } else {
                this.setState({
                    hosID: "",
                    publicBaseLocArr: []
                }, () => {
                    this.getPublicBaseLocSelect()
                })
            }

        }
        //获取科室下拉框
        getPublicBaseLocSelect = () => {
            let data = {}
            data = {
                params: [{
                    hospID: this.state.hosID || "",
                    locTypeID: this.state.locID || ""
                }],
            }
            $http.post('urlS', this, {
                code: '01050029',
                data: data,
                success: function (res) {
                    if (+res.errorCode === 0 && res.result.Data) {
                        let arr = res.result.Data && res.result.Data.map((item, index) => {
                            res.result.Data[index].key = Number(index)
                        })
                        this.setState({
                            publicBaseLocArr: res.result.Data,
                        })
                    } else {

                    }
                }
            })
        }
        // 修改page和pageSize 跳转至---
        onChange = (e, pageSize) => {
            this.setState({ page: e, pageSize: this.state.pageSize }, () => {
                // 重新调用查询方法
                let { values } = this.state;
                this.getFindDate(values);
            })
        }
        //下拉选择页数
        onShowSizeChange = (page, pageSize) => {
            this.setState({ page: 1, pageSize: pageSize }, () => {
                // 重新调用查询方法
                let { values } = this.state;
                this.getFindDate(values, "search");
            })
        }
        // 显示分页总条数
        showTotal(total) {
            return `共 ${total} 条`;
        }
        //定位到最新添加/当前修改的记录
        getNewData = (id) => {
            //跳至最后一页 并定位到刚添加的这条记录
            if (id) {
                let lastPage = Math.ceil((this.state.total + 1) / this.state.pageSize)
                this.onChange(lastPage, this.state.pageSize)
                this.onTabsRef.handleRestListCancel()
                this.setState({
                    rowIds: "", parms: "",
                })
            } else {
                this.setState({
                    rowIds: "", parms: "",
                })
                this.onTabsRef.handleRestListCancel()
                this.onChange(this.state.page, this.state.pageSize)
            }
        }
        //获取查询数据
        getFindDate = (values, e) => {
            if (this.state.total == 0) {
                this.setState({
                    searchLoading: true
                })
            }
            let { page, pageSize, } = this.state;
            let data = {}
            data = {
                params: [{
                    hospID: values && values.getHop || '',
                    locID: values && values.locID || '',
                    input: values && values.searchSerInt || '',
                    status: values && values.status || "ALL",
                }],
                pagination: [{
                    pageSize: pageSize,
                    currentPage: page,
                }]
            }
            $http.post('urlS', this, {
                code: '01040154',
                data: data,
                success: function (res) {
                    if (+res.errorCode === 0 && res.result) {
                        this.setState({
                            searchLoading: false,
                            search: e
                        })
                        for (var i = 0; i < res.result.data.length; i++) {
                            res.result.data[i].key = i + 'bed'
                        }
                        this.setState({ baseData: res.result.data, total: res.result.TotalCount, }, () => {
                        })
                    } else {
                        this.setState({
                            searchLoading: false
                        })
                    }
                },
                error: function () {
                    this.setState({
                        searchLoading: false
                    })
                }
            })

        }
        //点击查询---
        findData = () => {
            this.props.form.validateFields((err, values) => {
                if (!err) {
                    this.setState({
                        values: values,
                        rowIds: "",
                        parms: "",
                    })
                    this.onTabsRef.handleRestListCancel()
                    this.onShowSizeChange("1", this.state.pageSize)
                }
            })
        }
        // 调用子组件的连接事件 -- 添加新
        OnChildrefs = (ref) => {
            this.child = ref
        }
        add = () => {
            this.child.showModal()
        }
        //点击查询后 表格行
        setRowClassNames = (record) => {
            return record.id === this.state.rowIds ? 'clickRowStyle' : '';
        }
        //点击Row ---服务组列表
        onClickRow = (record) => {
            return {
                onClick: () => {
                    if (this.state.rowIds === "") {
                        this.setState({
                            rowIds: record.id,
                            parms: record,
                            rowIdtoHosId: record.hospId,
                        }, () => {
                            this.onTabsRef.getDocData(record)
                            // this.getToDoc(record.id)
                            this.onTabsRef.onChangeDoc(1)
                            this.onTabsRef.getAuthorizationList(record.id)
                            this.onTabsRef.getOtherLoc(record.hospId)
                        });

                    } else {
                        if (this.state.rowIds !== record.id) {
                            this.setState({
                                rowIds: record.id,
                                parms: record,
                                rowIdtoHosId: record.hospId,
                            }, () => {
                                this.onTabsRef.handleRestListchange()
                                this.onTabsRef.getDocData(record)
                                this.onTabsRef.onChangeDoc(1)
                                this.onTabsRef.getAuthorizationList(record.id)
                                this.onTabsRef.getOtherLoc(record.hospId)
                            });
                        } else {
                            this.setState({
                                rowIdtoHosId: "",
                                totalDoc: 0,
                                searchDoc: "search",
                                rowIds:"",
                                parms: "",
                            })
                            this.props.form.setFieldsValue({ docID: undefined })
                            this.onTabsRef.handleRestListCancel()
                        }
                    }
                },
            };
        }
        //编辑 /删除 
        toggleEditable = (record, num) => {
            if (num == "1") {
                this.child.showModal(record, num)
            } else {
                let datas = {}
                datas = {
                    params: [{
                        updateUserID: JSON.parse(sessionStorage.userData).userID || '',
                        ID: record.id,
                    }],
                }
                $http.post('urlS', this, {
                    code: '01040156',
                    data: datas,
                    success: function (res) {
                        if (+res.errorCode === 0) {
                            message.success("删除成功");
                            this.getFindDate()
                        }
                    }
                })
            }
        }
        //国际化
        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 statusData = [
                {
                    descriptsSPCode: "QB",
                    descripts: "全部",
                    id: "ALL",
                    descriptsEN: "All"
                }, {
                    descriptsSPCode: "SX",
                    descripts: "生效",
                    id: "Y",
                    descriptsEN: "Take effect"
                }, {
                    descriptsSPCode: "SX",
                    descripts: "失效",
                    id: "N",
                    descriptsEN: "Invalid"
                },
            ]
            //状态
            let statusOp = [];
            statusData && statusData.map((item, index) => {
                statusOp.push(<Option key={index} code={item.descriptsSPCode} value={item.id} title={item.descripts + '^' + item.id}>{this.state.userData.language == 'EN' ? item.descriptsEN : item.descripts}</Option>)
            })
            //医院
            let hosOp = []
            this.state.hospArr && this.state.hospArr.map((item) => {
                hosOp.push(<Option key={item.id} role={item.descripts + '^' + item.descriptsSPCode} title={item.descripts} onClick={(e, ) => this.handleBaseHosp(item.id)} value={String(item.id)}>{item.descripts}</Option>)
            })
            //科室类型
            let locOp = []
            this.state.publicBaseLocArr && this.state.publicBaseLocArr.map(item => {
                locOp.push(<Option key={item.id} role={item.descripts + '^' + item.descriptsSPCode} title={item.descripts} value={String(item.id)}>{item.descripts}</Option>)
            })
            //医生
            let docOp = []
            this.state.docArr && this.state.docArr.map((item) => {
                docOp.push(<Option key={item.doctorID} value={String(item.doctorID)}>{item.descripts}</Option>)
            })
            //医嘱子类
            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.state.rowIdtoHosId,
                            GroupID: this.state.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.state.rowIdtoHosId,
                            GroupID: this.state.rowIds,
                            MedItemID: "",
                            createDate: moment().format('YYYY-MM-DD') || undefined,//创建日期
                            startDate: moment().format('YYYY-MM-DD') || undefined,//开始日期
                            stopDate: undefined,
                        }
                        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.state.rowIdtoHosId,
                            GroupID: this.state.rowIds,
                            MedItemID: "",
                            createDate: moment().format('YYYY-MM-DD') || undefined,//创建日期
                            startDate: moment().format('YYYY-MM-DD') || undefined,//开始日期
                            stopDate: undefined,
                        }
                        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">
                    <div className="department-header">
                        <Form>
                            <Row gutter={60} style={{ margin: '0' }}>
                                <Col span={4} style={paddRightCol}>
                                    <FormItem {...formItemLayoutType} label={this.state.localeProvider && this.state.localeProvider.CureServiceGroupDocHospital ? this.setMessage('CureServiceGroupDocHospital', 'descripts') : "医院"}>
                                        {getFieldDecorator('getHop', {
                                            initialValue: undefined,
                                            rules: [{ required: false, message: '' }],
                                        })(
                                            <Select
                                                allowClear
                                                showSearch
                                                optionFilterProp="role"
                                                onChange={this.handleBaseHosp}
                                            >
                                                {hosOp}
                                            </Select>
                                        )}
                                    </FormItem>
                                </Col>
                                <Col span={4} style={paddRightCol}>
                                    <FormItem {...formItemLayoutType} label={this.state.localeProvider && this.state.localeProvider.CureServiceGroupDocDepartment ? this.setMessage('CureServiceGroupDocDepartment', 'descripts') : "科室"}>
                                        {getFieldDecorator('locID', {
                                            initialValue: undefined,
                                            rules: [{ required: false, message: '' }],
                                        })(
                                            <Select
                                                allowClear
                                                showSearch
                                                optionFilterProp="role"
                                                placeholder={"请先选择医院"}
                                            >
                                                {locOp}
                                            </Select>
                                        )}
                                    </FormItem>
                                </Col>
                                <Col span={4} style={paddRightCol}>
                                    <FormItem {...formItemLayoutType} label={this.state.localeProvider && this.state.localeProvider.CureServiceGroupDocServiceGroup ? this.setMessage('CureServiceGroupDocServiceGroup', 'descripts') : "服务组"}>
                                        {getFieldDecorator('searchSerInt', {
                                            initialValue: undefined,
                                            rules: [{ required: false, message: '' }],
                                        })(
                                            <Input placeholder={this.state.localeProvider && this.state.localeProvider.CureServiceGroupDocCodeOrName ? this.setMessage('CureServiceGroupDocCodeOrName', 'descripts') : "代码或名称"} onPressEnter={this.findData}></Input>
                                        )}
                                    </FormItem>
                                </Col>
                                <Col span={4} style={paddRightCol}>
                                    <FormItem {...formItemLayoutType} label={this.state.localeProvider && this.state.localeProvider.CureServiceGroupDocStatus ? this.setMessage('CureServiceGroupDocStatus', 'descripts') : "状态"}>
                                        {getFieldDecorator('status', {
                                            initialValue: "ALL",
                                            rules: [{ required: false, message: '' }],
                                        })(
                                            <Select
                                                allowClear
                                            >
                                                {statusOp}
                                            </Select>
                                        )}
                                    </FormItem>
                                </Col>
                                <Col span={2} style={paddRightCol}>
                                    <FormItem  {...formItemLayout}>
                                        {getFieldDecorator('posInp', {
                                            initialValue: undefined,
                                            rules: [{ required: false, message: '' }],
                                        })(
                                            <Button onClick={this.findData} loading={searchLoading} style={{ background: 'rgba(66,185,131,1)', color: '#fff' }}>{this.state.localeProvider && this.state.localeProvider.CureServiceGroupDocSearch ? this.setMessage('CureServiceGroupDocSearch', 'descripts') : "查询"}</Button>
                                        )}
                                    </FormItem>
                                </Col>
                                <Col span={2} style={{ padding: "0px" }}>
                                    <FormItem  {...formItemLayout}>
                                        {getFieldDecorator('addNewCard', {
                                            initialValue: undefined,
                                            rules: [{ required: false, message: '' }],
                                        })(
                                            <Button onClick={this.add} style={{ background: 'rgba(66,185,131,1)', color: '#fff' }}>{this.state.localeProvider && this.state.localeProvider.CureServiceGroupDocAddServiceGroup ? this.setMessage('CureServiceGroupDocAddServiceGroup', 'descripts') : "添加服务组"}</Button>
                                        )}
                                    </FormItem>
                                </Col>
                            </Row>
                        </Form>
                    </div>
                    <Row>
                        <Col span={10}>
                            <Card style={{ position: "relative", paddingBottom: "0" }} className="joinDom" >
                                <div className="diagTitle">
                                    <span className='scheduling-title-border' style={{ marginLeft: '10px' }}></span>
                                    <span style={{ marginLeft: 5, }}>{this.state.localeProvider && this.state.localeProvider.CureServiceGroupDocListOfServiceGroups ? this.setMessage('CureServiceGroupDocListOfServiceGroups', 'descripts') : "服务组列表"}</span>
                                </div>
                                <div className="listDom">
                                    <Table
                                        // scroll={{ x: 1160, y: store.getState().tableHeight.y + 156 }}
                                        columns={columns}
                                        dataSource={this.state.baseData}
                                        pagination={false}
                                        rowKey={record => record.key}
                                        onRow={this.onClickRow}
                                        rowClassName={this.setRowClassNames}
                                        bordered
                                        style={{ height: store.getState().tableHeight.y + 106 + 'px' }}
                                    />
                                    <CommonPagination size={this.state.size} page={this.state.page} current={this.state.page} total={this.state.total} search={this.state.search}
                                        onShowSizeChange={this.onShowSizeChange.bind(this)} complete={true} dataSource={this.state.baseData}
                                        onChange={this.onChange.bind(this)} />
                                </div>
                                <ServiceGroupListModal getNewData={this.getNewData} OnChildrefs={this.OnChildrefs}></ServiceGroupListModal>
                                <ColumnAuthoritysModel
                                    clientWidth='800px'
                                    compontName='DocCureServiceGroup'
                                    configType="C"
                                    onRef={this.onColumnRef}
                                    reloadData={this.getMainTableColumns}
                                />
                            </Card>
                        </Col>
                        <ServiceGroupTabs onTabs={this.onTabs}></ServiceGroupTabs>
                    </Row>
                </div>

            )
        }
    })
export default ServiceGroup    