/*
 * Creator:     ML
 * CreatDate:   2019-12-11
 * 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';
import ColumnAuthoritysModel from 'pages/columnAuthority/ColumnAuthoritysModel';



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

const FormItem = Form.Item;
const Option = Select.Option;
const PrescriptClassification = Form.create()(
    class PrescriptClassification extends React.Component {
        cacheOriginData = {};
        constructor() {
            super()
            this.state = {
                sizeRight:"small",
                search:"",
                pageRight:1,
                pageSizeRight:10,
                checkedRight:true
            }
        }
        componentDidMount = () => {
            this.props.prescriptClass(this)
            // 初始化设置table的高度以及表体的高度
            if (document.querySelector('.ant-table-body')) {
                document.querySelector('.ant-table-body').style.height = store.getState().tableHeight.y-50 + 'px'
            }
            this.getHopSelect()
            this.getMainTableColumns()
            this.getPoison()
        }
         //动态表头
         onColumnRef = (ref) => {
            this.columnRef = ref;
          }
        // 获取主列表columns
        getMainTableColumns = () => {
            let data = {
                params: [{
                    compontName: "PrescTypeLinkPoison", 
                    reactCode: ['PrescTypeLinkPoison'],
                    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,
                                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: "操作",
                            display: "Y",
                            render: (value, row, index) => {
                                return (
                                    <span>
                                            <Popconfirm title="删除不可恢复，你确定要删除吗?" onCancel={this.handlePopconfirm} onConfirm={(e) => this.delate(e, row)} >
                                                <span className='span' style={{ cursor: "pointer" }} style={{ color: 'rgba(240,65,52,1)' }}>删除</span>
                                            </Popconfirm>
                                    </span>

                                )
                            },
                        }
                        filterArr.push(seqArr)
                        this.setState({ rightColumns: filterArr,widthTotal: res.totalWidth })
                        // console.log("res.totalWidth",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
                })
              }
            }
          })
    }
     //获取管制分类下拉框
     getPoison = () => {
        let data = {
            params: [{
              
            }],
          }
          $http.post('urlS', this, {
            code: '02050003',
            data: data,
            success: function (res) {
              if (+res.errorCode === 0) {
                this.setState({
                    poisonArr:res.result
                })
              }
            }
          })
    }
    initPagination=()=>{
        this.setState({
            pageRight:1,
            search:"search" 
        })
    }
    //重置页数之后 再次调起查询
    initSearch=(prescriptsID)=>{
        this.setState({
            pageRight:1,
            search:"search"
        },()=>{
            this.getSubLocDatas(prescriptsID)
        })
    }
    //根据规则类型ID获取管制分类
    getSubLocDatas = (prescriptsID) => {
        this.props.form.resetFields()
        this.setState({
            prescriptsID,
            rowIds:"",
            centerInfo:{}
        },()=>{
        const { pageRight, pageSizeRight } = this.state
        let data = {}
        data = {
            params: [{
                prescTypeID: prescriptsID&&prescriptsID?prescriptsID:this.state.prescriptsID,
                status:this.state.checkedRight==true?"Y":"N"
            }],
            pagination: [{
                pageSize: parseInt(pageSizeRight),
                currentPage: parseInt(pageRight),
            }]
        }
        $http.post('urlS', this, {
            code: '03050157',
            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(this.state.prescriptsID)
            })
        }
        // 页码改变的回调，参数是改变后的页码及每页条数
        PageChangeRight = (e,) => {
            this.setState({ pageRight: e, pageSizeRight: this.state.pageSizeRight }, () => {
                // 重新调用查询方法
                this.getSubLocDatas(this.state.prescriptsID)
            });
        }
        //下拉选择页数
        onShowSizeChangeRight = (page, pageSize) => {
            this.setState({ pageRight: 1, pageSizeRight: pageSize,search:"search" }, () => {
                // 重新调用查询方法
                this.getSubLocDatas(this.state.prescriptsID)
            })
        }
        //点击是否生效 --右侧
        changeCheckedRight = (e) => {
            this.setState({
                checkedRight: e.target.checked,
                pageRight: 1,
                search:"search" 
            }, () => {
                this.getSubLocDatas(this.state.prescriptsID)
            })
        }
        //设置点击row颜色 -右侧表格
        setRowClassNames = (record) => {
            return record.ID === this.state.rowIds ? 'clickRowStyle' : '';
        }
        
        //点击右侧表格行
        onClickRightRow = (record) => {
            const { rightData } = this.state
            return {
                onClick: () => {
                    this.setState({
                        centerInfo: {},
                    })
                    this.props.form.resetFields()
                    if (record.ID) {
                        if (this.state.rowIds === "") {
                            this.setState({
                                rowIds: record.ID,
                                centerInfo: record,
                            });
                        } else {
                            if (this.state.rowIds !== record.ID) {
                                this.setState({
                                    rowIds: record.ID,
                                    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: [{
                            userID: sessionStorage.userData ? JSON.parse(sessionStorage.userData).userID : "",
                            ID: this.state.rowIds,
                            poisonID: values.poisonID,
                            hospID: values.getHop,
                            prescTypeID:this.state.prescriptsID,
                            startDate: values.getDateFrom ? moment(values.getDateFrom).format('YYYY-MM-DD') : "",
                            stopDate: values.getDateTo ? moment(values.getDateTo).format('YYYY-MM-DD') : "",
                        }],
                    }  
                    }else{
                       data = {
                        params: [{
                            userID: sessionStorage.userData ? JSON.parse(sessionStorage.userData).userID : "",
                            poisonID: values.poisonID,
                            prescTypeID:this.state.prescriptsID,
                            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: '03050155',
                        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.prescriptsID)
                                            return
                                        }
                                    }
                                    this.setState({
                                        checkedRight:true
                                    })
                                    this.getSubLocDatas(this.state.prescriptsID)
                                }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.prescriptsID)
                                                return
                                            }
                                        }
                                        this.setState({
                                            checkedRight:true
                                        })
                                        this.getSubLocDatas(this.state.prescriptsID)
                                    })
                                }
                            }
                        }
                    })
                }
            })
        }

     //删除管制分类
     delate=(e,record)=>{
         this.props.form.resetFields()
        let data = {}
        data = {
            params: [{
                userID: sessionStorage.userData ? JSON.parse(sessionStorage.userData).userID : "",
                ID:record.ID,
            }],
        }
        $http.post('urlS', this, {
            code: '03050156',
            data: data,
            success: function (res) {
                if (+res.errorCode === 0) {
                    message.success("删除成功")
                    this.getSubLocDatas(this.state.prescriptsID)
                    this.props.form.resetFields()
                }
            }
        })
    }
       //初始化信息
       initData = () => {
        this.props.form.resetFields()
        this.setState({
            centerInfo:{},
            rightData:[],
            disSave:true
        })
    }
    //可保存 编辑状态
    canSaveTab=(subID)=>{
        this.setState({
            disSave:false,
            prescriptsID:subID,
        })
        // this.getSubLocDatas(prescriptsID)
    }
        render() {
            const { getFieldDecorator } = this.props.form;
            let {  baseUnit, tempChildDis, OrdDaShow, topInfo, centerInfo,rightColumns } = this.state
                //医院
                let hosOp = []
                this.state.hospArr && this.state.hospArr.map((item) => {
                    hosOp.push(<Option key={item.id}  value={String(item.id)}>{item.descripts}</Option>)
                })
                //管制分类
                let poisonOp = []
                this.state.poisonArr && this.state.poisonArr.map((item) => {
                    poisonOp.push(<Option key={item.id} title={item.descripts} value={String(item.id)}>{item.descripts}</Option>)
                })
            return (
                <div>
                    <Row gutter={60} className="majorCategoriesDom" style={{ marginRight: "0" }}>
                        <Col span={24} style={{ paddingLeft: "6px", paddingRight: "0" }}>
                                <div>
                                    <Form>
                                    <Row gutter={60} >
                                            <Col span={10} style={paddRightCol}>
                                                <FormItem {...formItemLayoutType} label='医院'>
                                                    {getFieldDecorator('getHop', {
                                                        initialValue: centerInfo && centerInfo.hospID ? centerInfo.hospID : undefined,
                                                        rules: [{ required: true, message: '请选择医院' }],
                                                    })(
                                                        <Select
                                                            onSelect={this.handleStatus}
                                                        >
                                                            {hosOp}
                                                        </Select>
                                                    )}
                                                </FormItem>
                                            </Col>
                                            <Col span={10} style={paddRightCol}>
                                                <FormItem {...formItemLayoutType} label='管制分类'>
                                                    {getFieldDecorator('poisonID', {
                                                        initialValue: centerInfo && centerInfo.poisonID ? centerInfo.poisonID : undefined,
                                                        rules: [{ required: true, message: '请选择管制分类' }],
                                                    })(
                                                        <Select
                                                            onSelect={this.handleStatus}
                                                        >
                                                            {poisonOp}
                                                        </Select>
                                                    )}
                                                </FormItem>
                                            </Col>
                                        </Row>
                                        <Row gutter={60}>
                                        <Col span={10} style={paddRightCol}>
                                                <FormItem label='生效日期' {...formItemLayoutType}>
                                                    {getFieldDecorator('getDateFrom', {
                                                        initialValue: centerInfo&&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={10} style={paddRightCol}>
                                                <FormItem label='失效日期' {...formItemLayoutType}>
                                                    {getFieldDecorator('getDateTo', {
                                                        initialValue: centerInfo&&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 >
                                        </Row>
                                        <Row style={{paddingLeft:"48px"}}>
                                         <Col span={2} style={{ textAlign: "center", }}>
                                                 <Button key="submitc" type="primary" disabled={this.state.canSave&&this.state.rowId==""}  onClick={this.handleRightCancel}>清空</Button>
                                                 </Col>
                                                 <Col span={2} style={{ textAlign: "center", }}>
                                             <Button key="submits" type="primary" disabled={this.state.disSave} onClick={this.handleRightOk}>保存</Button>
                                                
                                                 </Col>
                                         </Row>
                                    </Form>
                                </div>
                                {/* disabled={this.state.rowId==""}  */}
                                <Checkbox checked={this.state.checkedRight} disabled={ this.state.rightData && this.state.rightData.length==0} onChange={this.changeCheckedRight} style={{ marginRight: "50px", float: "right" }}>仅显示生效</Checkbox>
                                <Table
                                    columns={rightColumns}
                                    pagination={false}
                                    rowClassName={this.setRowClassNames}
                                    onRow={this.onClickRightRow}
                                    dataSource={this.state.rightData}
                                    bordered={true}
                                    className="clearBackground"
                                    style={{
                                        height:store.getState().tableHeight.y - 24 + 'px'
                                    }}
                                />
                                  <CommonPagination size={this.state.sizeRight} 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>
                    <ColumnAuthoritysModel
                        clientWidth='800px'
                        compontName='PrescTypeLinkPoison'
                        configType="C"
                        onRef={this.onColumnRef}
                        reloadData={this.getMainTableColumns}
                    />
                </div>
            )
        }
    })
export default PrescriptClassification