/*
 * 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 CommonPagination from 'components/pagination/index';
import ColumnAuthoritysModel from 'pages/columnAuthority/ColumnAuthoritysModel';

const FormItem = Form.Item;
const Option = Select.Option;
const paddRightCol = {
    paddingRight: "0px"
}
const formItemLayout = { // label 和input宽度
    labelCol: { span: 8 },
    wrapperCol: { span: 14 },
}
const formItemLayoutSearch = {
    labelCol: { span: 3 },
    wrapperCol: { span: 21 },
}
const ServiceGroupDoctors = Form.create()(
    class ServiceGroupDoctors 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.onDoctord(this)
            // 初始化设置table的高度以及表体的高度
            document.querySelector('.docDom .ant-table-body').style.height = (sessionStorage.userData&&JSON.parse(sessionStorage.userData).defaultMenuType==1 ?store.getState().tableHeight.y + 49 + 'px' : store.getState().tableHeight.y + 49 + 'px');
            document.querySelector('.docDom .ant-table-body').style.overflow = "auto";
            this.getMainTableColumnsDoc()
        }
        onColumnRefHos = (ref) => {
            this.columnRefHos = ref;
        }
       
        // 获取主列表columns---医生列表
        getMainTableColumnsDoc = () => {
            let data = {
                params: [{
                    compontName: "CureServiceGroupDoc",
                    reactCode: ['CureServiceGroupDoc'],
                    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.columnRefHos.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.CureServiceGroupDocOperating ? this.setMessage('CureServiceGroupDocOperating', 'descripts') : "操作",
                            display: "Y",
                            render: (value, row, index) => {
                                if (row.NotDelReason == "") {
                                    return (
                                        <span>
                                            <Popconfirm title={this.state.localeProvider && this.state.localeProvider.CureServiceGroupDocWhetherToDelete ? this.setMessage('CureServiceGroupDocWhetherToDelete', 'descripts') : "是否要删除"} onConfirm={() => this.toggleEditableDoc(row)}>
                                                <Button type="primary" style={{ background: "transparent", border: "0", color: "red" }}>{this.state.localeProvider && this.state.localeProvider.CureServiceGroupDocDelete ? this.setMessage('CureServiceGroupDocDelete', 'descripts') : "删除"}</Button>
                                            </Popconfirm>
                                        </span>
                                    )
                                } else {
                                    return (
                                        <Button type="primary" style={{ background: "transparent", border: "0", color: "##aaa" }} disabled title={row.NotDelReason} >{this.state.localeProvider && this.state.localeProvider.CureServiceGroupDocDelete ? this.setMessage('CureServiceGroupDocDelete', 'descripts') : "删除"}</Button>
                                    )
                                }
                            },
                        }
                        filterArr.push(seqArr)
                        this.setState({ localeProvider: this.state.userData.language == 'EN' ? res.result.language.EN : res.result.language.CN, columnsDoc: filterArr, widthTotalHos: res.totalWidth })
                        // console.log("res.totalWidth",res.totalWidth)
                    }
                }
            })
        }
      
       
        // 显示分页总条数
        showTotal(total) {
            return `共 ${total} 条`;
        }
      
        // 修改page和pageSize 跳转至---
        onChangeDoc = (e, pageSize) => {
            this.setState({ pageDoc: e, pageSizeDoc: this.state.pageSizeDoc }, () => {
                // 重新调用查询方法
                this.getToDoc(this.props.rowIds)
            })
        }
        //下拉选择页数
        onShowSizeChangeDoc = (page, pageSize) => {
            this.setState({ pageDoc: 1, pageSizeDoc: pageSize, searchDoc: "search" }, () => {
                // 重新调用查询方法
                this.getToDoc(this.props.rowIds)
            })
        }
        //获取医生列表
        getToDoc = (id, e) => {
            const { pageSizeDoc, pageDoc, parms } = this.state
            let data = {}
            data = {
                params: [{
                    // hospID: parms && parms.hospId ? parms.hospId : "",
                    // locID: parms && parms.locId ? parms.locId : "",
                    groupID: id || "",
                }],
                pagination: [{
                    pageSize: pageSizeDoc,
                    currentPage: pageDoc,
                }]
            }
            $http.post('urlS', this, {
                code: '01040157',
                data: data,
                success: function (res) {
                    if (+res.errorCode === 0) {
                        this.setState({
                            sourceDocData: res.result.data,
                            totalDoc: res.result.TotalCount,
                        })
                    }
                }
            })
        }
        //加入医生
        addDoc = () => {
            if (this.props.form.getFieldValue("docID") && this.props.form.getFieldValue("docID")) {
                let data = {}
                data = {
                    params: [{
                        updateUserID: JSON.parse(sessionStorage.userData).userID || '',
                        createUserID: JSON.parse(sessionStorage.userData).userID || '',
                        doctorData: this.props.form.getFieldValue("docID") || '',
                        groupID: this.props.rowIds || "",
                        hospID: this.props.hosID || "",
                        startDate: moment().format('YYYY-MM-DD'),//生效日期
                        createDate: moment().format('YYYY-MM-DD'),
                    }],
                }
                $http.post('urlS', this, {
                    code: '01040158',
                    data: data,
                    success: function (res) {
                        if (+res.errorCode === 0) {
                            message.success(this.state.localeProvider && this.state.localeProvider.CureServiceGroupDocJoinedSuccessfully ? this.setMessage('CureServiceGroupDocJoinedSuccessfully', 'descripts') : "加入成功");
                            this.props.form.setFieldsValue({ hos: undefined })
                            this.getToDoc(this.props.rowIds)
                            this.getDocData(this.props.rowIds,this.props.locId)
                        }
                    }
                })
            } else {
                message.warning(this.state.localeProvider && this.state.localeProvider.CureServiceGroupDocPleaseChooseoctor ? this.setMessage('CureServiceGroupDocPleaseChooseoctor', 'descripts') : "请选择医生")
            }
        }
        //删除医生
        toggleEditableDoc = (record) => {
            let data = {}
            data = {
                params: [{
                    updateUserID: JSON.parse(sessionStorage.userData).userID || '',
                    // ResTypeId:this.state.rowIds,
                    ID: record.ID,
                }],
            }
            $http.post('urlS', this, {
                code: '01040159',
                data: data,
                success: function (res) {
                    if (+res.errorCode === 0) {
                        message.success(this.state.localeProvider && this.state.localeProvider.CureServiceGroupDocSuccessfullyDeleted ? this.setMessage('CureServiceGroupDocSuccessfullyDeleted', 'descripts') : "删除成功");
                        this.getToDoc(this.props.rowIds)
                        this.getDocData(this.props.rowIds,this.props.locId)
                    }
                }
            })
        }
      
        //医生数据 loc---
        getDocData = (id,locId) => {
            let datas = {}
            datas = {
                params: [{
                    // updateUserID: JSON.parse(sessionStorage.userData).userID || '',
                    groupID: id || "",
                    locID:locId||"",
                }],
            }
            $http.post('urlS', this, {
                code: '01040198',
                data: datas,
                success: function (res) {
                    if (+res.errorCode === 0) {
                        this.props.form.setFieldsValue({ docID: undefined })
                        this.setState({
                            docArr: res.Data,
                        })
                    }
                }
            })
        }
        /*
        状态重置
        新增/查询服务组-- 服务组列表取消选中
        服务组列表取消选中-- 右侧服务组医生 服务组项目重置 服务组列表选中id置空
        服务组列表切换选中-- 右侧服务组医生 服务组项目重置
        右侧服务组医生列表 新增-- 服务组医生列表选中取消 服务组项目置空
        右侧服务组医生列表 切换选中--  服务组项目置空
        // 右侧服务组医生列表 取消选中--  服务组项目置空
        右侧服务项目列表 查询-- 服务组项目列表置空 取消已选中
        右侧已选服务项目列表 查询-- 已选服务组项目列表置空 取消已选中
        */
        handleRestListCancel = () => {
            this.props.form.setFieldsValue({ docID: undefined, subDr: undefined, searchLoc: undefined, searchRightItem: undefined })
            this.setState({
                 parms: "",
                rowIdHos: "", rowIdtoHosId: "", sourceDocData: [], searchDoc: "search", pageDoc: 1,
                selectedRowKeys: [], selectedRowKeys_right: [], selectedData: [], selectrow: '', selectedRows: '', leftLocData: [], rightLocData: []
            });
        }
        handleRestListchange = () => {
            this.props.form.setFieldsValue({ docID: undefined,})
            this.setState({
                rowIdHos: "", sourceDocData: [], searchDoc: "search", pageDoc: 1,
            });
        }
        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: []
            });
        }
        handleChangeDoc=()=>{

        }
        //国际化
        setMessage(name, message) {
            return this.state.localeProvider ? this.state.localeProvider[name][message] : ''
        }

        render() {
            const { getFieldDecorator } = this.props.form;
            const { columnsDoc, } = this.state;
            //医生
            let docOp = []
            this.state.docArr && this.state.docArr.map((item) => {
                docOp.push(<Option key={item.doctorID} value={String(item.doctorID)}>{item.descripts}</Option>)
            })
           
            return (
                <div style={{ padding: '4px 2px' }} className="serviceGroupDom">
                    <Row>
                        <Col span={24}>
                                <Form>
                                    <Row>
                                        <Col span={12} style={paddRightCol}>
                                            <FormItem {...formItemLayoutSearch} label={this.state.localeProvider && this.state.localeProvider.CureServiceGroupDocDoctor ? this.setMessage('CureServiceGroupDocDoctor', 'descripts') : "医生"}>
                                                {getFieldDecorator('docID', {
                                                    initialValue: undefined,
                                                    rules: [{ required: true, message: '请选择至少一个医生'}],
                                                })(
                                                    <Select
                                                    mode="multiple"
                                                    onChange={this.handleChangeDoc}
                                                    >
                                                        {docOp}
                                                    </Select>
                                                )}
                                            </FormItem>
                                        </Col>
                                        <Col span={2} style={{ paddingLeft: "10px", paddingRight: "0px", width: "5%" }}>
                                            <FormItem  {...formItemLayout}>
                                                {getFieldDecorator('searchBtn', {
                                                    initialValue: undefined,
                                                    rules: [{ required: false, message: '' }],
                                                })(
                                                    <Button onClick={this.addDoc} disabled={!this.props.rowIds} style={{ background: 'rgba(66,185,131,1)', color: '#fff' }}>{this.state.localeProvider && this.state.localeProvider.CureServiceGroupDocJoin ? this.setMessage('CureServiceGroupDocJoin', 'descripts') : "加入"}</Button>
                                                )}
                                            </FormItem>
                                        </Col>
                                    </Row>
                                    <div className="docDom">
                                        <Table
                                            // scroll={{ x: 1160, y: store.getState().tableHeight.y + 156 }}
                                            columns={columnsDoc}
                                            dataSource={this.state.sourceDocData}
                                            pagination={false}
                                            rowKey={record => record.key}
                                            // onRow={this.onClickRowHos}
                                            // rowClassName={this.setRowClassNamesHos}
                                            bordered
                                            style={{ height:((sessionStorage.userData&&JSON.parse(sessionStorage.userData).defaultMenuType==1 ?store.getState().tableHeight.y +49 + 'px' : store.getState().tableHeight.y + 49 + 'px'))  }}
                                        />
                                        <CommonPagination size={this.state.sizeDoc} page={this.state.pageDoc} current={this.state.pageDoc} total={this.state.totalDoc} search={this.state.searchDoc}
                                            onShowSizeChange={this.onShowSizeChangeDoc.bind(this)} complete={true} dataSource={this.state.sourceDocData}
                                            onChange={this.onChangeDoc.bind(this)} />
                                    </div>
                                    <ColumnAuthoritysModel
                                        clientWidth='800px'
                                        compontName='CureServiceGroupDoc'
                                        configType="C"
                                        onRef={this.onColumnRefHos}
                                        reloadData={this.getMainTableColumnsDoc}
                                    />
                                </Form>
                        </Col>
                    </Row>
                </div>

            )
        }
    })
export default ServiceGroupDoctors    