/*
 * Creator:     ML
 * CreatDate:   2020-09-18
 * descripts：  医生助理
*/
import React from 'react';
import { Form, Row, Col, Input, Button, Table, message, Popconfirm, Spin, Card, Divider, Select, Icon } from 'antd';
import { $http } from '../../../containers/config/https';
import '../css/index.less';
import store from 'store';
import moment from 'moment';
import ColumnAuthoritysModel from 'pages/columnAuthority/ColumnAuthoritysModel';
import EditAssistantModal from './EditAssistantModal';
const formItemLayoutTT = {
    labelCol: { span: 3 },
    wrapperCol: { span: 21 },
}
const formItemLayoutLoc = {
    labelCol: { span: 5 },
    wrapperCol: { span: 19 },
}
const paddRightCol = {
    paddingRight: "0px"
}
const FormItem = Form.Item;
const AddAssistant = Form.create()(
    class AddAssistant extends React.Component {
        cacheOriginData = {};
        constructor(props) {
            super(props)
            this.state = {
                rightData: [],
                loadingDom: false,
                initRored: {},
                selectedRowKeys_right:[]
            }
        }
        componentDidMount() {
            let userData = sessionStorage.getItem("userData") ? JSON.parse(sessionStorage.getItem("userData")) : {};
            this.setState({
                userData,
            })
            this.props.onAddAssistant(this)
        }
        getData = () => {
            this.getLocType()
            this.getMainTableColumnsLoc()
            this.getAllDoc()
            this.getAuthorizationList()
        }
        //查询科室医生列表
        getAllDoc = () => {
            let data = {
                params: [{
                    locID: sessionStorage.userData ? JSON.parse(sessionStorage.userData).locID : "",
                    inputValue: this.props.form.getFieldValue("searchLoc"),
                }]
            }
            $http.post('urlS', this, {
                code: "03020061",
                data: data,
                success: (res) => {
                    if (+res.errorCode === 0) {
                        res.Data.map((item, index) => {
                            res.Data[index].key = index;
                            return res.Data;
                        })
                        this.setState({
                            // rightLocData: this.mapDataToKey(res.result.data),
                            leftLocData: res.Data,
                            //  total: res.result.TotalCount,
                            // rightTabLoading: false
                        })
                    }
                }

            })
        }
        //查询已添加助理
        getAuthorizationList = () => {
            let data = {
                params: [{
                    locID: sessionStorage.userData ? JSON.parse(sessionStorage.userData).locID : "",
                    hospID: sessionStorage.userData ? JSON.parse(sessionStorage.userData).hospID : "",
                    userID: sessionStorage.userData ? JSON.parse(sessionStorage.userData).userID : "",
                    inputValue: this.props.form.getFieldValue("searchRightLoc"),
                }]
            }

            $http.post('urlS', this, {
                code: "01040224",
                data: data,
                success: (res) => {
                    if (+res.errorCode === 0) {
                        res.result.data.map((item, index) => {
                            res.result.data[index].key = index;
                            return res.result.data;
                        })
                        this.setState({
                            // rightLocData: this.mapDataToKey(res.result.data),
                            rightLocData: res.result.data,
                            // data: res.result.Data,
                            //  total: res.result.TotalCount,
                            // rightTabLoading: false
                        })
                    }
                }

            })
        }
        //国际化
        setMessage(name, message) {
            // return this.props.localeProvider ? this.props.localeProvider[name][message] : ''
        }
        findLeftLocData = () => {
            this.getAllDoc(this.state.rowIdHos)
        }
        findRightLocData = () => {
            this.getAuthorizationList(this.state.rowIdHos)
        }
        //批量删除
        moreDel = () => {
            const {selectedRowKeys,selectedRow_right} = this.state
            console.log("selectedRowsRight",selectedRow_right)
            if (this.state.selectedRowKeys_right.length > 0) {
                selectedRow_right &&selectedRow_right .map((item,i)=>{
                    item.userID= sessionStorage.userData ? JSON.parse(sessionStorage.userData).userID : ""
                })
                let data = {
                    params:[
                        {
                            data:selectedRow_right
                        }
                    ]
                }
                $http.post('urlS', this, {
                    code: "01040226",
                    data: data,
                    success: (res) => {
                        if (+res.errorCode === 0) {
                            message.success("删除成功");
                            this.getAuthorizationList();
                            this.getAllDoc()
                            this.setState({  selectedRowKeys_right: [],selectedRow_right:[] });
                        }
                    },
                    error: (error) => {
                        message.error(this.state.localeProvider && this.state.localeProvider.DeptDoctorAddFailed ? this.setMessage('DeptDoctorAddFailed', 'descripts') : "删除失败" + error);
                    }
                })
            } else {
                message.error(this.state.localeProvider && this.state.localeProvider.DeptDoctorPleaseCheck ? this.setMessage('DeptDoctorPleaseCheck', 'descripts') : "请勾选后再点击删除");
            }
        }

        //获取科室类型下拉框
        getLocType = () => {
            let data = {
                params: [{

                }],
            }
            $http.post('urlS', this, {
                code: '05100225',
                data: data,
                success: function (res) {
                    if (+res.errorCode === 0) {
                        this.setState({
                            locTypeData: res.result.Data
                        })
                    }
                }
            })
        }
        handelAdd = () => {
            const {selectedRowKeys,selectedRows} = this.state
            if (this.state.selectedRows.length > 0) {
                selectedRows &&selectedRows .map((item,i)=>{
                    item.locID= sessionStorage.userData ? JSON.parse(sessionStorage.userData).locID : ""
                    item.hospID= sessionStorage.userData ? JSON.parse(sessionStorage.userData).hospID : ""
                    item.userID= sessionStorage.userData ? JSON.parse(sessionStorage.userData).userID : ""
                    item.docID= item.doctorID
                    item.ID = "",
                    item.startDate= moment().format('YYYY-MM-DD') || undefined//创建日期
                    item.stopDate= moment().format('YYYY-MM-DD') || undefined//开始日期
                })
                let data = {
                    params:[
                        {
                            data:selectedRows
                        }
                    ]
                }
                $http.post('urlS', this, {
                    code: "01040225",
                    data: data,
                    success: (res) => {
                        if (+res.errorCode === 0) {
                            message.success("新增成功");
                            this.setState({ selectedRowKeys: [], selectedRowKeys_right: [],leftLocData:[] ,selectrow: '', selectedRows: '' },()=>{
                                this.getAuthorizationList();
                                this.getAllDoc()
                            });
                        }
                    },
                    error: (error) => {
                        message.error(this.state.localeProvider && this.state.localeProvider.DeptDoctorAddFailed ? this.setMessage('DeptDoctorAddFailed', 'descripts') : "新增失败" + error);
                    }
                })
            } else {
                message.error(this.state.localeProvider && this.state.localeProvider.DeptDoctorPleaseCheck ? this.setMessage('DeptDoctorPleaseCheck', 'descripts') : "请勾选后再点击增加");
            }
        }
        onColumnRef = (ref) => {
            this.columnRef = ref;
        }
        onColumnRefDoc = (ref) => {
            this.columnRefDoc = ref;
        }
        onColumnRefLoc = (ref) => {
            this.columnRefLoc = ref;
        }
        // 获取主列表columns---科室医生列表
        getMainTableColumnsLoc = () => {
            let data = {
                params: [{
                    compontName: "DeptDoctor",
                    reactCode: ['DeptDoctor'],
                    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,
                                // render: (text, record) => {
                                //    if (item.code == "status") {
                                //      return (
                                //      <span>{record.status=="Y"?"生效":"失效"}</span>
                                //      )
                                //    }
                                //    return text
                                //  }
                            }
                        }) : '';
                        let filterArr = arr.filter(function (item) { return item.display === 'Y' });
                        this.setState({
                            localeProvider: this.state.userData.language == 'EN' ? res.result.language.EN : res.result.language.CN,
                            colcolumnsLeftTab: filterArr,
                            widthTotalHos: res.totalWidth
                        }, () => {
                            // console.log("localeProvider",this.state.localeProvider)
                        })
                        // console.log("res.totalWidth",res.totalWidth)
                    }
                }
            })
            this.getMainTableColumnsDoc()
        }
        getMainTableColumnsDoc = () => {
            let data = {
                params: [{
                    compontName: "DoctorAssistant",
                    reactCode: ['DoctorAssistant'],
                    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.columnRefDoc.onOpenModel()}>{this.state.userData.language == 'EN' ? item.descripts : item.title}</div>,
                                display: item.display,
                                key: item.seqNo,
                                // render: (text, record) => {
                                //    if (item.code == "status") {
                                //      return (
                                //      <span>{record.status=="Y"?"生效":"失效"}</span>
                                //      )
                                //    }
                                //    return text
                                //  }
                            }
                        }) : '';
                        let filterArr = arr.filter(function (item) { return item.display === 'Y' });
                        let seqArr = {
                            align: "center",
                            widthNum: 140,
                            width: "50px",
                            code: "edit",
                            dataIndex: "edit",
                            title: this.state.localeProvider&&this.state.localeProvider.ResTypeLinkLocOperating?this.setMessage('ResTypeLinkLocOperating', 'descripts'):"操作",
                            display: "Y",
                            render: (value, row, index) => {
                                return (
                                    <span>
                                            <a style={{ color: "#1890FF" }} onClick={(e,)=>this.handleEdit(e,row)}>
                                                {this.state.localeProvider&&this.state.localeProvider.ResTypeLinkLocDelete?
                                                this.setMessage('ResTypeLinkLocDelete', 'descripts'):"编辑"}
                                            </a>
                                    </span>
                                )
                            },
                        }
                        filterArr.push(seqArr)
                        this.setState({
                            localeProvider: this.state.userData.language == 'EN' ? res.result.language.EN : res.result.language.CN,
                            colcolumnsRightTab: filterArr,
                            widthTotalHos: res.totalWidth
                        }, () => {
                            // console.log("localeProvider",this.state.localeProvider)
                        })
                        // console.log("res.totalWidth",res.totalWidth)
                    }
                }
            })
        }
          // 调用子组件的连接事件 -- 编辑
          OnChildrefs = (ref) => {
            this.child = ref
        }
        handleEdit = (e,row) => {
            this.child.showModal(e,row)
        }
        render() {
            const { initRored, rightData, colcolumnsLeftTab, selectedRowKeys, colcolumnsRightTab } = this.state
            const { getFieldDecorator } = this.props.form;
            //科室类型
            let locTypeOp = []
            this.state.locTypeData && this.state.locTypeData.map(item => {
                locTypeOp.push(<Option key={item.id} role={item.descripts + '^' + item.descriptsSPCode} title={item.descripts} value={String(item.id)}>{item.descripts}</Option>)
            })
            const rowSelection = {
                selectedRowKeys,
                onChange: (selectedRowKeys, selectedRows) => {
                    // console.log("selectedRowKeys",selectedRowKeys)
                    this.setState({ selectedRows, selectedRowKeys });
                },
                onSelect: (record, selected, selectedRows) => {
                    this.setState({ selectedRows });
                },
                onSelectAll: (selected, selectedRows, changeRows) => {
                    this.setState({ selectedRows });
                }
            };
            const rowSelection_right = {
                selectedRowKeys: this.state.selectedRowKeys_right,
                onChange: (selectedRowKeys, selectedRowsRight) => {
                    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: selectedRowsRight, selectedRowKeys_right: selectedRowKeys });
                },
                onSelectAll: (selected, selectedRowsRight, changeRows) => {
                    if (selectedRowsRight.length > 0) {
                        this.setState({
                            btnStatus: 'active'
                        })
                    } else {
                        this.setState({
                            btnStatus: 'default'
                        })
                    }
                    this.setState({ selectedRow_right: selectedRowsRight });
                }
            };
            return (
                <Spin spinning={this.state.loadingDom} tip="加载中...">
                    <div className="AddAssistant">
                        <Card style={{ position: "relative" }} title={null}>
                            {/* <Divider className="leftLine" type="vertical"></Divider> */}
                            <div className={"flexBox locDom"}>
                                <div className={"leftTbale"}>
                                    <Row>
                                        <Col span={24} className="title">
                                            <ul style={{ paddingLeft: '15px' }}>
                                                <li style={{ color: '#F7805D' }}><span style={{ color: 'green', fontSize: '16px' }}>{"科室医生列表"}</span></li>
                                            </ul>

                                        </Col>
                                    </Row>
                                    <Row>
                                        <Col span={24} style={paddRightCol}>
                                            <FormItem {...formItemLayoutLoc} label={"科室医生"}>
                                                {getFieldDecorator('searchLoc', {
                                                    initialValue: undefined,
                                                    rules: [{ required: false, message: '' }],
                                                })(
                                                    <Input placeholder={"描述/代码回车搜索"} onPressEnter={this.findLeftLocData}></Input>
                                                )}
                                            </FormItem>
                                            {/* <DigitalKeyboard  ref={this.onBoardRef} setValue={this.setValue}></DigitalKeyboard> */}
                                        </Col>
                                    </Row>
                                    {/* <Row style={{ textAlign: "right", marginTop: "-10px" }}>
                                        <Col span={24} style={{ marginBottom: "4px", }}>
                                            <Button type="primary" onClick={this.findLeftLocData}>{ "查询"}</Button>
                                        </Col>
                                    </Row> */}
                                    <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 + 2  + 'px', overflow: "auto" }}
                                        // scroll={{ x: 240, y: this.state.windowheight - 380 - 40 }}
                                        rowSelection={rowSelection}
                                    />
                                    <ColumnAuthoritysModel
                                        clientWidth='800px'
                                        compontName='DeptDoctor'
                                        configType="C"
                                        onRef={this.onColumnRefLoc}
                                        reloadData={this.getMainTableColumnsLoc}
                                    />
                                </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} className="title">
                                            <ul style={{ paddingLeft: '15px' }}>
                                                <li style={{ color: '#42B983' }}><span style={{ color: 'green', margintop: '1rem', fontSize: '16px' }}>{"已添加助理医生列表"}</span></li>
                                            </ul>

                                        </Col>
                                    </Row>
                                    <Row>
                                        <Col span={24} style={paddRightCol}>
                                            <FormItem {...formItemLayoutTT} label={this.state.localeProvider && this.state.localeProvider.DeptDoctorDepartment ? this.setMessage('DeptDoctorDepartment', 'descripts') : "助理"}>
                                                {getFieldDecorator('searchRightLoc', {
                                                    initialValue: undefined,
                                                    rules: [{ required: false, message: '' }],
                                                })(
                                                    <Input placeholder={this.state.localeProvider && this.state.localeProvider.DeptDoctorDescriptionCode ? this.setMessage('DeptDoctorDescriptionCode', 'descripts') : "描述/代码回车搜索"} onPressEnter={this.findRightLocData}></Input>
                                                )}
                                            </FormItem>
                                        </Col>
                                    </Row>
                                    <Row style={{ textAlign: "left", }}>
                                        <Col span={24} style={{ marginBottom: "4px", marginTop: "-10px" }}>
                                            {
                                                this.state.selectedRowKeys_right && this.state.selectedRowKeys_right.length == 0? <Button disabled
                                                style={{ background: "#fff", border: "0", color: "#cfcfcf"}}
                                                type="primary" onClick={this.moreDel} >{this.state.localeProvider && this.state.localeProvider.DeptDoctorDeleteInBatches ?
                                                 this.setMessage('DeptDoctorDeleteInBatches', 'descripts') : "批量删除"}</Button>:
                                                 <Popconfirm title={this.state.localeProvider&&this.state.localeProvider.ResTypeLinkLocWhetherToDelete?this.setMessage('ResTypeLinkLocWhetherToDelete', 'descripts'):"是否要删除"} onConfirm={(e) => this.moreDel()}>
                                                 <Button
                                                         style={{ background: "#fff", border: "0", color:"red" }}
                                                         type="primary">{this.state.localeProvider && this.state.localeProvider.DeptDoctorDeleteInBatches ?
                                                          this.setMessage('DeptDoctorDeleteInBatches', 'descripts') : "批量删除"}</Button>
                                             </Popconfirm>
                                            }
                                        
                                          
                                        </Col>
                                    </Row>
                                    <Table
                                        // style={{ height: this.state.windowheight - 380 + 'px', marginTop: '1.18rem' }}
                                        columns={colcolumnsRightTab}
                                        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 - 24 + 'px', overflow: "auto" }}
                                    // scroll={{ x: 440, y: this.state.windowheight - 380 - 40 }}
                                    />
                                    <ColumnAuthoritysModel
                                        clientWidth='800px'
                                        compontName='DoctorAssistant'
                                        configType="C"
                                        onRef={this.onColumnRefDoc}
                                        reloadData={this.getMainTableColumnsDoc}
                                    />
                                     <EditAssistantModal getAuthorizationList={this.getAuthorizationList} OnChildrefs={this.OnChildrefs}></EditAssistantModal>
                                </div>
                            </div>
                        </Card>
                    </div>
                </Spin>
            )
        }
    })
export default AddAssistant    