/*
 * Creator:     ML
 * CreatDate:   2019-10-08
 * descripts：医嘱子类设置 关联医院
 * */
import React from 'react';
import moment from 'moment';
import { Form, Row, Col, Input, Table, Select, DatePicker, Button, Modal, message, Divider, Tooltip, Icon, Checkbox, Radio, Badge, Fragment, Pagination, Popconfirm, Switch } from 'antd';
import { $http } from '../../../containers/config/https';
import store from '../../../store';
// import './style/index.less';
import CommonPagination from 'components/pagination';


const paddRightCol = {
    paddingRight: "0px"
}
const formItemLayoutType = {
    labelCol: { span: 9 },
    wrapperCol: { span: 15 }
}

const FormItem = Form.Item;
const Option = Select.Option;
const SubclassAffHospital = Form.create()(
    class SubclassAffHospital extends React.Component {
        cacheOriginData = {};
        constructor() {
            super()
            this.state = {
                leftData: [],//左边查询到的表格数据
                rightData: [],//右边双击后的表格数据
                rightUnitDr: [],
                findInfo: '请输入查询条件',//查询提示信息
                visible: false,//添加/修改医嘱子类表维护弹窗显示
                isMod: -1,//是否点击编辑
                ordTempletID: "",//编辑行id
                ordTempletDesc: "",//模板名称
                ordTempletAlias: "",//模板别名
                ordTempletCat: "",//医嘱分类
                rowId: "",//表格行id 设置颜色
                ordShow: false,//当前模板显示
                baseParentType: [],//添加医嘱子类表维护类型选择  上级分类
                baseUnit: [],//添加医嘱明细单位类型选择
                selectedData: [],//医嘱明细选中
                selectedId: [],//医嘱明细选中
                btnStatus: true,
                selectedRow_right: [],
                selectrow: "",//获取行 当前选中行
                deteleOrdId: "",//选中删除行
                leftDisRow: false,
                ordTempId: 1,//医嘱子类选择值
                isAdd: false,//是否点击添加
                ordDetailValue: "",//医嘱明细输入值
                ordDetailData: [],//医嘱项表格数据
                OrdDaShow: false,//医嘱项表格数据显隐
                OrdDaRowId: "",//医嘱项表格行id
                OrdCanType: "",//医嘱项允许录入类型
                editDis: true,//未选中

                nowRowID: "",//医嘱明细表格行id

                initRored: {},//原始右侧表格行
                ordTempletDetailItemDesc: "",
                ordTempletDetailQty: "",
                ordTempletDetailQtyUnitDr: "",
                ordTempletDetailID: "",
                disAdd: false,//是否可新增
                newOpen: [],
                leftData: [],


                searchCategoryName: "",//输入左侧搜索分类名称
                checkAll: false,//左侧全选
                checkedList: [],//左侧可选项
                plainOptions: [],
                rightTopTableData: [],//右上小表格数据
                cbiD: "",//自定义分类 区分触发场景
                radioValue: 0,//
                rowRightId: "",//右上小表格选中
                leftInfo: {},//左侧信息回显
                rightSearchInfo: "",//右侧搜索
                canDeleteStatus: true,//能否点击删除


         
                //右侧表格
                totalRight: 0,
                pageRight: 1,
                pageSizeRight: 10,
                checkedRight: true,
                baseTempType: [],//添加医嘱子类表维护类型选择
                topInfo: {},
                centerInfo: {},
                isDefalult:false,
                canSave:true,
                locArr:[],
                publicLocArr:[],
                disSave:true,
                size:"small",
                search:""
            }
            this.detailDeInput = React.createRef();
        }
        componentDidMount = () => {
            this.props.onHopChild(this)
            // 初始化设置table的高度以及表体的高度
            if (document.querySelector('.ant-table-body')) {
                document.querySelector('.subAffHosDom .ant-table-body').style.height = store.getState().tableHeight.y-231 + 'px'
                document.querySelector('.subAffHosDom .ant-table-body').style.overflow = 'auto'
            }
            this.getHopSelect()
        }
       //获取医院下拉框
       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
                })
              }
            }
          })
    }
    initPagination=()=>{
        this.setState({
            pageRight:1,
            search:"search"
        })
    }
      //重置页数之后 再次调起查询
      initSearch=(orderSubCatID)=>{
        this.setState({
            pageRight:1,
            search:"search"
        },()=>{
            this.getSubLocDatas(orderSubCatID)
        })
    }
    //根据医嘱子类ID获取关联医院
    getSubLocDatas = (orderSubCatID) => {
        const { pageRight, pageSizeRight } = this.state
        let data = {}
        data = {
            params: [{
                orderSubCatID: orderSubCatID&&orderSubCatID?orderSubCatID:this.state.orderSubCatID,
                status:this.state.checkedRight==true?"Y":"N"
            }],
            pagination: [{
                pageSize: parseInt(pageSizeRight),
                currentPage: parseInt(pageRight),
            }]
        }
        $http.post('urlS', this, {
            code: '05100230',
            data: data,
            success: function (res) {
                if (+res.errorCode === 0 && res.result.Data) {
                    res.result.Data.map((item, i) => {
                        res.result.Data.key == Number(i)
                    })
                    this.setState({
                        rightData: res.result.Data,
                        totalRight: res.result.TotalCount
                    })
                }
                // if(res.result.Data&&res.result.Data.length==0&&res.result.TotalCount>0){
                //     let prevPage = this.state.page - 1
                //     this.onChangeRight(prevPage, this.state.pageSize)
                //   }
            }
        })
    }
        //右侧
        // 显示分页总条数
        showTotalRight(total) {
            return `共 ${total} 条`;
        }
        // // 修改page和pageSize 跳转至---
        // onChangeRight = (e) => {
        //     this.setState({ pageRight: e, pageSizeRight: this.state.pageSizeRight }, () => {
        //         // 重新调用查询方法
        //         this.getSubLocDatas()
        //     })
        // }
        // // 页码改变的回调，参数是改变后的页码及每页条数
        // PageChangeRight = (e,) => {
        //     this.setState({ pageRight: e, pageSizeRight: this.state.pageSizeRight }, () => {
        //         // 重新调用查询方法
        //         this.getSubLocDatas()
        //     });
        // }
          // 修改page和pageSize 跳转至---
          onChangeRight = (page,pageSize) => {
            this.setState({ pageRight: page, pageSizeRight: this.state.pageSizeRight }, () => {
                // 重新调用查询方法
                this.getSubLocDatas()
            })
        }
        // 页码改变的回调，参数是改变后的页码及每页条数
        PageChangeRight = (page,pageSize) => {
            this.setState({ pageRight: page, pageSizeRight: this.state.pageSizeRight }, () => {
                // 重新调用查询方法
                this.getSubLocDatas()
            });
        }
        //下拉选择页数
        onShowSizeChangeRight = (page, pageSize) => {
            this.setState({ pageRight: 1, pageSizeRight: pageSize,search:"search" }, () => {
                // 重新调用查询方法
                this.getSubLocDatas()
            })
        }
        //点击是否生效 --右侧
        changeCheckedRight = (e) => {
            this.setState({
                checkedRight: e.target.checked,
                pageRight: 1,
            }, () => {
                this.getSubLocDatas()
            })
        }
        //设置点击row颜色 -右侧表格
        setRowClassNames = (record) => {
            return record.subCatHosID === this.state.rowIds ? 'clickRowStyle' : '';
        }
        
        //点击右侧表格行
        onClickRightRow = (record) => {
            const { rightData } = this.state
            return {
                onClick: () => {
                    this.setState({
                        centerInfo: {},
                    })
                    if (record.subCatHosID) {
                        if (this.state.rowIds === "") {
                            this.setState({
                                rowIds: record.subCatHosID,
                                centerInfo: record,
                            });
                        } else {
                            if (this.state.rowIds !== record.subCatHosID) {
                                this.setState({
                                    rowIds: record.subCatHosID,
                                    centerInfo: record,
                                });
                            } else {
                                this.setState({
                                    rowIds: "",
                                    centerInfo: {},
                                });
                                this.props.form.resetFields()
                                // this.props.form.resetFields();
                            }
                        }
                    }
                },
            }
        }
        handleRightCancel=(i)=>{
            if(i=="1"){
                this.setState({
                    rowIds:""
                })
            }
            this.setState({
                centerInfo:{},
                isDefalult:false
            })
            this.props.form.resetFields()
        }

        handleRightOk = () => {
            this.props.form.validateFields((err, values) => {
                if (!err) {
                    let data = {}
                    if(this.state.rowIds){
                       data = {
                        params: [{
                            updateUserID: sessionStorage.userData ? JSON.parse(sessionStorage.userData).userID : "",
                            subCatHosID: this.state.rowIds,
                            hospID: values.getHop,
                            startDate: values.getDateFrom ? moment(values.getDateFrom).format('YYYY-MM-DD') : "",
                            stopDate: values.getDateTo ? moment(values.getDateTo).format('YYYY-MM-DD') : "",
                        }],
                    }  
                    }else{
                       data = {
                        params: [{
                            updateUserID: sessionStorage.userData ? JSON.parse(sessionStorage.userData).userID : "",
                            orderSubCatID:this.state.orderSubCatID,
                            subCatHosID: this.state.rowIds || "",
                            hospID: values.getHop,
                            startDate: values.getDateFrom ? moment(values.getDateFrom).format('YYYY-MM-DD') : "",
                            stopDate: values.getDateTo ? moment(values.getDateTo).format('YYYY-MM-DD') : "",
                        }],
                    }  
                    }
                    $http.post('urlS', this, {
                        code: '05100231',
                        data: data,
                        success: function (res) {
                            if (+res.errorCode === 0) {
                                if(this.state.rowIds){
                                    message.success("修改成功")
                                    if ((values.getDateFrom && values.getDateFrom) && (values.getDateTo && values.getDateTo)) {
                                        if (moment(values.getDateTo).format('YYYYMMDD') < moment().format('YYYYMMDD')) {
                                            this.setState({
                                                checkedRight:false
                                            })
                                            this.getSubLocDatas(this.state.orderSubCatID)
                                            return
                                        }
                                    }
                                    this.setState({
                                        checkedRight:true
                                    })
                                    this.getSubLocDatas(this.state.orderSubCatID)
                                }else{
                                    message.success("添加成功")
                                    this.props.form.resetFields()
                                    let lastPage = Math.ceil((this.state.totalRight + 1) / this.state.pageSizeRight)
                                    this.setState({
                                        pageRight:lastPage
                                    },()=>{
                                        if ((values.getDateFrom && values.getDateFrom) && (values.getDateTo && values.getDateTo)) {
                                            if (moment(values.getDateTo).format('YYYYMMDD') < moment().format('YYYYMMDD')) {
                                                this.setState({
                                                    checkedRight:false
                                                })
                                                this.getSubLocDatas(this.state.orderSubCatID)
                                                return
                                            }
                                        }
                                        this.setState({
                                            checkedRight:true
                                        })
                                        this.getSubLocDatas(this.state.orderSubCatID)
                                    })
                                   
                                }
                            }
                        }
                    })
                }
            })
        }

     //删除医嘱子类关联医院
     delate=(e,record)=>{
        let data = {}
        data = {
            params: [{
                updateUserID: sessionStorage.userData ? JSON.parse(sessionStorage.userData).userID : "",
                subCatHosID:record.subCatHosID,
            }],
        }
        $http.post('urlS', this, {
            code: '05100232',
            data: data,
            success: function (res) {
                if (+res.errorCode === 0) {
                    message.success("删除成功")
                    this.getSubLocDatas(this.state.orderSubCatID)
                }
            }
        })
    }
       //初始化信息
       initData = () => {
        this.props.form.resetFields()
        this.setState({
            centerInfo:{},
            rightData:[],
            disSave:true
        })
    }
    //可保存 编辑状态
    canSaveTab=(subID)=>{
        this.setState({
            disSave:false,
            orderSubCatID:subID,
        })
        // this.getSubLocDatas(orderSubCatID)
    }
        render() {
            const { getFieldDecorator } = this.props.form;
            let {  baseUnit, tempChildDis, OrdDaShow, topInfo, centerInfo } = this.state
              //右侧关联医院表格
              const rightColumns = [
                {
                    align: "center",
                    title: '医院',
                    dataIndex: 'hospDesc',
                    key: '0',
                    editable: true,
                    render: (text, record, index) => {
                        return text;
                    },
                },  {
                    align: "center",
                    title: '状态',
                    dataIndex: 'status',
                    key: '4',
                    editable: true,
                    render: (value, row, index) => {
                        if (value == "Y") {
                            return (
                                "生效"
                            )
                        } else {
                            return (
                                "失效"
                            )
                        }
                    },
                },
                {
                    title: '操作',
                    dataIndex: '',
                    key: '6',
                    align: "center",
                    width: 200,
                    render: (text, record, index) => {
                            return (
                                <span>
                                <Popconfirm title="删除不可恢复，你确定要删除吗?" onCancel={this.handlePopcon} onConfirm={(e) => this.delate(e, record)} >
                                    <span className='span' style={{ cursor: "pointer" }} style={{ color: 'rgba(240,65,52,1)' }}>删除</span>
                                </Popconfirm>
                            </span>
                            )


                    }
                }
            ];
                //医院
                let hosOp = []
                this.state.hospArr && this.state.hospArr.map((item) => {
                    hosOp.push(<Option key={item.id}  value={String(item.id)}>{item.descripts}</Option>)
                })
            return (
                <div className="subAffHosDom">
                    <Row gutter={60} className="majorCategoriesDom" style={{ marginRight: "0" }}>
                        <Col span={24} style={{ paddingLeft: "6px", paddingRight: "0" }}>
                                <div>
                                    <Form>
                                    <Row gutter={60} style={{margin:"0"}}>
                                            <Col span={5} style={paddRightCol}>
                                                <FormItem {...formItemLayoutType} label='医院'>
                                                    {getFieldDecorator('getHop', {
                                                        initialValue: centerInfo.hospID && centerInfo.hospID ? centerInfo.hospID : undefined,
                                                        rules: [{ required: true, message: '请选择医院' }],
                                                    })(
                                                        <Select
                                                            onSelect={this.handleStatus}
                                                        >
                                                            {hosOp}
                                                        </Select>
                                                    )}
                                                </FormItem>
                                            </Col>
                                            <Col span={6} style={paddRightCol}>
                                                <FormItem label='生效日期' {...formItemLayoutType}>
                                                    {getFieldDecorator('getDateFrom', {
                                                        initialValue: centerInfo.startDate ? moment(centerInfo.startDate, "YYYY-MM-DD"):moment(),
                                                        rules: [{ required: true, message: '请选择生效日期' }],
                                                    })(
                                                        <DatePicker style={{ width: '100%' }} placeholder={'生效日期'} disabledDate={(curDate) => {
                                                            return curDate && curDate > moment().endOf('day');
                                                        }} />
                                                    )}
                                                </FormItem>
                                            </Col>
                                            <Col span={6} style={paddRightCol}>
                                                <FormItem label='失效日期' {...formItemLayoutType}>
                                                    {getFieldDecorator('getDateTo', {
                                                        initialValue: centerInfo.stopDate ? moment(centerInfo.stopDate, "YYYY-MM-DD"):undefined,
                                                        rules: [{ required: false, message: '' }],
                                                    })(
                                                        <DatePicker style={{ width: '100%' }} placeholder={'失效日期'} disabledDate={(curDate) => {
                                                            return curDate < moment(this.props.form.getFieldValue('getDateTo')).format('YYYY-MM-DD');
                                                        }} />
                                                    )}
                                                </FormItem>
                                            </Col >
                                            <Col span={5} style={{ textAlign: "center", lineHeight:"40px" }}>
                                            {/* disabled={this.state.canSave&&this.state.rowId==""} */}
                                                <Button key="submitc" type="primary" style={{margin:"0 4px"}}  onClick={this.handleRightCancel}>清空</Button>
                                                <Button key="submits" type="primary" disabled={this.state.disSave} onClick={this.handleRightOk}>保存</Button>
                                                </Col>
                                        </Row>
                                    </Form>
                                </div>
                                <Col span={24} style={{padding:"0"}}>   
                                <Checkbox checked={this.state.checkedRight} disabled={ this.state.rightData && this.state.rightData.length==0} onChange={this.changeCheckedRight} style={{ marginRight: "50px", float: "right" }}>仅显示生效</Checkbox>
                                </Col>
                                <Table
                                    columns={rightColumns}
                                    pagination={false}
                                    bordered
                                    rowClassName={this.setRowClassNames}
                                    onRow={this.onClickRightRow}
                                    dataSource={this.state.rightData}
                                    className="clearBackground"
                                    style={{height:store.getState().tableHeight.y-216 + 'px'}}
                                />
                                  <CommonPagination size={this.state.size} page={this.state.pageRight} current={this.state.pageRight} total={this.state.totalRight} search={this.state.search}
                                        onShowSizeChange={this.onShowSizeChangeRight.bind(this)} complete={true} dataSource={this.state.rightData}
                                        onChange={this.PageChangeRight.bind(this)} />
                                {/* {
                                    this.state.rightData && this.state.rightData.length > 0 ? <Pagination
                                        size="small"
                                        showQuickJumper
                                        showSizeChanger
                                        defaultCurrent={1}
                                        current={this.state.pageRight}
                                        total={this.state.totalRight}
                                        onChange={this.PageChangeRight}
                                        // onRow={this.selectID}
                                        onShowSizeChange={this.onShowSizeChangeRight}
                                        style={{ textAlign: "right", marginTop: '10px' }}
                                        showTotal={() => this.showTotalRight(this.state.totalRight)}
                                    /> : ""
                                } */}
                        </Col>
                    </Row>
                </div>
            )
        }
    })
export default SubclassAffHospital